Not All Mistakes Cost the Same
The baseline lesson showed that accuracy can hide a model that finds nothing. The deeper problem is that accuracy counts every mistake the same, while in practice they rarely cost the same. A screening test that misses a serious illness does far more harm than one that sends a healthy person for a second test. A fraud system that blocks honest customers' payments causes a different harm from one that lets fraud through.
To choose a model sensibly, you need to see which mistakes it makes and choose a measure that matches what those mistakes cost. This lesson covers the two-class case, where one class is the positive class, the thing you are looking for, such as fraud or a fault, and the other is negative.
The Confusion Matrix
A confusion matrix counts every combination of true class and predicted class. In scikit-learn, the entry in row i and column j is the number of samples whose true class is i and whose predicted class is j. With classes 0 (negative) and 1 (positive), the four cells have names:

Read the diagram row by row. Each row is what really happened; each column is what the model said. The diagonal from top left to bottom right holds the correct predictions. The other two cells are the two kinds of mistake: false positives, false alarms, and false negatives, misses. Precision looks down the right-hand column; recall looks along the bottom row.
Precision and Recall
- Precision = true positives ÷ (true positives + false positives). Of the cases the model flagged, how many were really positive? Low precision means many false alarms.
- Recall = true positives ÷ (true positives + false negatives). Of the cases that were positive, how many did the model find? Low recall means many misses.
Both range from 0 to 1. They usually pull against each other: flagging more cases finds more real positives, raising recall, but adds false alarms, lowering precision. Which matters more depends on the costs:
| If this mistake is worse | Prioritise | Example |
|---|---|---|
| Missing a real positive | Recall | Screening for a serious illness, followed by a confirmatory test |
| Raising a false alarm | Precision | Automatically blocking payments with no human review |
When no sample is predicted positive, precision divides zero by zero. Then
scikit-learn returns 0.0 and prints an UndefinedMetricWarning. Passing
zero_division=0 states that you accept 0.0 and silences the warning.
Exercise: Choose a Metric
You will evaluate a classifier on imbalanced generated data, compare its metrics with the baseline's, and check the calculations by hand.
Starting state: the course environment, active in your terminal. The script generates its own data.
-
Create the exercise folder. macOS and Linux:
mkdir -p ~/ai-practice/metric-choice cd ~/ai-practice/metric-choiceWindows PowerShell:
mkdir $HOME\ai-practice\metric-choice cd $HOME\ai-practice\metric-choiceSave this as
metric_choice.pyin that folder:"""Evaluate a classifier on imbalanced data with a confusion matrix, precision and recall.""" from sklearn.datasets import make_classification from sklearn.dummy import DummyClassifier from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score, confusion_matrix, precision_score, recall_score from sklearn.model_selection import train_test_split X, y = make_classification(n_samples=1000, weights=[0.95], random_state=2) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=2, stratify=y) model = LogisticRegression().fit(X_train, y_train) predictions = model.predict(X_test) print("Confusion matrix (rows: true class 0, 1; columns: predicted 0, 1):") print(confusion_matrix(y_test, predictions)) print("Accuracy: ", round(accuracy_score(y_test, predictions), 3)) print("Precision:", round(precision_score(y_test, predictions), 3)) print("Recall: ", round(recall_score(y_test, predictions), 3)) baseline_predictions = DummyClassifier().fit(X_train, y_train).predict(X_test) print("Baseline accuracy: ", round(accuracy_score(y_test, baseline_predictions), 3)) print("Baseline precision:", precision_score(y_test, baseline_predictions, zero_division=0)) print("Baseline recall: ", recall_score(y_test, baseline_predictions)) -
Run it:
python metric_choice.pyOutput, which should match exactly:
Confusion matrix (rows: true class 0, 1; columns: predicted 0, 1): [[279 5] [ 8 8]] Accuracy: 0.957 Precision: 0.615 Recall: 0.5 Baseline accuracy: 0.947 Baseline precision: 0.0 Baseline recall: 0.0 -
Before reading on, calculate precision and recall yourself from the matrix, using the formulas above, and compare with the printed values.
How the Script Works and What It Shows
The data and model. The data is the imbalanced generated set from the
baseline lesson, about 5% positive, split with a 0.3 test share: 300 test
samples, 16 of them positive. A logistic regression model is trained and its
test predictions stored in predictions.
The matrix. confusion_matrix(y_test, predictions) takes the true labels
first and the predictions second. Of 284 real negatives, 279 were predicted
negative and 5 positive. Of 16 real positives, 8 were missed and 8 found.
The scores. Accuracy is (279 + 8) ÷ 300 = 0.957, only one point above the
baseline's 0.947. Precision is 8 ÷ (8 + 5) = 0.615: about six in ten flagged
cases were real. Recall is 8 ÷ (8 + 8) = 0.5: half the real positives were
missed. The baseline flags nothing, so its precision is undefined, reported
as 0.0 because of zero_division=0, and its recall is 0.0.
So accuracy says the model is barely better than doing nothing, while recall shows it finds half the positives and the baseline none. Whether finding half is good enough depends on what a miss costs.
If you removed zero_division=0 from the baseline line, the result would
still be 0.0, but scikit-learn would also print an UndefinedMetricWarning
explaining that precision is ill-defined because nothing was predicted
positive.
Success: your hand calculations match the printed precision and recall, and you can explain why accuracy barely separates the model from the baseline while recall does.
If something differs:
| What you see | Likely cause | Next step |
|---|---|---|
| The matrix looks flipped, with large numbers bottom right | The arguments to confusion_matrix were swapped, or the classes are labelled differently | Pass y_test first, then predictions |
UndefinedMetricWarning appears | zero_division=0 was left out of the baseline precision line | Add it back, or accept the warning |
| Different numbers | test_size, random_state or weights was changed | Restore the values shown |
ModuleNotFoundError | The course environment is not active | Activate it and rerun |
-
Clean up. macOS and Linux:
cd ~/ai-practice ls rm -rf metric-choice lsWindows PowerShell:
cd $HOME\ai-practice ls Remove-Item -Recurse metric-choice lsCheck that the first
lsshowsmetric-choicebefore removing it.
Independent task: two models check 1,000 bridge cables, 40 of which are damaged. Every flagged cable is then inspected by an engineer; an unflagged damaged cable is not inspected at all. Calculate each model's precision and recall, and choose one.
Model A Model B
[[916 44] [[954 6]
[ 4 36]] [ 16 24]]
Check Your Understanding
For each task, choose whether precision or recall matters more, and explain using the cost of each kind of mistake:
- A screening test for a serious, treatable condition, where every positive result is followed by a reliable confirmatory test.
- A system that automatically suspends customer accounts for suspected fraud, with no human check.
Answer and Reasoning
Independent task
- Model A: recall = 36 ÷ (36 + 4) = 0.9; precision = 36 ÷ (36 + 44) = 0.45.
- Model B: recall = 24 ÷ (24 + 16) = 0.6; precision = 24 ÷ (24 + 6) = 0.8.
Choose model A. A missed damaged cable is never inspected, which could be dangerous, while a false alarm costs only an engineer's inspection. Model A misses 4 damaged cables against model B's 16, at the price of 44 unnecessary inspections instead of 6. The rows are the true classes, so the damaged cables are the bottom row in both matrices.
Understanding check
- Recall. A missed case goes untreated, while a false alarm is caught by the confirmatory test at the cost of some worry and an extra test.
- Precision. Every false positive suspends an honest customer with no one to catch the mistake, so false alarms are costly. Even then, the stakes argue for adding human review rather than relying on any single metric.