Metrics from a confusion matrix (K3)
Why This Matters
“The model is 92% accurate” sounds like a quality statement. It is not, until you know what the other 8% are. A loan model that rejects good customers loses money quietly; one that approves bad customers loses it loudly. A fraud model that catches nothing can still be 99% accurate, if 99% of transactions are honest. The confusion matrix is how you see which mistakes a model makes, and the metrics calculated from it are how you agree with a team on which mistakes matter.
This is one of the four K3 learning objectives in CT-AI v2.0: in the exam you calculate these metrics, and the question counts double.
What you will learn
- Build a confusion matrix from predictions and actual outcomes
- Calculate accuracy, precision, recall, specificity and F1-score
- Explain how the decision threshold trades precision against recall
- Choose the metric that matches the cost of a mistake
The four cells
A binary classifier gives every case one of two answers. The positive class is the one you are looking for. For the loan model on practiceautomatedtesting.com the positive class is repaid: the model should approve applicants who will repay their loan.
Comparing each prediction with what really happened gives four possible outcomes:
| Actually repaid | Actually defaulted | |
|---|---|---|
| Model approved | TP, true positive: good loan approved | FP, false positive: bad loan approved |
| Model rejected | FN, false negative: good customer rejected | TN, true negative: bad loan rejected |
The name of a cell is two words: true/false says whether the model was right; positive/negative says what the model predicted. A false negative is a case the model predicted negative, wrongly. Mixing up FP and FN is the most common mistake in the exam, so check the second word against the prediction every time.
Five metrics
| Metric | Formula | Question it answers |
|---|---|---|
| Accuracy | (TP + TN) / (TP + TN + FP + FN) | What fraction of all predictions is right? |
| Precision | TP / (TP + FP) | When the model says approve, how often is it right? |
| Recall (sensitivity, true positive rate) | TP / (TP + FN) | Of all applicants who would repay, how many does the model approve? |
| Specificity (true negative rate) | TN / (TN + FP) | Of all applicants who would default, how many does the model reject? |
| F1-score | 2 × precision × recall / (precision + recall) | One number that is only high when precision and recall are high |
A way to remember precision and recall: both have TP on top. Precision looks along the predicted row (TP + FP: everything the model approved). Recall looks down the actual column (TP + FN: everyone who really repaid).
Try it on a real model
The matrix below loads the test set of the practice loan model live from the ML practice API: 40 applicants, each with the real outcome and the probability the model gave them. Move the threshold and watch the cells and the metrics change.
At the default threshold of 0.5 the matrix is:
| Actually repaid | Actually defaulted | |
|---|---|---|
| Approved | TP = 13 | FP = 3 |
| Rejected | FN = 6 | TN = 18 |
Worked out:
- Accuracy = (13 + 18) / 40 = 31 / 40 = 0.775
- Precision = 13 / (13 + 3) = 13 / 16 = 0.813
- Recall = 13 / (13 + 6) = 13 / 19 = 0.684
- Specificity = 18 / (18 + 3) = 18 / 21 = 0.857
- F1 = 2 × 0.813 × 0.684 / (0.813 + 0.684) = 0.743
You can check your own calculation against the API: /api/ml/test-set/metrics?threshold=0.5.
The threshold is a business decision
The model does not output “approve” or “reject”. It outputs a probability, and someone decides where the line is. Moving that line moves cases between the cells:
| Threshold | TP | FP | FN | TN | Precision | Recall |
|---|---|---|---|---|---|---|
| 0.3 | 13 | 6 | 6 | 15 | 0.684 | 0.684 |
| 0.5 | 13 | 3 | 6 | 18 | 0.813 | 0.684 |
| 0.8 | 11 | 2 | 8 | 19 | 0.846 | 0.579 |
A higher threshold makes the model more careful: fewer bad loans approved (precision up), but more good customers turned away (recall down). There is no setting that is best for both. Which one is right depends on what a mistake costs:
- A false positive costs more (a bad loan approved, a fraudulent payment let through, a wrong medical diagnosis acted upon): favour precision.
- A false negative costs more (a disease missed, a fraudulent transaction not flagged for review, a defect not detected): favour recall.
- Both matter and the classes are balanced: F1 is a reasonable single number.
As a tester, you do not choose the threshold. You make sure the acceptance criteria say which metric matters and what its minimum is (module 2), and you test against that, at the threshold that will be used in production.
When accuracy lies
Take a fraud detector tested on 1,000 transactions, of which 20 are fraudulent (the positive class):
| Actually fraud | Actually honest | |
|---|---|---|
| Flagged | TP = 5 | FP = 5 |
| Not flagged | FN = 15 | TN = 975 |
Accuracy = (5 + 975) / 1000 = 0.98. Recall = 5 / (5 + 15) = 0.25. The model looks excellent and misses three out of four frauds. A model that never flags anything would score 0.98 accuracy too. With imbalanced classes, accuracy says almost nothing; look at precision and recall for the class you care about.
Calculate it yourself
The matrix below has editable counts. Use it to check the exercises after you have done them on paper, the way you will in the exam.
Hands-on: test the metrics in code
Calculating by hand is the exam skill; checking a model’s metrics in an automated test is the job skill. You continue in the practice project from the lesson Set up your practice project (module 3). Open a terminal in the project folder and activate the environment:
cd ai-testing-practice
source .venv/bin/activate # Windows: .venv\Scripts\activate
Write the tests
Create the folder module-4 with the file module-4/test_metrics.py:
"""Lesson "Metrics from a confusion matrix (K3)": calculate the metrics yourself and test them."""
import pytest
@pytest.fixture(scope="module")
def test_set(api):
"""The 40 labelled applicants with the model's probability, fetched once for all tests."""
response = api.get(f"{api.base}/test-set", timeout=10)
response.raise_for_status()
return response.json()["data"]
def confusion_matrix(rows, threshold):
"""Count TP, FP, FN, TN. Positive class: repaid. Predicted positive: probability >= threshold."""
tp = fp = fn = tn = 0
for row in rows:
approved = row["probability"] >= threshold
if approved and row["repaid"]:
tp += 1
elif approved:
fp += 1
elif row["repaid"]:
fn += 1
else:
tn += 1
return tp, fp, fn, tn
@pytest.mark.parametrize("threshold", [0.3, 0.5, 0.8])
def test_my_confusion_matrix_matches_the_api(api, test_set, threshold):
tp, fp, fn, tn = confusion_matrix(test_set, threshold)
expected = api.get(f"{api.base}/test-set/metrics", params={"threshold": threshold}, timeout=10).json()
assert (tp, fp, fn, tn) == (
expected["truePositives"], expected["falsePositives"],
expected["falseNegatives"], expected["trueNegatives"],
)
def test_precision_and_recall_meet_the_acceptance_criteria(test_set):
# Example acceptance criteria: at the production threshold of 0.5,
# precision at least 0.80 and recall at least 0.65.
tp, fp, fn, tn = confusion_matrix(test_set, 0.5)
precision = tp / (tp + fp)
recall = tp / (tp + fn)
assert precision >= 0.80, f"precision {precision:.3f}"
assert recall >= 0.65, f"recall {recall:.3f}"
Three things to notice:
confusion_matrixis your own implementation; the API’s/test-set/metricsis the oracle that tells you whether it is right. Comparing two independent calculations is a technique you will meet again as back-to-back testing (module 7).- The
test_setfixture fetches the data once for all four tests (scope="module"). Theapifixture comes fromconftest.py, so the address of the API is in one place. - The acceptance-criteria test is the one that matters in a real project: it fails the build when a new model gets worse. Its thresholds come from the acceptance criteria, not from the current model.
Run them
pytest module-4 -v
This is a real run against the live site:
module-4/test_metrics.py::test_my_confusion_matrix_matches_the_api[0.3] PASSED [ 57%]
module-4/test_metrics.py::test_my_confusion_matrix_matches_the_api[0.5] PASSED [ 71%]
module-4/test_metrics.py::test_my_confusion_matrix_matches_the_api[0.8] PASSED [ 85%]
module-4/test_metrics.py::test_precision_and_recall_meet_the_acceptance_criteria PASSED [100%]
(The percentages count from the setup tests, because this run was pytest -v for the whole project.)
Make it fail on purpose
A test you have never seen fail is a test you cannot trust. Change recall >= 0.65 into recall >= 0.70 and run again:
> assert recall >= 0.70, f"recall {recall:.3f}"
E AssertionError: recall 0.684
E assert 0.6842105263157895 >= 0.7
The message gives the actual value, so a failing build tells you how far the model is from the criteria, not only that it fails. Change it back to 0.65.
Then test the retrained model. In the test_set fixture, change the request into api.get(f"{api.base}/test-set", params={"model": "v2"}, timeout=10). The criteria test now fails on precision (0.706): the new model is not ready for release. Fix precision, and the next assertion would fail on recall too (0.632). Change it back to v1 afterwards.
Your project so far
ai-testing-practice/
├── .venv/
├── .gitignore
├── conftest.py
├── pytest.ini
├── requirements.txt
├── setup/
│ └── test_setup.py
└── module-4/
└── test_metrics.py new in this lesson
The finished version is in the example repository: module-4/test_metrics.py.
Exercise
Use the matrix from the editable widget above: TP = 40, FP = 10, FN = 20, TN = 130.
- Calculate accuracy, precision, recall, specificity and F1-score.
- The model screens job applications; positive means “invite for an interview”. Which metric would the hiring manager care most about, and which one the candidates?
Show suggested answer
Total = 40 + 10 + 20 + 130 = 200.
- Accuracy = (40 + 130) / 200 = 170 / 200 = 0.85
- Precision = 40 / (40 + 10) = 40 / 50 = 0.80
- Recall = 40 / (40 + 20) = 40 / 60 = 0.667
- Specificity = 130 / (130 + 10) = 130 / 140 = 0.929
- F1 = 2 × 0.80 × 0.667 / (0.80 + 0.667) = 1.067 / 1.467 = 0.727
The hiring manager pays for every interview, so false positives (unsuitable people invited) cost time: they care about precision. Candidates care about false negatives, suitable people never invited: recall. Both views are legitimate, which is why the acceptance criteria have to name the metric and the minimum before anyone tests, and why a test report should show the whole matrix, not one number.
Exam-style questions
1. A model’s test results are TP = 30, FP = 20, FN = 10, TN = 140. What is its precision?
- A. 0.60
- B. 0.75
- C. 0.85
- D. 0.875
Show answer
2. A medical screening model must miss as few sick patients as possible. “Sick” is the positive class. Which metric should the acceptance criteria require to be high?
- A. Precision
- B. Recall
- C. Specificity
- D. Accuracy
Show answer
3. You raise a classifier’s decision threshold. What usually happens?
- A. Precision and recall both rise
- B. Precision rises, recall falls
- C. Precision falls, recall rises
- D. Nothing changes; the threshold only affects the probability