Section 3 · Lesson 2
Confusion matrices, precision and recall
Count the four kinds of right and wrong, measure precision and recall, and move the threshold to fit the business goal.
“85% accurate” sounded fine until we noticed that predicting nobody converts scores 84.7%. To judge a classifier you need to know which mistakes it makes, and that starts with a table of four counts.
The confusion matrix
Every prediction falls into one of four boxes:
| Predicted 0 | Predicted 1 | |
|---|---|---|
| Actually 0 | True negative (TN) | False positive (FP) |
| Actually 1 | False negative (FN) | True positive (TP) |
from sklearn.metrics import confusion_matrix
pred = (proba >= 0.5).astype(int)
confusion_matrix(y_test, pred) # [[TN, FP], [FN, TP]]
For our logistic model at the default 0.5 threshold:
| Predicted 0 | Predicted 1 | |
|---|---|---|
| Actually 0 | 1,035 | 24 |
| Actually 1 | 154 | 37 |
Accuracy is (1,035 + 37) / 1,250 = 85.8%, but the model only found 37 of the 191 buyers.
Precision and recall
- Precision = TP / (TP + FP): of the visitors we flagged, what share actually bought? In ad terms, how much of the targeted spend reached buyers.
- Recall = TP / (TP + FN): of the visitors who bought, what share did we flag? Also called sensitivity or the true positive rate.
- F1 = 2 × precision × recall / (precision + recall): their harmonic mean. It’s high only when both are.
At 0.5, precision is about 61% but recall is only 19%: the model is accurate when it speaks up, but it rarely does.
Moving the threshold
The 0.5 cut-off is a default, not a law. Lowering it flags more visitors: recall rises and precision falls.
| Threshold | Visitors flagged | Precision | Recall | F1 |
|---|---|---|---|---|
| 0.50 | 61 | 0.61 | 0.19 | 0.29 |
| 0.25 | 206 | 0.48 | 0.52 | 0.50 |
| 0.20 | 285 | 0.39 | 0.58 | 0.47 |
There is no free lunch. Every threshold is a trade between wasting impressions on non-buyers (false positives) and missing buyers (false negatives). The model is the same in every row; only the decision rule changed.
Choose the threshold from the business problem
F1 treats both errors as equally bad, which is rarely true. Put money on each box instead.
Suppose an impression costs $2 and a conversion earns $40 of margin. Showing an ad to a visitor
with conversion probability p is worth 40p - 2, which is positive whenever p > 2/40 = 0.05.
The profitable threshold is far below 0.5, and it comes from the economics, not from the model.
(This assumes the ad causes the purchase, a caveat you’ll come back to in the propensity lesson.)
Other situations point the other way. A fraud team that can only review 50 cases a day cares about precision at the top of the list. A cancer screen cares most about recall.
Related measures and tools
- Specificity = TN / (TN + FP): the share of non-buyers correctly left alone. The false positive rate is 1 − specificity. You’ll need it for ROC curves in the next lesson.
classification_report(y_test, pred)prints precision, recall and F1 for each class.precision_recall_curve(y_test, proba)computes precision and recall at every possible threshold at once.LogisticRegression(class_weight="balanced")up-weights the rare class during training. That pushes probabilities upward, which has much the same effect as lowering the threshold. If you need calibrated probabilities for budgeting, it’s usually simpler to leave training alone and choose the threshold afterwards.
Practice
Write your answer, press Run to see results and Check answer to grade it. Shortcuts: Ctrl/⌘ + Enter run, Shift + Enter check.
The confusion matrix at 0.5
DoneThe starter computes proba, the logistic model's probability of converting for each test visitor. Predict 1 when proba >= 0.5.
pred: the 0/1 predictionscm:confusion_matrix(y_test, pred)tn,fp,fn,tp: the four counts (cm.ravel()returns them in that order)precision:tp / (tp + fp), rounded to 4 decimalsrecall:tp / (tp + fn), rounded to 4 decimals
Need a hint?
(proba >= 0.5).astype(int)turns True/False into 1/0.- scikit-learn's matrix has true labels on the rows and predictions on the columns:
[[tn, fp], [fn, tp]].
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix, precision_score, recall_score
audience = pd.read_csv("audience.csv")
features = ["sessions_30d", "pages_viewed_30d", "minutes_on_site_30d", "cart_adds_30d",
"days_since_last_visit", "past_purchases", "email_subscriber", "ad_impressions_7d"]
X_train, X_test, y_train, y_test = train_test_split(
audience[features], audience["converted"], test_size=0.25, random_state=42,
stratify=audience["converted"],
)
model = make_pipeline(StandardScaler(), LogisticRegression()).fit(X_train, y_train)
proba = model.predict_proba(X_test)[:, 1]
pred = None
cm = None
tn = fp = fn = tp = None
precision = None
recall = None
print(cm, precision, recall)
Files in the working directory
audience.csv (5,000 rows)daily_stats.csv (1,561 rows)campaigns.csv (40 rows)Pick a threshold
DoneUsing the same proba:
precision_20,recall_20,f1_20: precision, recall and F1 when you predict 1 for
proba >= 0.2, each rounded to 4 decimals
f1_by_threshold: a pandas Series of F1 scores indexed by threshold, for
thresholds = np.round(np.arange(0.05, 0.65, 0.05), 2)
best_threshold: the threshold with the highest F1
Need a hint?
- A list comprehension builds all the F1 scores:
[f1_score(y_test, (proba >= t).astype(int)) for t in thresholds]. series.idxmax()returns the index label (here the threshold) with the largest value.
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import precision_score, recall_score, f1_score
audience = pd.read_csv("audience.csv")
features = ["sessions_30d", "pages_viewed_30d", "minutes_on_site_30d", "cart_adds_30d",
"days_since_last_visit", "past_purchases", "email_subscriber", "ad_impressions_7d"]
X_train, X_test, y_train, y_test = train_test_split(
audience[features], audience["converted"], test_size=0.25, random_state=42,
stratify=audience["converted"],
)
model = make_pipeline(StandardScaler(), LogisticRegression()).fit(X_train, y_train)
proba = model.predict_proba(X_test)[:, 1]
thresholds = np.round(np.arange(0.05, 0.65, 0.05), 2)
precision_20 = None
recall_20 = None
f1_20 = None
f1_by_threshold = None
best_threshold = None
print(precision_20, recall_20, f1_20, best_threshold)
Files in the working directory
audience.csv (5,000 rows)daily_stats.csv (1,561 rows)campaigns.csv (40 rows)