AI and machine learning · Intermediate · 30 min
Write a model card for a model you ship
By Padding · Updated 18 Nov 2026
Python 3.15 (python:3.15-slim) · standard library only
You will write a model card for a loan-approval classifier that covers intended and out-of-scope uses, data gaps, results by group, failure cases, privacy, ownership and review, with a Python script that fills the metrics from the evaluation file and fails when the card is out of date.
On this page
A model card is a short document that ships with a model and tells the people around it what it is for, what it must not be used for, how well it works for whom, and who to call when it goes wrong. It is one of the cheapest responsible-AI controls you have. A loan officer who reads "this score never declines anyone on its own" behaves differently from one who sees only a number on a screen.
The idea comes from the paper Model Cards for Model Reporting (Mitchell and others, 2019), which proposed a fixed set of sections: model details, intended use, the factors results are broken down by, metrics, training and evaluation data, results, ethical considerations, and caveats. Hugging Face uses the same idea for every model on its Hub, where the card is the repository's README.md. This tutorial uses that structure, trimmed to what a team shipping one internal model needs.
The example is the loan-approval classifier from the Fairlearn tutorial: a logistic regression trained on 20,000 past loan officer decisions, using income, debt ratio, years employed, part-time work and distance to a branch. It is given a made-up lender, Ashgrove Microfinance, so the card has something concrete to say. Everything that tutorial measured, including that the officers' own decisions were biased, belongs in the card. Cards go stale the moment someone re-evaluates the model and forgets to update the numbers, so the metrics tables are not typed by hand. A small Python script builds them from the evaluation results file, flags groups the model serves worse, and fails in CI when the card no longer matches the results.
Step 1 · Set up the project and the evaluation results
Create a throwaway folder for the card:
mkdir -p ~/model-card-demo/sections
cd ~/model-card-demoThe card needs two inputs. card.json holds the facts that change rarely: the model's name, version, owner, contact and next review date, and which results file to read.
cat > card.json <<'JSON'
{
"name": "Ashgrove loan pre-approval",
"version": "1.0.0",
"owner": "Credit Models team",
"contact": "credit-models@ashgrove.example",
"review_by": "2027-05-18",
"eval_file": "eval.json"
}
JSONeval.json holds the evaluation results: metrics on the whole test set and the same metrics for each group, plus the gap above which a group is flagged. The keys are the ones render_card.py reads, and the group sizes match the Fairlearn tutorial's 6,000-row test set. The metric values are a round-number sample, so your own run will give different numbers; the snippet after this block writes the real ones.
cat > eval.json <<'JSON'
{
"model_version": "1.0.0",
"evaluated_on": "2026-11-12",
"test_rows": 6000,
"gap_threshold": 0.05,
"overall": {"accuracy": 0.84, "selection_rate": 0.41, "false_negative_rate": 0.18, "precision": 0.81},
"by_group": {
"gender": {
"female": {"count": 2997, "accuracy": 0.83, "selection_rate": 0.33, "false_negative_rate": 0.27, "precision": 0.83},
"male": {"count": 3003, "accuracy": 0.85, "selection_rate": 0.46, "false_negative_rate": 0.13, "precision": 0.80}
},
"region": {
"rural": {"count": 2385, "accuracy": 0.82, "selection_rate": 0.30, "false_negative_rate": 0.29, "precision": 0.82},
"urban": {"count": 3615, "accuracy": 0.85, "selection_rate": 0.46, "false_negative_rate": 0.14, "precision": 0.81}
}
}
}
JSONSelection rate is the share of applicants the model pre-approves. The label is the officers' past decision (approved), so the false negative rate is the share of applicants the officers approved but the model did not. It measures disagreement with past officers, not missed repayments, and the officers' decisions are the ones the Fairlearn tutorial found biased against women and rural applicants.
If you have worked through the Fairlearn tutorial, you can write this file from its by_group.py, which already has test, pred and the metrics dictionary (with the keys n, selection_rate, false_neg_rate, precision and accuracy). Add these lines at the end of that script. They build one MetricFrame per sensitive column and rename Fairlearn's keys to the names render_card.py reads:
import json
NAMES = {
"n": "count",
"selection_rate": "selection_rate",
"false_neg_rate": "false_negative_rate",
"precision": "precision",
"accuracy": "accuracy",
}
def tidy(row):
out = {}
for key, value in row.items():
name = NAMES[key]
out[name] = int(value) if name == "count" else round(float(value), 3)
return out
frames = {
column: MetricFrame(metrics=metrics, y_true=test["approved"], y_pred=pred,
sensitive_features=test[column])
for column in ("gender", "region")
}
overall = tidy(frames["gender"].overall)
overall.pop("count")
results = {
"model_version": "1.0.0",
"evaluated_on": "2026-11-12",
"test_rows": int(len(test)),
"gap_threshold": 0.05,
"overall": overall,
"by_group": {
column: {str(group): tidy(row) for group, row in frame.by_group.iterrows()}
for column, frame in frames.items()
},
}
with open("eval.json", "w", encoding="utf-8") as f:
json.dump(results, f, indent=2)Copy the eval.json it writes into ~/model-card-demo. The overall values do not depend on the sensitive column, so taking them from the gender frame is safe.
Check it worked
python3 -m json.tool card.json > /dev/null && python3 -m json.tool eval.json > /dev/null && echo "both files are valid JSON"The command prints both files are valid JSON. If it prints a line and column number instead, that is where the JSON is broken, usually a missing comma.
Step 2 · Render the metrics tables from the evaluation file
Write render_card.py. It reads card.json, the results file and the written sections in sections/, builds the evaluation tables, and writes MODEL_CARD.md. A group's value is shown in bold, with its difference from the overall value, when the difference is larger than gap_threshold. Sections you have not written yet appear as a visible "Not written yet" line, so a half-finished card never looks finished.
cat > render_card.py <<'PY'
import argparse
import datetime
import json
import sys
from pathlib import Path
SECTIONS = {
"overview": "Model details and intended use",
"data": "Training and evaluation data",
"limitations": "Known limitations and failure cases",
"privacy": "Privacy and consent",
"ownership": "Ownership, contact and review",
}
METRICS = {
"accuracy": "Accuracy",
"selection_rate": "Approval rate",
"false_negative_rate": "Officer approvals missed",
"precision": "Precision",
}
OUT = Path("MODEL_CARD.md")
def fail(message):
sys.exit(f"error: {message}")
def load():
card = json.loads(Path("card.json").read_text(encoding="utf-8"))
results = json.loads(Path(card["eval_file"]).read_text(encoding="utf-8"))
if results["model_version"] != card["version"]:
fail(
f'{card["eval_file"]} is for version {results["model_version"]}, '
f'but card.json says {card["version"]}'
)
sections, missing = {}, []
for name, title in SECTIONS.items():
path = Path("sections") / f"{name}.md"
if not path.exists():
sections[name] = f"## {title}\n\n_Not written yet: add {path}._"
missing.append(name)
continue
text = path.read_text(encoding="utf-8").strip()
if "TODO" in text:
fail(f"{path} still contains TODO")
sections[name] = text
return card, results, sections, missing
def metrics_section(results):
overall, limit = results["overall"], results["gap_threshold"]
lines = [
"## Evaluation results",
"",
f'Test set: {results["test_rows"]} applications, evaluated on {results["evaluated_on"]}. '
f"A group's value is in bold when it differs from the overall value by more than {limit}.",
"",
"| Metric | Overall |",
"| --- | --- |",
]
lines += [f"| {label} | {overall[key]:.3f} |" for key, label in METRICS.items()]
gaps = []
for factor, groups in results["by_group"].items():
lines += [
"",
f"### By {factor}",
"",
"| Group | Rows | " + " | ".join(METRICS.values()) + " |",
"| --- | --- |" + " --- |" * len(METRICS),
]
for group, values in groups.items():
cells = []
for key, label in METRICS.items():
gap = round(values[key] - overall[key], 3)
if abs(gap) > limit:
cells.append(f"**{values[key]:.3f}** ({gap:+.3f})")
gaps.append(
f"- {label}, {group} ({factor}): {values[key]:.3f} "
f"against {overall[key]:.3f} overall"
)
else:
cells.append(f"{values[key]:.3f}")
lines.append(f'| {group} | {values["count"]} | ' + " | ".join(cells) + " |")
lines += ["", "### Gaps over the threshold", ""]
lines += gaps or ["- None."]
return "\n".join(lines), len(gaps)
def render(card, results, sections):
metrics, gap_count = metrics_section(results)
header = "\n".join([
f'# Model card: {card["name"]}',
"",
f'Version {card["version"]} · owner: {card["owner"]} · contact: {card["contact"]} '
f'· next review by {card["review_by"]}',
"",
"> Generated by render_card.py from card.json, sections/ and "
f'{card["eval_file"]}. Edit those, not this file.',
])
parts = [header, sections["overview"], sections["data"], metrics,
sections["limitations"], sections["privacy"], sections["ownership"]]
return "\n\n".join(parts) + "\n", gap_count
def main():
parser = argparse.ArgumentParser(description="Render MODEL_CARD.md")
parser.add_argument("--check", action="store_true",
help="fail if MODEL_CARD.md is unfinished or out of date")
args = parser.parse_args()
card, results, sections, missing = load()
text, gap_count = render(card, results, sections)
if datetime.date.fromisoformat(card["review_by"]) < datetime.date.today():
print(f'warning: the review was due by {card["review_by"]}', file=sys.stderr)
if args.check:
if missing:
fail("sections not written yet: " + ", ".join(missing))
if not OUT.exists() or OUT.read_text(encoding="utf-8") != text:
fail("MODEL_CARD.md is out of date; run python3 render_card.py")
print("MODEL_CARD.md is up to date")
return
OUT.write_text(text, encoding="utf-8")
written = len(SECTIONS) - len(missing)
print(f"Wrote {OUT}: {written} of {len(SECTIONS)} sections written, {gap_count} gaps flagged")
if __name__ == "__main__":
main()
PY
python3 render_card.pyCheck it worked
The script prints:
Wrote MODEL_CARD.md: 0 of 5 sections written, 4 gaps flaggedLook at the generated tables:
sed -n '/^## Evaluation results/,/^## Known/p' MODEL_CARD.mdThe "By gender" table shows women's approval rate as **0.330** (-0.080) and their officer approvals missed as **0.270** (+0.090). The "By region" table flags rural applicants the same way. The men's approval rate, 0.050 above overall, is not flagged, because the rule is "more than" the threshold. The last list names the four flagged values in plain words.
Step 3 · Write the intended use and the uses that are out of scope
This section answers the question people ask first: may I use this for my decision? Be specific about the decision the model supports and where a person takes over. The out-of-scope list matters more than the in-scope one, because it is what stops a score built for one job being reused for another, such as deciding which borrowers collections calls first.
List your own model's real inputs. The ones below are the five features the Fairlearn tutorial's model uses.
cat > sections/overview.md <<'MD'
## Model details and intended use
- **What it is:** a logistic regression (scikit-learn) that scores a personal loan application with the probability that an Ashgrove loan officer would have approved it. It imitates past officer decisions; it does not predict repayment.
- **Inputs:** monthly income, debt ratio (existing repayments as a share of income), years in current work, whether the applicant works part time, and distance from the applicant's home to the nearest branch.
- **Not inputs:** gender and region. They are collected separately and used only to evaluate the model by group.
- **Output:** applications scoring 0.5 or above are pre-approved. Everything else goes to a loan officer, who makes the decision.
### Intended use
- Sorting new personal loan applications into "pre-approve" and "send to a loan officer", so officers spend their time on the harder cases.
- Every decline is decided by a person. The model never declines an application on its own.
### Out of scope
- Declining an application, or setting interest rates, fees or credit limits.
- Business loans, asset finance or any product other than personal loans.
- Deciding which borrowers to contact first in collections.
- Applicants under 18, and countries where Ashgrove does not lend.
- Any decision outside lending, such as hiring, tenancy or insurance.
MD
python3 render_card.pyCheck it worked
The script now reports 1 of 5 sections written. Test the section by reading only the out-of-scope list and answering two questions from it: "Can the collections team use the score to rank who to chase?" and "Can an officer decline an application because the score is low?" Both answers should be an unambiguous no. If you have to think about it, the wording is too loose.
Step 4 · Describe the training data and its gaps
Readers need to know where the data came from, what the label really means, and who is missing from it. The gaps are the useful part. This model's label is the decision a loan officer made, not whether the loan was repaid, so the model learns the officers' habits, including the penalty against women and rural applicants that the Fairlearn tutorial measured. That is the most important line in this section.
In many markets, including much of Africa, a large share of applicants have a thin formal credit history but a long record of mobile money payments or informal savings groups. If your data cannot see that history, say so plainly, because the model will undervalue those applicants.
cat > sections/data.md <<'MD'
## Training and evaluation data
- **Source:** 20,000 Ashgrove personal loan applications from January 2024 to June 2026, each decided by a loan officer. 14,000 rows for training, 6,000 held out for evaluation, split at random with each gender and region combination kept at the same share in both.
- **Label:** `approved` is 1 when the loan officer approved the application. It records what officers decided, not whether the borrower repaid or whether the loan was affordable.
- **Group fields:** gender and region (urban or rural). Both are kept out of the inputs and used only to evaluate the model by group.
### Known gaps
- The labels are biased. Officers approved women and rural applicants less often than their finances explain, so a model that matches the labels well repeats that penalty. High accuracy for a group means agreement with past officers, not fair treatment.
- There is no repayment outcome in the data. Nobody can tell from it which declined applicants would have repaid, or which approved ones did.
- Rural applicants are 40% of the evaluation set and gender is close to half and half. Every gender and region combination has over 1,000 test rows, so the group gaps are not small-sample noise.
- Mobile money and savings group records are not in the data. Applicants whose history lives there look like applicants with no history.
- Seasonal income, common for farmers and traders, is recorded as a single monthly figure.
MD
python3 render_card.pyCheck it worked
The script reports 2 of 5 sections written. Open MODEL_CARD.md and check that every gap you listed points at something a reader can act on: a group the model may treat worse, or a kind of applicant it has never seen. A gap such as "the data may contain errors" tells nobody anything; replace it with the specific error you know about.
Step 5 · Record the known failure cases
Now read the flagged gaps in the evaluation table and write down what they mean in practice: who gets a worse result, the likely reason, and what the team does about it. Do not copy numbers into this section. The table already has them, and a number typed here is the first thing to go stale.
Say what you decided and why. The Fairlearn tutorial shows that fairness metrics pull against each other and against accuracy, so choosing between them is a policy decision. The card is where that decision is written down.
cat > sections/limitations.md <<'MD'
## Known limitations and failure cases
- **Women and rural applicants are pre-approved less often, and more of the applications officers approved are turned down by the model** (see the flagged values above). Gender and region are not inputs, but two features act as proxies: `part_time` (women are more likely to work part time) and `branch_km` (rural applicants live much further from a branch, and the distance identifies them almost perfectly). The labels themselves also carry the officers' penalty against both groups.
- **Seasonal income:** an applicant who earns most of their income at harvest is scored on an average month and looks riskier than they are.
- **Thin files:** applicants with no formal employment record score low whatever their mobile money record shows.
- **High incomes:** fewer than 2% of training applicants earned more than 1,000,000 a month in local currency. Scores above that are less reliable.
### What we do about it
- No application is declined by the model. Every application below the threshold is reviewed by a loan officer, who sees the applicant's full history.
- Officers are told in training that a low score for a rural or seasonal applicant is a reason to look closer, not a reason to decline.
- We tried per-group thresholds (Fairlearn ThresholdOptimizer). It closed most of the gap in officer approvals missed at a small cost in accuracy, but using gender at decision time needs legal sign-off, which is pending. Until then we rely on officer review.
- We plan to retrain on repayment outcomes once enough loans have matured, so the label stops being the officers' judgement.
- The by-group tables are recomputed every month on new applications. A new flagged value is a trigger for review (see below).
MD
python3 render_card.pyCheck it worked
The script reports 3 of 5 sections written. Check two things in sections/limitations.md. Every group flagged in the "Gaps over the threshold" list is explained, with a likely cause. And the file contains no metric values: search it for a decimal point.
grep -nE '0\.[0-9]' sections/limitations.md || echo "no metric values in the limitations section"The command prints no metric values in the limitations section.
Step 6 · Add privacy, consent, ownership and the review date
The privacy section tells a reader what personal data the model touches, what applicants were told, and what they can ask for. Write it with whoever owns data protection in your organisation, and check it against the law that applies where you lend. The Consent and data controls tutorial covers how to design the product side of this.
The ownership section names who answers for the model and when it is reviewed. The date itself lives in card.json and appears in the card's header, so it is not repeated here. Instead, list what brings the review forward.
cat > sections/privacy.md <<'MD'
## Privacy and consent
- **Personal data used:** the inputs listed under model details, from the application form. Distance to a branch is computed from the applicant's home address, which is not passed to the model itself. No data is bought from third parties.
- **What applicants are told:** the application form says an automated score is used to pre-approve applications and that a person reviews every application that is not pre-approved.
- **Gender and region:** asked as a separate, optional question, stored apart from the application, and readable only by the Credit Models team for monitoring. They never reach the scoring service.
- **Applicants' rights:** anyone can ask why they were not pre-approved and have their application reviewed by a person. Requests go to the contact below.
- **Retention:** training extracts are deleted 24 months after the model they trained is retired.
MD
cat > sections/ownership.md <<'MD'
## Ownership, contact and review
- **Owner:** the Credit Models team, who answer for this model's behaviour in production.
- **Report a problem:** email the contact in the header with the application ID. Do not send applicants' personal details by chat.
- **Scheduled review:** by the date in the header, then every six months.
- **Review early when:** the model is retrained; it is used for a new product or a new country; a monthly by-group check flags a new gap; or a complaint suggests a group is treated unfairly.
- **Who reviews:** the Credit Models team with someone from lending operations and from compliance.
MD
python3 render_card.pyCheck it worked
The script reports 5 of 5 sections written, 4 gaps flagged, and MODEL_CARD.md no longer contains "Not written yet":
grep -c 'Not written yet' MODEL_CARD.md || trueThe command prints 0. The header line under the title shows the owner, the contact address and next review by 2027-05-18.
Step 7 · Stop the card going stale
The script has a --check mode for CI. It renders the card in memory and fails if any section is missing or if the result differs from the MODEL_CARD.md in the repository. Run it now:
python3 render_card.py --checkIt prints MODEL_CARD.md is up to date. Now simulate a re-evaluation: the same model version, scored again on newer applications, with a worse result for rural applicants.
python3 - <<'PY'
import json
from pathlib import Path
path = Path("eval.json")
results = json.loads(path.read_text(encoding="utf-8"))
results["evaluated_on"] = "2027-02-10"
results["by_group"]["region"]["rural"]["false_negative_rate"] = 0.31
path.write_text(json.dumps(results, indent=2) + "\n", encoding="utf-8")
PY
python3 render_card.py --check || echo "the card no longer matches eval.json"The check fails with error: MODEL_CARD.md is out of date; run python3 render_card.py, then the second message prints. In CI that non-zero exit stops the merge. Re-render, and the check passes:
python3 render_card.py
python3 render_card.py --check
grep '| rural |' MODEL_CARD.mdThe rural row now shows **0.310** (+0.130), and the test set line says 6000 applications evaluated on 2027-02-10.
The script also refuses to mix versions. If eval.json says 1.1.0 while card.json still says 1.0.0, it exits with an error naming both, so a retrained model cannot ship under the old card.
Add python3 render_card.py --check to the CI job that runs your tests, next to the step that produces eval.json.
Check it worked
You saw --check fail after eval.json changed and pass after you re-rendered. Run git diff MODEL_CARD.md in your own repository after a re-evaluation and the only changes are the numbers and the evaluation date, which is exactly what a reviewer of that pull request needs to see.
Step 8 · Have someone outside the team review the card
The script proves the numbers match the results file. It cannot tell you whether the words are true or clear. Give MODEL_CARD.md to one person who did not build the model, ideally a loan officer or someone from compliance, and ask them to answer these from the card alone:
- What decision does this model support, and what must it never decide?
- Which applicants does it serve worse, and what happens to them?
- What personal data does it use, and what were applicants told?
- Who do they contact about a problem, and when is the next review?
If you used an AI tool to draft any section, the reviewer also checks each claim in it against the data and the team's real process. Drafts tend to describe controls that sound right but that nobody runs.
If loan officers read the card in a second language, keep sentences short and avoid idioms. A plain card is easier to translate, by a person or a tool, without losing the out-of-scope list.
Check it worked
The reviewer's four answers match the card, and they could find each one in under a minute. Every question they got wrong or had to ask you about becomes an edit to a file in sections/, followed by python3 render_card.py. When the card is final, delete the demo folder if you no longer need it:
rm -rf ~/model-card-demoNext steps
- Produce a real
eval.jsonfrom a model with group metrics in Check a classifier for unfair outcomes with Fairlearn. - Serve the model the card describes, and return the model version with each prediction, in Serve a scikit-learn model with FastAPI.
- Design what applicants see and control in Design consent and data controls for AI features.
Related tutorials
- Check a classifier for unfair outcomes with FairlearnYou will measure how a loan-approval model treats women, men, rural and urban applicants with Fairlearn, see why dropping the sensitive columns leaves most of the gap in place, and compare two ThresholdOptimizer fixes against their cost in accuracy.
- Serve a scikit-learn model as an API with FastAPIYou will have a FastAPI service that loads a saved scikit-learn pipeline once at startup, rejects bad input, returns a churn probability with the model version for one customer or a capped batch, logs every prediction for drift checks without personal data, and passes a TestClient test suite.
- Design consent and data controls for AI featuresYou will have a first-use screen, a just-in-time prompt, a settings screen and a delete flow for an AI assistant, each written in plain language from a data inventory your team has confirmed, and checked with five people.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials