Sub topic 2
The decision threshold
A classifier that outputs scores doesn't output labels. The decision threshold is the rule that turns one into the other. Every point on a ROC curve comes from one choice of threshold, so you need this idea before you can build or read the curve.
This chapter assumes you know binary classification basics, have used predicted probabilities from a model such as logistic regression, and can read basic Python and NumPy. Confusion matrix counts come in the next chapter, so this chapter only looks at predicted labels.
Scores are not decisions
Most classifiers compute a number for each example before they decide anything. Examples include:
- Predicted probabilities from
predict_proba, such as 0.82 for "positive". - Raw decision values from
decision_function, such as a logistic regression log-odds value or the signed distance from an SVM boundary. - Arbitrary scores from a tree ensemble or a hand-built rule.
Higher scores mean "more likely positive". Only the ordering is guaranteed to carry meaning. A score of 0.8 is not necessarily an 80% chance of being positive unless the model is calibrated.
The threshold rule
A decision threshold, written t, is a cutoff on the score. The standard rule is:
predict positive if score >= t
predict negative if score < tThe ROC tutorial uses "greater than or equal to" throughout, and so does the hand-built curve in a later chapter. Other libraries sometimes use strict ">", which changes results only when a score exactly equals the threshold.
Same scores, different labels
Here are four examples that appear throughout this tutorial. Two are negative and two are positive.
import numpy as np
y_true = np.array([0, 0, 1, 1])
y_score = np.array([0.1, 0.4, 0.35, 0.8])
for t in [0.9, 0.5, 0.38, 0.35, 0.1]:
y_pred = (y_score >= t).astype(int)
print(f"t={t:<4} predicted={y_pred} positives flagged={y_pred.sum()}")The output is:
t=0.9 predicted=[0 0 0 0] positives flagged=0
t=0.5 predicted=[0 0 0 1] positives flagged=1
t=0.38 predicted=[0 1 0 1] positives flagged=2
t=0.35 predicted=[0 1 1 1] positives flagged=3
t=0.1 predicted=[1 1 1 1] positives flagged=4The model and the scores did not change. Only t changed, and the predicted labels changed with it. Note that at t=0.38 the model flags the negative example scored 0.4 but misses the positive example scored 0.35. No threshold in this list gets every label right, because the scores themselves rank a negative (0.4) above a positive (0.35).
What moving the threshold does
Lowering t can only add examples to the predicted-positive set. Raising t can only remove them. This one-way behavior is why ROC curves are well-behaved: as you sweep t downward, the set of flagged examples only grows.
| Threshold direction | Predicted positives | Typical effect |
|---|---|---|
| Raise `t` | Fewer | Fewer false alarms, more missed positives |
| Lower `t` | More | More positives caught, more false alarms |
| `t` above every score | None | Nothing is flagged |
| `t` at or below every score | All | Everything is flagged |
The two extreme rows matter. They correspond to the two corners of the ROC curve, which a later chapter builds.
Only distinct scores matter
Between two adjacent score values, moving t changes nothing. In the example, any t in the range (0.35, 0.4] gives the same labels as t=0.38. A dataset with n distinct scores therefore produces at most n + 1 different sets of predictions:
| Threshold range | Flagged scores | Count |
|---|---|---|
| `t > 0.8` | none | 0 |
| `0.4 < t <= 0.8` | 0.8 | 1 |
| `0.35 < t <= 0.4` | 0.8, 0.4 | 2 |
| `0.1 < t <= 0.35` | 0.8, 0.4, 0.35 | 3 |
| `t <= 0.1` | all four | 4 |
This is why curve-building code loops over the unique scores and does not scan a grid such as 0.00, 0.01, 0.02. A grid can miss a boundary or repeat identical points.
Tied scores
If several examples share the same score, they always cross the threshold together. You cannot flag one and skip another. Ties between a positive and a negative produce a diagonal step in the ROC curve, and a later chapter covers this. For now, remember that tied examples cannot be separated by any threshold.
Thresholds and monotonic transformations
Applying an increasing function to every score, such as a logarithm, a logit, or s ** 3, preserves the order of the scores. Every set of predictions you could make before is still possible, using a transformed threshold.
import numpy as np
y_score = np.array([0.1, 0.4, 0.35, 0.8])
logit = np.log(y_score / (1 - y_score))
pred_prob = y_score >= 0.5
pred_logit = logit >= 0.0 # logit(0.5) is 0
print(np.array_equal(pred_prob, pred_logit)) # TrueThe probability threshold 0.5 and the log-odds threshold 0 are the same decision. This matters for ROC analysis: the curve depends only on the ranking of the scores, not on their scale. If you rescale or transform the scores monotonically, the ROC curve and AUC stay the same. The curve does not change, although the threshold values that label each point do.
Thresholds in scikit-learn
predict for a binary scikit-learn classifier applies a fixed default rule. For logistic regression, that rule is equivalent to a 0.5 threshold on the positive-class probability. You can reproduce it, and then use any other threshold yourself.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
X, y = make_classification(n_samples=500, weights=[0.8, 0.2], random_state=0)
model = LogisticRegression(max_iter=1000).fit(X, y)
proba = model.predict_proba(X)[:, 1]
default_pred = model.predict(X)
manual_pred = (proba >= 0.5).astype(int)
print(np.array_equal(default_pred, manual_pred)) # True unless a score is exactly 0.5
strict_pred = (proba >= 0.8).astype(int)
print(default_pred.sum(), strict_pred.sum()) # the stricter threshold flags fewerThe column [:, 1] selects the probability of class 1. Taking the wrong column is a common error that flips the meaning of every threshold. Check model.classes_ if the labels are not 0 and 1.
Why 0.5 is not special
0.5 is the default, and it fits one situation: a calibrated model, balanced classes, and equal costs for both kinds of mistake. Often at least one of those fails.
- Class imbalance. With 2% positives, a well-calibrated model rarely outputs probabilities above 0.5, so the default threshold flags almost nothing as positive.
- Unequal costs. In screening for a serious disease, missing a case costs more than a false alarm. A lower threshold is justified. In an automated account-closing system, a false alarm is expensive, so a higher one is.
- Uncalibrated scores. Many models, such as random forests, naive Bayes, and SVMs, produce scores that are not honest probabilities. A threshold of 0.5 on them has no stated meaning.
- Different score scales. A
decision_functionis centered at 0, not 0.5. Using 0.5 there is a mistake.
Where the threshold comes from in practice
Common ways to pick a threshold include the following. Only the last two use the ROC curve, and a later chapter covers them.
- Accept the library default.
- Set it from business cost: the score where the expected cost of flagging equals the expected cost of not flagging.
- Set it to meet a constraint, such as "no more than 5% false alarms".
- Pick the point on the ROC curve that maximizes a criterion such as Youden's J.
Whatever you choose, tune the threshold on validation data and report performance on separate test data. A threshold chosen on the test set makes the test result optimistic.
Common mistakes
- Applying the threshold to labels. Thresholds apply to scores only.
- Mixing
>=and>. The two conventions differ when a score equals the threshold, which happens often with tree models that output a few repeated values. - Scanning a fixed grid. This repeats identical decisions or misses a boundary between two close scores.
- Reading a probability threshold from a ROC curve of raw scores. If you computed the curve from
decision_functionoutput, the thresholds are on that scale, not on a 0 to 1 scale. - Assuming a threshold transfers. A threshold tuned on one dataset or class mix may not suit another. Distribution shift moves the scores.
Exercise
Using y_score = [0.1, 0.4, 0.35, 0.8] and the rule "predict positive if score >= t", what are the predicted labels for t = 0.4? How many distinct sets of predictions can these four scores produce across all possible thresholds?
Show answer
At t = 0.4 the scores 0.4 and 0.8 are at or above the threshold, so the predictions are [0, 1, 0, 1]. Four distinct scores give at most 4 + 1 = 5 distinct prediction sets: none flagged, one, two, three, or all four.
Exercise
A logistic regression model's decision_function returns raw log-odds values. Which threshold on those values matches the default probability threshold of 0.5, and why does a monotonic transformation of the scores leave the ROC curve unchanged?
Show answer
The matching threshold is 0, because logit(0.5) = log(0.5 / 0.5) = 0. A monotonic transformation keeps the ordering of the scores, so the same sets of examples fall above some threshold as before. The curve is built from those sets, so it does not change. Only the numeric threshold labels on its points change.