Lesson 7 of 227 min
Precision, recall and the confusion matrix
When one answer is rare, a model can be right almost every time and still miss most of what you want, so count its four kinds of answer and ask two questions: how many of its picks are right, and how many of the real yeses it finds.
After this lesson you can choose the metric that matches the cost of each mistake.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
The bank's model, whole
Put bank-additional-full.csv from UCI's Bank Marketing dataset next to your notebook, and run these cells in order. The 1,000 test calls are the video's. How the columns are prepared is the feature preparation lesson's.
import pandas as pd
from sklearn.compose import make_column_transformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix, precision_score, recall_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScalercalls = pd.read_csv("bank-additional-full.csv", sep=";")
y = calls["y"].eq("yes")
numbers = ["age", "campaign", "previous"]
words = ["job", "marital", "education", "default", "housing", "loan", "contact", "poutcome"]
X = calls[numbers + ["pdays"] + words]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=1000, stratify=y, random_state=0
)prep = make_column_transformer(
(StandardScaler(), numbers),
(SimpleImputer(missing_values=999, add_indicator=True), ["pdays"]),
(OneHotEncoder(handle_unknown="ignore"), words),
)
model = make_pipeline(prep, LogisticRegression()).fit(X_train, y_train)
picks = model.predict(X_test)
print(model.score(X_test, y_test))0.898
The matrix's order
confusion_matrix puts the truth in the rows and the answer in the columns, both sorted, so False comes first. That is why the right picks sit at the bottom right. Pass labels to put the yeses first, or unpack the four counts by name. confusion_matrix reference
print(confusion_matrix(y_test, picks, labels=[True, False]))
tn, fp, fn, tp = confusion_matrix(y_test, picks).ravel()
print(tn, fp, fn, tp)[[ 18 95] [ 7 880]] 880 7 95 18
Draw the table
ConfusionMatrixDisplay draws the same four counts as a picture, with your own names for the rows and columns. It needs matplotlib.
from sklearn.metrics import ConfusionMatrixDisplay
ConfusionMatrixDisplay.from_predictions(
y_test, picks, display_labels=["said no", "said yes"]
)F1, one number for both
The report's f1-score mixes precision and recall into one number, their harmonic mean. It stays low when either one is low: 0.72 and 0.16 give 0.26. It helps when you must rank many models by one number. It hides which mistake costs more, so read the two as well.
from sklearn.metrics import f1_score
print(round(f1_score(y_test, picks), 3))0.261
Three or more kinds
With more than two answers, each kind gets its own precision and recall. average=None gives them all; average="macro" averages them, each kind counting the same. Here a model tells the three penguin species apart from their bills.
url = "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/penguins.csv"
penguins = pd.read_csv(url).dropna()
bills = penguins[["bill_length_mm", "bill_depth_mm"]]
b_train, b_test, s_train, s_test = train_test_split(bills, penguins["species"], random_state=0)
kinds = LogisticRegression().fit(b_train, s_train).predict(b_test)
print(recall_score(s_test, kinds, average=None).round(2))
print(f"{recall_score(s_test, kinds, average='macro'):.3f}")[1. 0.71 0.96] 0.893
Balanced accuracy and class weights
Balanced accuracy averages the recall of the yeses and the recall of the no's, so a rare yes counts as much as a common no: 0.576 here, not 0.898. class_weight="balanced" makes each missed yes cost more while the model learns. It finds far more yeses and wastes far more calls.
from sklearn.metrics import balanced_accuracy_score
print(round(balanced_accuracy_score(y_test, picks), 3))
weighted = make_pipeline(prep, LogisticRegression(class_weight="balanced")).fit(X_train, y_train)
heavy = weighted.predict(X_test)
print(confusion_matrix(y_test, heavy))
print(round(precision_score(y_test, heavy), 3), round(recall_score(y_test, heavy), 3))0.576 [[600 287] [ 39 74]] 0.205 0.655
Run on Python 3.13.3, scikit-learn 1.9.1, pandas 3.1.1 and matplotlib 3.11.2. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: Logistic regression
For bills of 40, 43, 45 and 48 mm, model.predict_proba(new)[:, 1] prints [0.013 0.217 0.679 0.978]: each bill's chance of being a Chinstrap. What does model.predict(new) print?
2 of 3
Of 1,000 calls, 113 said yes. The bank's model is right on 898 of them. A model that says no to everyone is right on 887. What does that tell you?
3 of 3
A spam filter's confusion matrix prints [[950 10] [30 30]]. Rows: real email, then spam. Columns: kept, then moved to spam. What is its recall, as a percent?
The ideas in this lesson
- Accuracy and a rare yes
- When one answer is rare, a model that always gives the common one is right almost every time and finds no one.
- Confusion matrix
- Sort every answer by what the model said and what was true: right picks, wasted picks, misses and right no's.
- Precision and recall
- Precision: of the model's picks, the share that are right. Recall: of the real yeses, the share it picks.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Precision and recall
Here's a question. A bank uses a model to choose which customers to call. The model is almost always right. Is it a good model?
Keep your guess
Hold on to your guess.
These are real calls from a bank, offering its customers a savings deposit. Most people said no. About one in nine said yes.
Here are a thousand calls the model never learned from.
A hundred and thirteen of them said yes. The model picks the customers to call.
On these thousand calls, it's right eight hundred and ninety-eight times.
A model that picks no one
A model that chooses who to call is usually scored by how often it's right. So take a model that picks no one at all. It says no to every customer. How many of the thousand does it get right?
Eight hundred and eighty-seven.
And it finds none of the hundred and thirteen who said yes.
The real model gets just eleven more.
Accuracy hides a rare yes
The share of right answers is called accuracy. When only a hundred and thirteen out of a thousand say yes, most answers are no, and getting those right is easy. Almost all of the model's right answers are no's. It found very few of the yeses.
That's the base rate at work: how common the yes is. When a yes is rare, accuracy hides it.
Two questions of every call
The bank's model is a logistic regression. From twelve things the bank knows before it calls, it gives each customer a chance of saying yes.
It picks the customers whose chance is over one half. So ask two things about every call. Did the model pick it? And did the customer say yes?
Pull the picks out: twenty-five here, nine hundred and seventy-five there. In each pile, the yeses go first.
Four kinds of answer
Now count.
Eighteen were picked and said yes: right picks.
Seven were picked and said no: wasted calls.
Ninety-five weren't picked, but said yes: missed yeses.
Eight hundred and eighty weren't picked, and said no: right no's.
That table of four... is called the confusion matrix.
Its cells also have the usual names. Positive means the model picked it. So a wasted call is a false positive, and a missed yes is a false negative.
Where the yeses went
Accuracy is just two of those cells, added up: eighteen, and eight hundred and eighty. Spot it: where are the customers the bank was looking for?
Most of them are in the missed yeses. Accuracy never shows that cell.
Precision
A model's answers can be sorted into four kinds: right picks, wasted calls, missed yeses, and right no's.
Now turn those counts into shares. First, of the customers the model picks, how many say yes? Look inside the picks.
Eighteen of twenty-five. Seventy-two percent.
That share is called precision: how often a pick is right. In the Probability course's words, it's the chance of a yes, given a pick.
Recall
Now turn it around. Of everyone who would say yes, how many does the model find? More than half of them, or less?
All the yeses: a hundred and thirteen. Picked: eighteen. Sixteen percent. That share is called recall. Turned around: the chance of a pick, given a yes. The same eighteen, divided by a different pile.
One alone can be fooled
Can one of them do the job alone? Pick everyone. Every yes is found, so recall is a hundred percent. And precision falls to eleven percent: nine out of ten calls are wasted.
Pick no one, and recall is zero. Recall alone can look perfect on a silly model. So you always read the two together.
Which mistake costs more
So which one matters more?
That depends on which mistake costs more. A wasted call costs the bank a few minutes. A missed yes loses a sale. So the bank leans toward recall: it would rather make some wasted calls than miss a yes.
This model leans the other way. It finds fewer than one in six of the yeses.
A spam filter is the other way around. Its picks are the emails it moves to spam, and its yeses are the real spam. Losing a real email costs more than letting a spam email through. So a spam filter leans toward precision.
In code
In real code, with scikit-learn, a dummy classifier says no to everyone. On the thousand calls, it scores zero point eight eight seven. The model's predict gives its picks. Then the confusion matrix prints the four counts. It has a row for each truth, no first, then yes. And a column for each answer, not picked first, then picked. So where do the wasted calls sit?
The row for no, the column for picked: seven.
The second column is the picks: seven and eighteen. The second row is the yeses: ninety-five and eighteen. Precision is zero point seven two. Recall is zero point one six.
And the classification report gives both, for the yeses and for the no's. These are the numbers reported for any model that answers yes or no, like a chatbot's safety filter.
Three ideas
So, accuracy can hide a rare yes, and the four counts show it.
Precision counts inside the model's picks.
Recall counts inside the real yeses.
Accuracy can hide a rare yes
Accuracy can hide a rare yes, so count all four kinds. Now try it on this lesson's page, and take the quiz. Find the recall for the no's.
You use this lesson in Lab 3: A call list the bank can trust, after Data leakage.
Facts last checked on .
