Lesson 06 · 40 minutes
Measure a model with precision, recall and a confusion matrix
- Read a confusion matrix and a per-class report
- Say what precision and recall mean for a detector
- Show why a high accuracy can hide a useless detector
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
Your SOC (security operations centre) runs a detector that the vendor calls "99 percent accurate". The analysts say that they drown in false alarms, and a manager says that the detector "catches 99 percent of attacks". Both statements can be true at once. Your task is to find which measures show what each person means, to compute them for a detector from numbers, and to measure the model of lesson 3 on a new split.
Recall
Why must the test set stay unseen until the end?
If the test set takes part in any decision, the score on it is no longer an honest estimate for new data. The model, or you, have then adapted to it.
What do `random_state` and `stratify` do in `train_test_split`?
random_state fixes the random choice, so that the split and every number repeat. stratify=y keeps the share of each class equal in the training and the test part.
The idea
Think of a detector with two answers, "attack" and "normal". Every prediction falls into one of four boxes.
| Detector says attack | Detector says normal | |
|---|---|---|
| Really an attack | True positive (TP) | False negative (FN): a missed attack |
| Really normal | False positive (FP): a false alarm | True negative (TN) |
- Predictions → Compare: put each one next to the true label
- Compare → Four boxes: count TP, FP, FN and TN
- Four boxes → Measures: accuracy, precision, recall
- Accuracy = right answers / all answers.
- Precision = TP / (TP + FP). Of the alerts, how many were real?
- Recall = TP / (TP + FN). Of the real attacks, how many did you find?
Precision protects the analyst from noise. Recall protects the company from missed attacks. You usually gain one by losing the other. The confusion matrix counts all the boxes; with ten classes it has ten rows and ten columns. Row i, column j counts the examples of class i that the model called j.
Worked example
1. Get the predictions
Create measure.py. It rebuilds the model of lesson 3 and asks for a full report. Three functions are new, and each one takes the true labels first and the predicted labels second:
accuracy_scorereturns the accuracy.confusion_matrixreturns the table of counts.classification_reportprints precision, recall and a third measure for each class.digits=3sets the number of decimals.
measure.py
from sklearn.datasets import load_digits
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
from sklearn.model_selection import train_test_split
X, y = load_digits(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=42, stratify=y
)
model = LogisticRegression(max_iter=2000).fit(X_train, y_train)
pred = model.predict(X_test)
print("accuracy:", round(accuracy_score(y_test, pred), 4))
print(confusion_matrix(y_test, pred))
print(classification_report(y_test, pred, digits=3))cd ~/krlab/how-ai-works
source .venv/bin/activate
python measure.pyaccuracy: 0.9622
[[45 0 0 0 0 0 0 0 0 0]
[ 0 43 0 1 0 0 0 0 2 0]
[ 0 1 43 0 0 0 0 0 0 0]
[ 0 0 0 46 0 0 0 0 0 0]
[ 0 0 0 0 45 0 0 0 0 0]
[ 0 0 0 0 0 45 0 0 0 1]
[ 0 0 0 0 0 0 44 0 1 0]
[ 0 0 0 0 1 0 0 44 0 0]
[ 0 4 0 0 0 1 1 0 37 0]
[ 0 0 0 0 1 0 0 0 3 41]]2. Read the matrix
The numbers on the diagonal are right answers. Every other number is a mistake. Look at row 8: of 43 real eights, 37 were found, and 4 were called ones. Look at column 8: three nines, two ones and one six were wrongly called eights. The model confuses 8 with 1, 5, 6 and 9, which are shapes that look similar.
3. Read the report
The same command printed a table. Its important part is below.
precision recall f1-score support
1 0.896 0.935 0.915 46
8 0.860 0.860 0.860 43
9 0.976 0.911 0.943 45
accuracy 0.962 450support is the number of real examples of the class. The classes 0, 3, 5 and 7 (not shown) reach 0.978 or more for both measures. The digit 8 has the weakest results, 0.860 for precision and for recall. The average of 0.962 hides this. When a class matters to you, read its row, not the average. The f1-score is one number that mixes precision and recall; it is high only when both are high.
4. Test a detector for rare attacks
Now the case that makes security different. In 100,000 events, 100 are attacks. Create rare.py. Detector A never raises an alert. Detector B finds 99 of the 100 attacks and raises a false alarm for 1 percent of the normal events.
Here np.array makes a NumPy list, and [1] * 100 + [0] * 99_900 is 100 ones followed by 99,900 zeros: the true labels. np.zeros_like(y_true) makes a list of zeros of the same size: the predictions of A. b[:99] = 1 sets the first 99 items to 1, and b[100:1099] = 1 sets the 999 items from position 100 on to 1. Those are the normal events that B wrongly marks: 1 percent of 99,900. precision_score and recall_score work like accuracy_score; zero_division=0 says "give 0, not an error" when a detector raises no alert and precision has no meaning.
rare.py
import numpy as np
from sklearn.metrics import accuracy_score, precision_score, recall_score
y_true = np.array([1] * 100 + [0] * 99_900)
a = np.zeros_like(y_true) # never alerts
b = np.zeros_like(y_true)
b[:99] = 1 # finds 99 of 100 attacks
b[100:1099] = 1 # 999 false alarms
for name, pred in (("A never alerts", a), ("B", b)):
print(name,
"accuracy", round(accuracy_score(y_true, pred), 4),
"precision", round(precision_score(y_true, pred, zero_division=0), 3),
"recall", round(recall_score(y_true, pred), 3),
"alerts", int(pred.sum()))python rare.pyA never alerts accuracy 0.999 precision 0.0 recall 0.0 alerts 0
B accuracy 0.99 precision 0.09 recall 0.99 alerts 1098Detector A has the better accuracy and is worthless: it finds no attack. Detector B has 99 percent accuracy and catches 99 attacks. But 1,098 alerts hold only 99 real ones, so 9 alerts in 100 are real. An analyst who reads B's alerts will stop trusting them. Accuracy cannot show either problem.
Your turn
Part A. Measure the digits model on a new split. There is no code here: adapt measure.py.
- Split with
test_size=0.3,random_state=7andstratify=y. Train aLogisticRegression(max_iter=2000). - Print the confusion matrix and the report.
- Find the class with the lowest recall and the class with the lowest precision.
- In the matrix, find how many real 9s the model called 8.
Part B. Detector C watches 50,000 events. 200 are attacks. It raises 600 alerts. 150 of them are real attacks. You do not need code: use the formulas of this lesson, and check them with precision_score if you wish.
Last, find the recall of detector C and say in one sentence which of A, B and C you would keep, and what you would ask its owner.
Check yourself
What does a recall of 0.86 mean for the digit 8 in this lesson?
Of all the real eights in the test set, the model found 86 percent. The other 14 percent were called something else.
Why is accuracy a poor measure when attacks are 0.1 percent of the events?
A detector that never alerts is right 99.9 percent of the time. Accuracy is dominated by the common class. Precision and recall for the rare class show what you need.
Your detector has recall 0.99 and precision 0.09. Which problem does it have and who suffers?
Too many false alarms. The analysts suffer: 91 alerts in 100 are noise. They begin to ignore alerts, and the real attacks in the noise are missed.
The overall accuracy is 0.96. Is it safe to say that every class works at about 96 percent?
No. The average hides the spread. In the report, the digit 8 is at 0.86 and the digit 0 is at 1.0. Always read the per-class results.
Field notes
- Choose the measure from the cost of a mistake. Missing a ransomware infection costs far more than one false alarm, so recall comes first; a model that blocks a user from a payment needs high precision.
- The base rate (the share of real attacks) controls precision. The same detector can have a high precision where attacks are common and a precision of 0.09, as in step 4, where they are rare. Always state the base rate when you report precision.
- Most models give a score, and the cut-off at 0.5 is a default, not a law. Move the cut-off and you trade precision for recall. The functions
precision_recall_curveandroc_auc_scorein scikit-learn show the whole trade. - Add the confidence of the number. With 43 examples of a class, one more mistake changes its recall by two points. Do not compare classes or models on differences that small.
- Measure the model against a simple baseline (always the common class, or one hand-written rule) and report both. A model that does not beat the baseline is not worth running.