Lesson 8 of 227 min
Thresholds, ROC and PR curves
A model gives every case a chance, and you choose the line above which it says yes: lower it and it finds more yeses with more wasted picks, so set it from your budget or your costs, and judge the model by its curves.
After this lesson you can move a threshold, read the trade-off, and handle a rare class.
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.
Tune the threshold on folds
Put bank-additional-full.csv from UCI’s Bank Marketing dataset next to your notebook. Run these cells in order. Keep the 1,000 test calls aside. The tuner uses five folds of the remaining calls to choose the threshold that gives the best F1 score.
import pandas as pd
from sklearn.compose import make_column_transformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import TunedThresholdClassifierCV, 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())
tuned = TunedThresholdClassifierCV(model, scoring="f1", cv=5)
tuned.fit(X_train, y_train)
print(f"Threshold: {tuned.best_threshold_:.3f}")Threshold: 0.180
Set a threshold by hand
Use FixedThresholdClassifier when you already know the line you want. Its predict returns the picks at that line. Its predict_proba still returns the model’s chances.
from sklearn.metrics import precision_score, recall_score
from sklearn.model_selection import FixedThresholdClassifier
fixed = FixedThresholdClassifier(model, threshold=0.2).fit(X_train, y_train)
picks = fixed.predict(X_test)
print(f"{picks.sum()} picks, precision {precision_score(y_test, picks):.3f}")
print(f"Recall {recall_score(y_test, picks):.3f}")61 picks, precision 0.525 Recall 0.283
Turn costs into a line
With a wasted call costing one and a missed yes costing ten, break even when 1 - p = 10 * p. Use that threshold with calibrated chances. Among customers given a 20% chance, about 20% should say yes. CalibratedClassifierCV fits that adjustment on training folds.
from sklearn.calibration import CalibratedClassifierCV
cost_line = 1 / (1 + 10)
calibrated = CalibratedClassifierCV(model, cv=5).fit(X_train, y_train)
chance = calibrated.predict_proba(X_test)[:, 1]
picks = chance >= cost_line
wasted = (picks & ~y_test).sum()
missed = (~picks & y_test).sum()
print(f"Line {cost_line:.3f}, cost {wasted + 10 * missed}")Line 0.091, cost 645
Check every line
In scikit-learn 1.9 and later, confusion_matrix_at_thresholds returns the four counts for every distinct score and metric_at_thresholds runs a metric at those same scores. To choose a line, sweep on a validation set. Reserve the test calls for your final check.
from sklearn.metrics import confusion_matrix_at_thresholds, metric_at_thresholds
X_fit, X_val, y_fit, y_val = train_test_split(
X_train, y_train, test_size=0.25, stratify=y_train, random_state=1
)
val_chance = model.fit(X_fit, y_fit).predict_proba(X_val)[:, 1]
tn, fp, fn, tp, lines = confusion_matrix_at_thresholds(y_val, val_chance)
recall, _ = metric_at_thresholds(y_val, val_chance, recall_score)
print(f"At {lines[-1]:.3f}: recall {recall[-1]:.1f}, {int(fp[-1])} wasted calls")At 0.002: recall 1.0, 8915 wasted calls
Draw both curves
Pass the chances into both displays. The dashed reference for precision–recall is the share of actual yeses. Average precision weights precision by the gain in recall at each step.
from sklearn.metrics import PrecisionRecallDisplay, RocCurveDisplay
test_chance = fixed.predict_proba(X_test)[:, 1]
RocCurveDisplay.from_predictions(y_test, test_chance)
PrecisionRecallDisplay.from_predictions(y_test, test_chance, plot_chance_level=True)Count tied scores
ROC AUC gives a point when a yes ranks above a no and half a point when their scores tie. With several classes, compare each class with the rest using its own score column.
from sklearn.metrics import roc_auc_score
print(roc_auc_score([0, 1], [0.4, 0.4]))0.5
Run on Python 3.13, scikit-learn 1.9.1, pandas 3.1.1 and matplotlib. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: Precision, recall and the confusion matrix
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?
2 of 3
A missed yes costs the bank as much as ten wasted calls. Where should its line go, on the model's chance of a yes?
3 of 3
About 11 customers in 100 said yes. On them, roc_auc_score prints 0.739 and average_precision_score prints 0.375. What do the two say about the model?
The ideas in this lesson
- Threshold
- The line on a model's chance above which it says yes: lower it to find more yeses, with more wrong picks.
- ROC curve and its area
- Every threshold as a point, recall against the share of no's picked; the area is the chance a yes ranks above a no.
- Precision–recall curve
- Precision against recall at every threshold; for a rare yes it shows the wrong picks that the ROC curve hides.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Thresholds and their curves
Here's a puzzle. A bank's model gives every customer a chance of saying yes. The bank calls the ones over one half. Is one half the right line?
Keep your guess
Hold on to your guess.
These are a thousand real calls from a bank, offering a savings deposit, kept aside from the model's training. A hundred and thirteen people said yes: about one in nine, so a yes is rare.
The bank's model, a logistic regression, gives every customer a chance. At one half, it picks twenty-five.
In order, the surest first
A model that answers yes or no gives every case a chance first.
Now put the thousand customers in order, the most likely yes first, like a queue.
Yeses are more common near the front.
But a lot of them stand far back.
One half is a line across this queue.
Everyone in front of it is picked.
That line is called the threshold.
At one half, it picks the first twenty-five.
The four counts
Count the four kinds of answer, as before.
Precision counts in the picks: seventy-two percent.
Recall counts in the yeses: sixteen percent.
Most of the yeses still stand behind the line.
Lower the line
What happens if you lower the line, so it moves back along the queue? You'll find more yeses.
But what happens to the wasted calls? Make a guess.
At zero point two, the model picks sixty-one, and thirty-two of them say yes. Recall goes up, to twenty-eight percent. Precision goes down, to fifty-two percent.
A trade
Lower it again, to zero point one two.
Now it picks three hundred and seventeen, and seventy of them say yes.
Recall is sixty-two percent. Precision is twenty-two.
Every line is a trade-off. Lower it, and you find more yeses, and you waste more calls.
A line from a budget
So which line should the bank choose?
That depends on the job. Suppose the bank can make only a hundred calls. Of the hundred most likely customers, how many will say yes?
Thirty-six. A hundred customers picked at random would give about eleven, since about one in nine says yes.
With this budget, the line falls at zero point one six.
A line from the costs
Or the line comes from what each mistake costs. Suppose a missed yes costs the bank as much as ten wasted calls. Then a line's cost is its wasted calls, plus ten for every missed yes. Count that for every line. Where is the cheapest line: above one half, or below it?
The cost is lowest near zero point zero nine, about one chance in eleven. That costs about a third less than the line at one half. That line is far below one half. Why one in eleven? Call a customer whose chance is one in eleven. Ten times out of eleven, the call is wasted. Once, it brings a yes, and a yes is worth ten calls. So it breaks even. If a miss and a wasted call cost the same, it breaks even at one in two. That's when one half is the right line.
Every line at once
A model gives each case a chance, and a line, the threshold, says yes above it. Can you see every line at once? Walk down the queue from the front, one customer at a time. Each yes steps the path up. Each no steps it right. Up is recall: the share of the yeses found. Across is the share of the no's that get picked: the false alarms. That path is called the ROC curve.
The area under it
Now guess the path of a model that only picks at random.
The diagonal. It finds yeses and no's at the same rate. The area under the diagonal is zero point five. Under this model's curve, it's zero point seven four. A perfect model would get one. Pick one yes and one no at random. Seventy-four times out of a hundred, the yes has the higher chance.
What the ROC curve hides
The ROC curve scores the order of a model's chances. Here, zero point seven four. Sounds good?
Spot the catch. The number across is a share of what?
Across is a share of all eight hundred and eighty-seven no's. So when half the yeses are found, a step of zero point one six across looks small. But it's a hundred and forty-five wasted calls, for fifty-eight yeses.
The precision–recall curve
So put precision up instead, and recall across. This is the precision-recall curve.
Its floor is the share of yeses, zero point one one. That's picking everyone.
At half the yeses found, precision is twenty-nine percent: seven out of ten calls are wasted. The area under it is zero point three seven five. It's called the average precision: the precision you get, on average, as you find the yeses. When the yes is rare, read this curve.
In code
In real code, with scikit-learn, the model's predict proba gives every customer's chance.
A line is just a comparison: is the chance at least zero point two? Guess what it gives back.
A True or a False for every customer.
Sixty-one Trues: the picks.
Precision is about zero point five two.
Recall is about zero point two eight.
The area under the ROC curve is zero point seven four.
The average precision is zero point three seven five. And a tuned threshold classifier chooses the line for you, on folds of the training set.
Here, zero point one eight.
A safety filter on a chatbot works the same way.
It gives a chance that a message is unsafe, and its owner sets the line.
Three ideas
So: a model gives a chance, and you choose the line, from your budget or your costs. The ROC curve scores the whole order. And when the yes is rare, read the precision-recall curve.
Choose the line for the job
Choose the line for the job, not just one half. Now try it on this lesson's page, and take the quiz. Make a missed yes cost twice as much. Then find the cheapest line.
You use this lesson in Lab 3: A call list the bank can trust, after Data leakage.
Facts last checked on .
