Guide to AI and Data Courses · Lecture Notes

Chapter 15: Explainable AI and AI Ethics

A bank rejects your loan application and the only reason it gives is "our model did not approve it". Which piece of information decided it, what would have had to change for the answer to flip, and does the same model look at applicants from another neighborhood in the same way? This course asks these three questions: explaining a decision, measuring whether decisions are spread fairly across groups, and choosing among metrics that can contradict each other. These notes introduce the course and work through its three core ideas with small examples you can compute by hand.

Learning outcomes

Kinds of explanation
Tell interpretable models, black-box models, local and global explanations apart with examples.
Shapley values
Compute the Shapley values of a small three-feature model by hand by walking through all orderings, and check that they add up.
Counterfactuals
Find the smallest change that flips a decision for a linear score and present it as a path to approval.
Fairness metrics
Compute selection rate, recall and false positive rate per group from confusion matrices; show with base rates why the metrics cannot all hold together.
Place of the course
State what separates this course from machine learning, data science, cybersecurity and expert systems.

15.1What question does the course ask?

When can we trust an AI system's decision, and who is responsible for the outcome?

This course studies how to explain an AI system's decisions in a way people can understand, and how to make the system fair, reliable and accountable. The technical question is "why did the model decide this?"; the ethical question is "whom can this decision harm, and who is responsible?"

In machine learning, success is usually measured by one number, such as accuracy. A model that predicts correctly can still be unacceptable: if nobody can understand its decisions, if it makes systematically more errors on some groups, or if nobody is responsible for what it decides. This course takes seriously two questions that accuracy does not answer: "why did the model decide this?" and "whom can this decision harm, and how?"

The first question is technical and has two routes. On the first, an interpretable model is chosen from the start: a small decision tree or a linear model can be read directly. On the second, the model stays a black box (a deep network, a tree ensemble) and its behavior is explained afterwards. An explanation of one prediction is local; an explanation of the model's overall behavior is global.

The second question is as social as it is technical. Measuring something measurable (error rates across groups) is not the same as deciding what counts as fair (which metric, which threshold). The course teaches the first with numbers and says openly that the second is a value judgement. A good audit answers both together: explanation, fairness measurement and documentation (the model card) are parts of one piece of work.

15.1.1How this differs from machine learning

Training and evaluating a model is learned in Machine Learning. Here the model is taken as given and examined through an outside lens: what does the decision rest on, on whom do its errors pile up, who will audit it? That is why the course reuses tools such as the confusion matrix, but reads every number as tied to a group and to people.

15.1.2At a glance

CriterionExplainable AI and AI Ethics
Approachhuman-centered evaluation
Inputmodel, its data and context of use
Outputexplanation, audit report, principles
Success measureinterpretability, fairness, accountability
Math loadlow-medium
Data needsthe model's own data

15.2A short history

YearMilestone
2016ProPublica publishes an analysis arguing that the COMPAS recidivism score is biased against Black defendants.
2016Ribeiro, Singh and Guestrin introduce LIME: explaining one prediction with a simple local model.
2017Lundberg and Lee publish SHAP: feature contributions from game-theoretic Shapley values.
2018The EU General Data Protection Regulation (GDPR) takes effect, granting a right to contest automated decisions.
2018The Gender Shades study shows commercial face analysis systems err far more often on darker-skinned women.
2024The EU AI Act is adopted: systems are classified by risk level.

15.3Core concepts

The rest of the course is built on the concepts below. The following sections work through the most important ones with examples.

ConceptMeaning
Black-box modelA model whose inner workings people cannot follow.
InterpretabilityA model readable by design, such as a decision tree or a linear model.
Local explanationExplaining one prediction: LIME, SHAP values.
Global explanationThe model's overall behavior: feature importance, PDP.
Counterfactual"Had your income been this much, the loan would be approved."
Data biasImbalance in training data carried into decisions.
Fairness metricsDemographic parity, equal opportunity, calibration.
AccountabilityAuditing, logging and ownership of a decision.

15.4Explaining one prediction: Shapley values and counterfactuals

A credit model gives an applicant a 35 percent chance of approval; the average over all applicants is 50 percent. Which features account for the 15-point drop? The Shapley value answers this with an idea from game theory: the features are players on a team and the difference in the prediction is the payoff to be shared. A feature's share is the average of what it adds to the prediction when it joins the others in every possible order.

Definition 15.1 (Shapley value)

v(S) is the prediction when only the features in S are fixed at the applicant's values and the rest are filled in with the data average. The Shapley value of feature i is the average change it produces when added to the features before it, over all orderings: φi = average [ v(S ∪ {i}) − v(S) ]. Additivity: Σ φi = v(all) − v(∅).

