Lesson 05 · 45 minutes
Explain a model's decisions and keep a record of each one
- Find which inputs a model relies on with permutation importance
- Give the main reasons for one decision from a linear model
- Write an explanation record for every decision and check that none is missing
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
An applicant of Harbour Credit was declined and wrote to ask why. Your lead looks at the case and finds that LoanScore stored the decision and nothing else. "A person at the bank can say what they think happened. Next time I want the reasons on file, for every decision, and a check that tells me if one is missing." You get the model of lesson 4. You write the code that explains it and the checker that audits the record.
Recall
Lesson 4: the model was accurate for both groups and the selection rates differed. What did the group threshold change?
It lowered the approval threshold of group B from 0.50 to 0.36. The ratio reached 0.80, accuracy stayed at 0.87, and the number of bad loans rose from 25 to 28.
Lesson 1: who is accountable for an AI system, and why does that matter for an explanation?
The owner. An explanation is given by somebody. When an applicant contests a decision, the owner answers, and the record is what the owner shows.
The idea
Explainability means that a person can see what drove a model's output. It serves three uses, and each one asks for a different record.
| Use | Who | What they need |
|---|---|---|
| Review | The builder and the reviewer | Which inputs the model relies on |
| Contest | The affected person and the officer who answers them | The main reasons for one decision, in plain terms |
| Audit | A later reviewer | A record of each decision that can be checked against the decision itself |
Two kinds of explanation answer these needs. A global explanation says what matters over all decisions. Permutation importance is one: shuffle the values of one input among the rows, so that the link between that input and the outcome breaks, and measure how far accuracy falls. A big fall means that the model relied on the input. A local explanation says why one decision came out as it did. For a linear model (such as logistic regression) it is exact for the model: each input's value, rescaled, times its coefficient, adds to or takes from the score. The sum of these pushes and the intercept gives the log-odds, and the biggest pushes against the outcome are the reasons.
- Decision → Reasons: the two biggest pushes
- Reasons → Record: id, reasons, model version
- Record → Check: one record for each decision
- Check → Audit: a person reads both
An explanation describes the model, not the world. "Debt ratio pushed the score down" does not say that debt caused the default. For models that are not linear, methods such as SHAP and LIME give approximate local reasons. The approximation can be wrong, and the record should say which method made it.
Worked example
Work in ~/krlab/ai-governance with the environment on. This lesson uses fairness.py from lesson 4.
1. Write the explainer
A word first. In this course a decision is the recommendation that LoanScore gives to the credit officer: approve or decline. The officer makes the final choice (lesson 7), and the officer's reasons go to the applicant. So the column approved of decisions.csv holds the model's recommendation to approve (1) or not (0), and the record explains that recommendation.
The file has three parts. Read the notes of each part before you read its code.
- Importance (
importance).np.random.RandomState(0)is a random generator with a fixed start.rng.permutation(column)shuffles a column..copy()makes a copy, so the shuffle does not change the original. - One decision (
explain_one).model[0]andmodel[-1]are the first and the last step of a pipeline: the scaler and the logistic regression.coef_holds the coefficients of the regression.np.argsort(values)gives the positions of the values from the smallest to the largest. - Writing the files (the part under
__main__).json.dumpsturns a dictionary into one line of JSON text, and a file of such lines is called JSON Lines.enumerate(X_test)gives a counter with each row.zip(a, b)pairs the items of two lists. In{"id": ..., **record}, the**copies the entries of the dictionaryrecordinto the new one. Thelambda(lesson 3) insortedsorts the pairs by their second item, largest first.
CUTS holds the cut-off of each group from lesson 4: group B is approved from a probability of 0.36. The record keeps the probability and the cut-off that was used, so a reviewer can see that an approval at 0.45 came from the cut-off 0.36 of group B. A different cut-off for each group is a choice that your legal team must approve first (lesson 4).
explain.py
"""explain.py: which inputs matter to the model, and the reasons for each decision.
python3 explain.py prints the importance of each input and writes decisions.csv and explanations.jsonl
"""
import csv
import json
import numpy as np
from fairness import LOANS, fit, load, split
MODEL_NAME = "loanscore-1.0"
CUTS = {"A": 0.50, "B": 0.36} # the cut-off of each group from lesson 4 (a choice that legal must approve first)
def importance(model, X, y, repeats=10, seed=0):
"""Permutation importance: how much accuracy falls when one input column is shuffled."""
rng = np.random.RandomState(seed)
base = (model.predict(X) == y).mean()
drops = []
for j in range(X.shape[1]):
runs = []
for _ in range(repeats):
shuffled = X.copy()
shuffled[:, j] = rng.permutation(shuffled[:, j])
runs.append(base - (model.predict(shuffled) == y).mean())
drops.append(float(np.mean(runs)))
return drops
def explain_one(model, row, features, cut=0.50):
"""Reasons for one decision from a linear model: each input's push on the log-odds, strongest first."""
scaler, linear = model[0], model[-1]
push = linear.coef_[0] * scaler.transform([row])[0]
probability = float(model.predict_proba([row])[0, 1])
decision = "approve" if probability >= cut else "decline"
order = np.argsort(push if decision == "decline" else -push)
reasons = [{"feature": features[j], "push": round(float(push[j]), 2)} for j in order[:2]]
return {"decision": decision, "probability": round(probability, 2), "cut": cut, "reasons": reasons, "model": MODEL_NAME}
if __name__ == "__main__":
X, y, g = load(**LOANS)
with open(LOANS["path"], newline="") as f:
ids = np.array([r["id"] for r in csv.DictReader(f)])
X_train, X_test, y_train, y_test, _, g_test, _, id_test = split(X, y, g, ids)
model = fit(X_train, y_train)
for name, drop in sorted(zip(LOANS["features"], importance(model, X_test, y_test)), key=lambda p: -p[1]):
print(f"{name:<15}{drop:.2f}")
with open("decisions.csv", "w", newline="") as d, open("explanations.jsonl", "w") as e:
d.write("id,group,approved\n")
for i, row in enumerate(X_test):
record = explain_one(model, row, LOANS["features"], CUTS[g_test[i]])
d.write(f"{id_test[i]},{g_test[i]},{int(record['decision'] == 'approve')}\n")
e.write(json.dumps({"id": str(id_test[i]), **record}) + "\n")
print("wrote decisions.csv and explanations.jsonl,", len(X_test), "decisions")python explain.pyincome 0.22
debt_ratio 0.12
history_years 0.07
wrote decisions.csv and explanations.jsonl, 300 decisionsIncome matters most. The script also wrote decisions.csv, with one row for each of the 300 test decisions, and explanations.jsonl, with one record for each.
2. Read two records
head -1 prints the first line of a file. grep -m 1 decline prints the first line that holds the word decline.
head -1 explanations.jsonl
grep -m 1 decline explanations.jsonl{"id": "L0994", "decision": "approve", "probability": 1.0, "cut": 0.5, "reasons": [{"feature": "income", "push": 3.87}, {"feature": "history_years", "push": 1.68}], "model": "loanscore-1.0"}
{"id": "L0673", "decision": "decline", "probability": 0.45, "cut": 0.5, "reasons": [{"feature": "history_years", "push": -0.89}, {"feature": "debt_ratio", "push": -0.21}], "model": "loanscore-1.0"}The first applicant was approved, and income gave the biggest push (+3.87). The second was declined at probability 0.45, below the cut-off 0.5 that the record keeps. Both reasons pushed down.
A decline below the cut-off is not a mystery, and the officer can say: "your credit history is short for this model".
3. Write the record checker
The checker joins decisions.csv and explanations.jsonl by id. It finds a decision with no record, a record that disagrees with its decision, a record whose decision is on the wrong side of its own cut-off (a probability equal to the cut-off passes, because the probability is rounded), a record with no reasons or no model version, two records for one decision, and a record for a decision that does not exist. keys() - keys() gives the keys that are in the first set and not in the second.
explain_check.py
"""explain_check.py: every decision needs one explanation record that agrees with it.
python3 explain_check.py decisions.csv explanations.jsonl
"""
import csv
import json
import sys
from govlib import finish
def off_cut(record):
"""True when the decision is on the wrong side of the cut-off. The probability is rounded, so equal passes."""
below, above = record["probability"] < record["cut"], record["probability"] > record["cut"]
return below if record["decision"] == "approve" else above
def problems(decisions_path, records_path):
with open(decisions_path, newline="") as f:
decisions = {row["id"]: row for row in csv.DictReader(f)}
records, found = {}, []
with open(records_path) as f:
for line in f:
record = json.loads(line)
if record["id"] in records:
found.append(f"{record['id']}: two explanation records")
records[record["id"]] = record
for id_, row in decisions.items():
record = records.get(id_)
if record is None:
found.append(f"{id_}: no explanation record")
elif record["decision"] != ("approve" if row["approved"] == "1" else "decline"):
found.append(f"{id_}: the record says {record['decision']}, the decision differs")
elif off_cut(record):
found.append(f"{id_}: the record decides {record['decision']} at {record['probability']} with cut-off {record['cut']}")
elif not record["reasons"]:
found.append(f"{id_}: the record has no reasons")
elif not record.get("model"):
found.append(f"{id_}: the record names no model version")
for id_ in sorted(records.keys() - decisions.keys()):
found.append(f"{id_}: a record for a decision that does not exist")
return found
if __name__ == "__main__":
finish(problems(sys.argv[1], sys.argv[2]))python explain_check.py decisions.csv explanations.jsonlproblems: 04. Lose two records on purpose
sed '5d;9d' prints a file without its lines 5 and 9.
sed '5d;9d' explanations.jsonl > lost.jsonl
python explain_check.py decisions.csv lost.jsonlPROBLEM L0673: no explanation record
PROBLEM L0307: no explanation record
problems: 2The checker names the two decisions that have no record. An auditor who finds such a gap asks a fair question: what else is missing?
Your turn
A month later, the clinic team of Harbour Credit (invented) sends one batch for review: eight decisions and their records. Save both files, then use the checker on them. There are no steps.
decisions-q3.csv
id,group,approved
Q01,A,1
Q02,B,0
Q03,A,0
Q04,B,1
Q05,A,1
Q06,B,0
Q07,A,0
Q08,B,1explanations-q3.jsonl
{"id": "Q01", "decision": "approve", "probability": 0.91, "cut": 0.5, "reasons": [{"feature": "income", "push": 2.1}], "model": "loanscore-1.0"}
{"id": "Q02", "decision": "decline", "probability": 0.62, "cut": 0.5, "reasons": [{"feature": "debt_ratio", "push": -1.4}], "model": "loanscore-1.0"}
{"id": "Q03", "decision": "approve", "probability": 0.64, "cut": 0.5, "reasons": [{"feature": "income", "push": 0.9}], "model": "loanscore-1.0"}
{"id": "Q05", "decision": "approve", "probability": 0.77, "cut": 0.5, "reasons": [], "model": "loanscore-1.0"}
{"id": "Q06", "decision": "decline", "probability": 0.31, "cut": 0.5, "reasons": [{"feature": "history_years", "push": -0.8}], "model": "loanscore-0.9"}
{"id": "Q07", "decision": "decline", "probability": 0.12, "cut": 0.5, "reasons": [{"feature": "income", "push": -2.5}], "model": ""}
{"id": "Q08", "decision": "approve", "probability": 0.71, "cut": 0.5, "reasons": [{"feature": "debt_ratio", "push": 1.2}], "model": "loanscore-1.0"}
{"id": "Q99", "decision": "approve", "probability": 0.88, "cut": 0.5, "reasons": [{"feature": "income", "push": 1.7}], "model": "loanscore-1.0"}Then answer from your own runs on the files of this lesson and on the batch.
Last, decide: is the record for Q06 a problem? It names the model loanscore-0.9, and the current model is loanscore-1.0. Write why the checker accepts it, and what rule you would add.
Check yourself
Why is it not enough to store only the decision?
When someone contests the decision, nobody can say what drove it, and the model may have changed since. The record fixes the reasons, the probability and the model version at the time. It is also the evidence for a reviewer who wants to check that the decisions follow the policy.
Permutation importance says that income matters most. Does that mean that income causes repayment?
No. It says that this model relies on income. The model learned a pattern from the data, and a pattern is not a cause. Income could stand in for other things, and inputs that move together share the importance between them.
The checker passes, and a record says "income, push +3.1" for a decision that was really made by a different model. Can the checker find it?
No. It checks that records exist and agree in form with the decisions. It cannot tell whether the reasons are true. A reviewer can sample records and recompute the reasons from the stored model version. Keep the model files and give each version a number (lesson 10).
Which use of explainability needs the most care in plain language: review, contest or audit?
Contest. The reader is the affected person, who is not an engineer. "debt_ratio push -0.21" must become a sentence such as "your debts are high compared with your income". The engineer provides the number and a person writes the sentence.
Field notes
- Explanations can leak. A record that shows the exact reason for a decline helps a person who wants to game the model. Decide what the affected person sees and what only the reviewer sees.
- Keep the stored record small and stable: id, decision, probability, cut-off, reasons, model version, time. Store the input values too if your data rules allow it, because a later reviewer will want to recompute.
- The EU AI Act asks providers of high-risk systems for automatic logging and for human oversight that works (lesson 6). A record like this one supports both. Take the exact duties from the current official text.
- A complex model needs an approximate method, and its explanation can be unstable: the same case can get different reasons on another run. Fix the random seeds, store the method and its version, and test that the explanation is stable on a sample.
- Know why you keep reasons. GDPR Article 22 and Article 15(1)(h), AI Act Article 86 and, for credit in the US, the adverse-action notice of ECOA all ask for an explanation of an individual decision. Take the exact duty from the current official text and let legal decide which one applies.
- Run the record check in the build, as lesson 13 does. A decision log with a gap is an audit finding, and a script finds it in a second.