Example 15.1: The share of three features

Features: debt ratio (D), income (I), credit history (H). The applicant's prediction is v(D,I,H) = 0.35; with nothing known the average is v(∅) = 0.50. The other values (illustrative): v(D) = 0.30, v(I) = 0.55, v(H) = 0.45, v(D,I) = 0.40, v(D,H) = 0.25, v(I,H) = 0.55.

  1. Orderings. Three features can be added in 3! = 6 orders. In each order a feature's contribution is the v after it is added minus the v before. For the order D, I, H: D contributes 0.30 − 0.50 = −0.20; I contributes 0.40 − 0.30 = +0.10; H contributes 0.35 − 0.40 = −0.05.
  2. Contributions in all six orders.
    OrderDIH
    D, I, H−0.20+0.10−0.05
    D, H, I−0.20+0.10−0.05
    I, D, H−0.15+0.05−0.05
    I, H, D−0.20+0.050.00
    H, D, I−0.20+0.10−0.05
    H, I, D−0.20+0.10−0.05
  3. Average. φD = −1.15/6 ≈ −0.19; φI = 0.50/6 ≈ +0.08; φH = −0.25/6 ≈ −0.04.
  4. Check. −0.19 + 0.08 − 0.04 = −0.15 = 0.35 − 0.50. The shares divide the difference exactly.

Reading: the debt ratio pulls the approval probability down by about 19 points, income pushes it up by 8, and credit history pulls it down by 4. Telling the applicant "your rejection is mainly due to your debt ratio" is grounded this way.

With n features there are n! orderings, so the exact computation quickly becomes impossible; SHAP therefore computes Shapley values for special structures such as tree models by clever shortcuts, or approximately by sampling. For the same reason, calling the result "exact" is a mistake.

15.4.1Counterfactual explanations

For the applicant the most useful question is often "what would have had to change for me to be approved?" A counterfactual explanation finds the smallest change that flips the decision and points to a path to approval.

Example 15.2: The smallest change that flips the decision

A linear score (illustrative): s = 0.04 · i − 5 · d, where i is income (thousands) and d is the debt ratio. The loan is approved if s ≥ 0. The applicant has i = 40, d = 0.5.

  1. Decision. s = 0.04 · 40 − 5 · 0.5 = 1.6 − 2.5 = −0.9: rejected.
  2. Only the debt ratio changes. 1.6 − 5d ≥ 0 gives d ≤ 0.32.
  3. Only income changes. 0.04 i − 2.5 ≥ 0 gives i ≥ 62.5.
  4. Both change. With i = 50, 2.0 − 5d ≥ 0 gives d ≤ 0.40.

Three paths can be offered to the applicant. Which one is realistic depends on the context: features that cannot be changed, such as age, are not used in the advice.

Common mistake

Taking a Shapley value, or a feature contribution, as evidence of causation. The share above describes how the model divides its prediction; it does not say whether lowering the debt ratio in the real world would make the borrower any more creditworthy. Explanation methods are also approximations and can mislead.

15.5Measuring fairness across groups

A model can have high average accuracy while its errors pile up on one group. The first job of a fairness analysis is to split errors and decisions by the protected attribute (gender, age, region, for example) and compare. The course's three metrics are:

Definition 15.2 (Three group metrics)

Demographic parity: the rate of favorable decisions (approval) should be equal across groups. Equal opportunity: among those who truly deserve it, the approval rate (recall) should be equal. Calibration (equal precision): of those approved, the share who truly deserve it should be equal across groups.

Example 15.3: Confusion matrices of two groups

Two groups of 200 applicants each (the values are illustrative). "Positive" means the person will repay the loan; if the model approves, the prediction is positive.

GroupTPFPFNTN
A80204060
B45155585
  1. Selection rate. A: (80 + 20)/200 = 0.50; B: (45 + 15)/200 = 0.30. Ratio 0.30/0.50 = 0.60.
  2. Recall (equal opportunity). A: 80/(80 + 40) ≈ 0.67; B: 45/(45 + 55) = 0.45. The gap is about 0.22.
  3. False positive rate. A: 20/(20 + 60) = 0.25; B: 15/(15 + 85) = 0.15.
  4. Precision (calibration). A: 80/100 = 0.80; B: 45/60 = 0.75.
  5. Accuracy. A: 140/200 = 0.70; B: 130/200 = 0.65.

Reading: group B's approval rate is only 60 percent of A's. Of the B applicants who deserve a loan only 45 percent get one; in A the figure is 67 percent. The "80 percent rule" known from US hiring practice treats a ratio of selection rates below 0.80 as a warning sign; here the ratio is 0.60. Precision, on the other hand, is close in the two groups (0.80 and 0.75).

The same model on the same data looks different depending on the metric: by precision it is close to fair, by recall it is clearly unfair. A report is therefore not a single "fairness score" but a table across groups and an explanation of why each metric was chosen.

15.5.1Reducing bias

When a disparity is found there are three stages at which to intervene: pre-processing (reweighting or balancing the data), in-processing (adding a fairness constraint to the loss) and post-processing (adjusting the decision threshold per group). Every intervention that fixes one thing can disturb another metric or accuracy, so the result must be measured again.

Common mistake

Believing that dropping the protected attribute (gender, race) from the data makes a model fair. Proxy features such as postal code, school or name can carry the same information. Fairness is measured not by whether the attribute is in the model but by how decisions are distributed across groups, and for that the attribute has to be available in the evaluation data.

15.6Why fairness metrics conflict

The previous section had three metrics. It would be nice to satisfy all of them at once, but most of the time it is impossible. The reason lies in base rates. The base rate is the share of true positives in a group (for example, the share of people who will repay). When base rates differ between groups, a model that is not perfect cannot have calibration and equal error rates together. The COMPAS debate was exactly this conflict: ProPublica pointed to the difference in false positive rates, while the company that produced the risk score pointed to calibration.

Definition 15.3 (Base rate and error rates)

With base rate p, precision P and false negative rate FNR, the false positive rate is FPR = p/(1 − p) · (1 − P)/P · (1 − FNR). If two groups have the same P and FNR, then as long as p differs, FPR differs too.

Example 15.4: Same precision, same recall, different false positive rate

In both groups precision is P = 0.8 and the false negative rate is FNR = 0.2. Group A has 100 people with base rate 0.5; group B has 100 people with base rate 0.2 (the values are illustrative).

  1. Group A. 50 positives, 50 negatives. Recall is 0.8, so TP = 40, FN = 10. The number of positive predictions is TP/P = 40/0.8 = 50, so FP = 10 and TN = 40. The false positive rate is 10/50 = 0.20.
  2. Group B. 20 positives, 80 negatives. TP = 16, FN = 4; positive predictions 16/0.8 = 20, FP = 4, TN = 76. The false positive rate is 4/80 = 0.05.
  3. Check with the formula. A: (0.5/0.5) · (0.2/0.8) · 0.8 = 0.20; B: (0.2/0.8) · (0.2/0.8) · 0.8 = 0.05. Same as the counts.
  4. Selection rate. A: 50/100 = 0.50; B: 20/100 = 0.20. Demographic parity fails as well.

Precision and recall are equal in the two groups; yet a member of A who will not repay is four times as likely as a member of B to be approved by mistake. Except for a perfect predictor (P = 1 and FNR = 0), these cannot all be equalized.

The practical consequence is that choosing a metric is not a mathematical detail but a value judgement. When a false positive is very costly (wrongful detention, for instance), equal error rates come first; when the score should "mean the same thing in every group", calibration does. The choice should be made with the people affected and with domain experts, and written into the model card with its reasons.

Common mistake

Concluding that the model is "broken" when one metric fails, or that the work is done once one metric is satisfied. When base rates differ between groups, violating one of the metrics is mathematically unavoidable; the real work is to report which one was chosen, why, and what happens to the others. Differences in base rates are also often the result of past inequality, and that deserves thought before a model scales it up.

15.7How is the course taught?

15.7.1A typical workflow

Set thecontextwho is hit,what risk?Auditthe datacoverage,biasExplainthe modelSHAP, LIME,counterfactualMeasurefairnesserror ratesby groupDocument,monitormodel card,audit
Figure 15.1: A typical workflow in Explainable AI and AI Ethics

A bank's credit model rejects an application. SHAP values show the rejection comes mostly from the debt ratio; a comparison across groups reveals markedly higher rejection rates in some neighborhoods. The team removes the feature that indirectly encodes neighborhood and documents the decision in the model card.

15.7.2Topics over the semester

  1. Interpretable models: linear models and trees
  2. Feature importance and partial dependence (PDP, ICE)
  3. Local explanations: LIME
  4. Shapley values and SHAP
  5. Saliency maps for deep networks
  6. Counterfactual explanations and recourse
  7. Evaluating explanations: faithfulness and stability
  8. Fairness metrics and the conflicts between them
  9. Bias mitigation: pre-, in- and post-processing
  10. Privacy: anonymization and differential privacy
  11. Accountability: model cards, datasheets, audits
  12. Regulation: GDPR, KVKK and the EU AI Act

This is a typical semester; the order and coverage vary between universities.

15.7.3Skills you will gain

  • explaining models with SHAP and LIME
  • measuring group fairness with Fairlearn
  • generating counterfactual explanations
  • writing a model card
  • assessing the risks of a system

15.7.4Try it yourself

The Try It: Is the Credit Model Fair to Both Groups? slide in the presentation lets you solve a typical problem of this course yourself: The model scores each application from 0 to 100; scores above the threshold are approved. Group B scores lower because of historical data. Move the thresholds and watch how two fairness metrics change.

15.8Are you ready for this course?

15.8.1Prerequisites

CourseWhy it is needed
Programmingtraining models in Python and analyzing results
Algorithmic Game Theorythe Shapley value: the theoretical root of SHAP explanations
Philosophy or lawethical theories, personal data rights and the notion of responsibility

15.8.2Ask yourself

For every "no", the right-hand column shows where to start. If you can say "yes" to most of them, you are ready.

QuestionIf not, start with
Can you train a classifier in Python and evaluate it on a test set?Machine Learning
Can you compute false positive and false negative rates?A short reading on confusion matrices and classification metrics
Can you explain conditional probability and base rates?Probability and Statistics
Can you explain what the Shapley value means in game theory?The Shapley value topic of the Algorithmic Game Theory course

15.9Neighboring courses

Expert SystemsMachine LearningData ScienceAI in CybersecurityMedical ImagingExplainable AI & Ethics
subfieldbuilds onshares methodsapplication
Figure 15.2: Neighbors of Explainable AI and AI Ethics and the kind of relation

15.9.1Where it overlaps

RelationCourseShared ground
shares methodsShares methods with Machine Learningmodel explanation, feature importance
shares methodsShares methods with Expert Systems and Knowledge Representationexplainable decisions through readable rules
shares methodsShares methods with Medical Image Processingexplainability and accountability in diagnosis
shares methodsShares methods with Data Sciencedata bias, fairness metrics
shares methodsShares methods with AI in Cybersecurityrobustness, adversarial examples

15.9.2Where it differs

  • Machine Learning: ML focuses on the model predicting correctly; this course asks why it predicts and whom it affects, and how.
  • Data Science: Data science draws conclusions from data; this course checks whether those conclusions are biased, fair or explainable.
  • AI in Cybersecurity: Cybersecurity protects against attackers; this course studies the harm a system does to people even without an attack.
  • Expert Systems and Knowledge Representation: Expert systems are already transparent through their rules; this course seeks ways to explain black-box models after the fact.

15.10In practice

15.10.1Applications

AreaWhat is done
Credit decisionsExplaining a rejection to the applicant.
Medical diagnosisShowing the physician what the model looked at.
HiringGender and age bias in résumé screening.
Justice and public sectorAuditing whether risk scores are fair.
Face recognitionMeasuring error gaps between groups.
Regulatory complianceDocumentation for the EU AI Act and KVKK.

15.10.2Risks and ethics

RiskExplanation
Misleading explanationsLIME and SHAP are approximations; an adversarial model can look innocent to the explainer while hiding its real decision rule.
Ethics washingAn ethics principles document or a single fairness score can serve as a showcase in place of real auditing.
The wrong fairness metricChoosing a metric is a value judgement: COMPAS could look fair under one metric and biased under another.
Over-trusting explanationsA plausible-looking explanation can lead users to follow a wrong decision without question.

15.10.3Tools and datasets

Tools: SHAP, LIME, Captum, InterpretML, Fairlearn, AI Fairness 360, What-If Tool.

Well-known datasets: COMPAS (ProPublica), Adult (income), German Credit, CelebA, Pilot Parliaments Benchmark.

In this course datasets are often used to expose a problem: COMPAS and Adult are the classic examples of how bias is measured.

15.11Common misconceptions

Common mistake

Removing the protected attribute (gender, race) is enough.

Proxy features such as postal code or name can carry the same information; the bias remains.

Common mistake

An algorithm is neutral because it works with numbers.

A model learns the bias in past decisions from the data and scales it up.

Common mistake

An explanation shows how the model really works.

Methods such as LIME and SHAP are approximations; the explanation itself can mislead.

Common mistake

All fairness metrics can be satisfied at once.

When base rates differ between groups, calibration and equal error rates usually cannot hold together.

15.12Summary

  • Explainability asks "why did the model decide this?" and ethics asks "whom can this decision harm, and who is responsible?"; accuracy answers neither.
  • The Shapley value gives a feature's contribution as the average of what it adds over all orderings; the contributions sum to the difference between the prediction and the average, but they are computed approximately and do not show causation.
  • A counterfactual explanation finds the smallest change that flips a decision and points the applicant to a way forward; features that cannot be changed stay out of the advice.
  • Fairness is computed from confusion matrices group by group: selection rate (demographic parity), recall (equal opportunity), precision (calibration); dropping the protected attribute is not enough because of proxy features.
  • When base rates differ, calibration and equal error rates cannot hold together; choosing a metric is a value judgement and must be documented.

15.13Test Yourself

  1. In a two-feature model v(∅) = 0.5, v(a) = 0.6, v(b) = 0.4, v(a,b) = 0.7. Compute the Shapley values of a and b and check that they add up.

    Answer

    There are two orders. For a: order a, b gives 0.6 − 0.5 = 0.1; order b, a gives 0.7 − 0.4 = 0.3; average φa = 0.2. For b: order a, b gives 0.7 − 0.6 = 0.1; order b, a gives 0.4 − 0.5 = −0.1; average φb = 0. Total 0.2 + 0 = 0.2 = 0.7 − 0.5.

  2. Score s = 0.04 · i − 5 · d, approved if s ≥ 0. An applicant has i = 30, d = 0.3. What is the decision? If rejected, what is the smallest change in income alone, or in the debt ratio alone?

    Answer

    s = 1.2 − 1.5 = −0.3: rejected. Income alone: 0.04 i ≥ 1.5 gives i ≥ 37.5. Debt ratio alone: 5d ≤ 1.2 gives d ≤ 0.24.

  3. In group X, 20 of 50 applicants are approved; in group Y, 48 of 80. Compute the selection rates and their ratio. What does the 80 percent rule say?

    Answer

    X: 20/50 = 0.40; Y: 48/80 = 0.60. The ratio is 0.40/0.60 ≈ 0.67, below 0.80: a warning sign that calls for a closer look (it is not proof of discrimination by itself).

  4. In group X, 18 of the 30 people who deserve approval get it; in group Y, 30 of 40. What is the equal opportunity gap? Which group is disadvantaged?

    Answer

    Recalls: for X 18/30 = 0.60, for Y 30/40 = 0.75. The gap is 0.15. Deserving applicants in X are rejected more often, so X is disadvantaged.

  5. A team removes the gender column from a hiring model and says the model is now fair with respect to gender. Why is that not enough, and what should be done?

    Answer

    Features such as school, hobbies or words in the résumé can act as proxies for gender, and the model will still learn the bias in past hiring. Fairness has to be measured by looking at how decisions are distributed between women and men (selection rate, recall, false positive rate), and for that the gender information must be kept in the evaluation data.

  6. The base rate is 0.5 in group A and 0.2 in group B; in both groups precision is 0.75 and the false negative rate is 0.2. Compute the false positive rates with the formula. What does this show?

    Answer

    A: (0.5/0.5) · (0.25/0.75) · 0.8 ≈ 0.267. B: (0.2/0.8) · (0.25/0.75) · 0.8 ≈ 0.067. Although precision and recall are equal, the false positive rates differ by a factor of four: when base rates differ, calibration and equal error rates cannot hold together.

15.14After this course

This course adds a lens to every applied course: explaining a diagnosis in medical image processing, fooling a model in cybersecurity and monitoring a model in MLOps rest on the same questions. On the technical side you can continue with causal inference and adversarial robustness; on the social side, with law and policy.

Related careers: Responsible AI specialist, Model auditor, AI policy and compliance specialist, Data scientist, Researcher.

15.15Further reading

  • C. Molnar, Interpretable Machine Learning (2nd ed., 2022; online): an easy-to-use, example-rich reference for Shapley values, LIME and counterfactual explanations.
  • S. Barocas, M. Hardt and A. Narayanan, Fairness and Machine Learning (MIT Press, 2023): a rigorous treatment of fairness metrics and the conflicts between them.
  • C. O'Neil, Weapons of Math Destruction (2016): a read that needs no mathematics, showing the social harm of algorithmic decisions through real cases.

15.16References

  1. Molnar, Interpretable Machine Learning, 2nd ed., self-published (online), 2022.
  2. Barocas, Hardt and Narayanan, Fairness and Machine Learning: Limitations and Opportunities, MIT Press, 2023.
  3. O'Neil, Weapons of Math Destruction, Crown, 2016.
  4. Ribeiro, Singh and Guestrin, "Why Should I Trust You?: Explaining the Predictions of Any Classifier", KDD, 2016.
  5. Lundberg and Lee, "A Unified Approach to Interpreting Model Predictions", NeurIPS, 2017.

Related pages: Slides · Slides (PDF) · Course page