Sub topic 1
From Model Scores to Labels
A binary classifier is usually described as something that answers "yes" or "no". Most models do something different internally. They compute a number for each example, and a separate rule turns that number into a yes or no. ROC curves and AUC evaluate the numbers, not the final yes or no answers. This chapter covers what those numbers are, how they become labels, and what is lost in the conversion.
Prerequisites
This chapter assumes you have:
- Binary classification basics: examples with features, a label of 0 (negative) or 1 (positive), and a trained model.
- The confusion matrix terms true positive, false positive, true negative and false negative. They are only named here. Later chapters use them.
- Basic Python and NumPy, including boolean arrays and comparison operators.
- Some familiarity with predicted probabilities or scores from a model such as logistic regression.
What a classifier actually outputs
For each example, a typical classifier produces a score. A score is a real number where a higher value means the model considers the positive class more likely. Different models produce different kinds of scores.
| Source | scikit-learn method | Typical range | Natural cutoff |
|---|---|---|---|
| Logistic regression, random forest, gradient boosting | `predict_proba` | 0 to 1 | 0.5 |
| Logistic regression, linear SVM | `decision_function` | Any real number | 0 |
| Hand-built ranking, such as a risk points total | None | Any | None |
All three kinds work for ROC analysis. The only property ROC analysis needs is that a higher score means "more likely positive". A score does not need to be a calibrated probability.
From score to label
A predicted label is the model's final 0 or 1 answer for an example. It comes from one comparison:
predicted label = 1 if score >= t, otherwise 0The value t is the decision threshold. The next chapter treats it in detail. For now, treat it as a number you can choose.
Methods like predict hide this step. For a binary logistic regression, predict applies the threshold 0.5 to the positive-class probability. The code below checks that.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
X, y = make_classification(
n_samples=1000, n_features=6, n_informative=3, random_state=0
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=0, stratify=y
)
model = LogisticRegression(max_iter=1000).fit(X_train, y_train)
proba = model.predict_proba(X_test)[:, 1] # score for the positive class
labels_default = model.predict(X_test)
labels_manual = (proba >= 0.5).astype(int)
print(np.array_equal(labels_default, labels_manual)) # Truepredict_proba returns one column per class. The column order follows model.classes_, which is sorted. With labels 0 and 1, column 1 is the positive class. Taking the wrong column is a common mistake, and it produces an AUC below 0.5.
One set of scores, many sets of labels
The threshold is a free choice, so one set of scores can produce many different sets of labels. Here is a four-example set that appears throughout this tutorial.
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.3, 0.05]:
y_pred = (y_score >= t).astype(int)
print(f"t={t:<4} predicted={y_pred}")This prints:
t=0.9 predicted=[0 0 0 0]
t=0.5 predicted=[0 0 0 1]
t=0.38 predicted=[0 1 0 1]
t=0.3 predicted=[0 1 1 1]
t=0.05 predicted=[1 1 1 1]Compare each row with y_true = [0 0 1 1]:
- At
t=0.9nothing is predicted positive. Every error is a missed positive. - At
t=0.5the model gets one positive and misses the other. It makes no false alarms. - At
t=0.38it catches one positive and also flags a negative. - At
t=0.3it catches both positives and flags one negative. - At
t=0.05everything is predicted positive.
Moving the threshold down always flags more examples as positive. It never flags fewer. Each threshold gives a different balance between missed positives and false alarms. A ROC curve is the record of that balance across every possible threshold, and a later chapter builds it.
Information lost when you keep only labels
A single set of labels discards how confident the model was. Take the examples scored 0.80 and 0.35 in the set above. Both are positives. At t=0.3 both get label 1, so the labels look identical. The model was much more sure about the first one, and that difference is gone.
Evaluating the labels alone has two consequences:
- Accuracy, precision and recall each describe the model at one threshold. Changing the threshold changes all three.
- Two models can have equal accuracy at 0.5 while one of them ranks examples far better. Labels alone cannot show that.
Evaluating the scores directly avoids both problems. That is the reason for ROC analysis.
Scores, probabilities and ranking
Many people read a score of 0.8 as "an 80% chance of being positive". That reading holds only if the model is calibrated, meaning that among examples scored about 0.8, about 80% really are positive. Many models are not calibrated. Random forests, boosted trees and SVMs often are not, and logistic regression usually comes closer.
ROC analysis does not need calibration. It uses only the order of the scores. Any strictly increasing transformation of the scores gives the same ROC curve, because the same examples fall above each threshold. The code below shows this. It compares the probability with the raw decision_function output, which is the same quantity before the sigmoid function is applied.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_score
X, y = make_classification(
n_samples=1000, n_features=6, n_informative=3, random_state=0
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=0, stratify=y
)
model = LogisticRegression(max_iter=1000).fit(X_train, y_train)
proba = model.predict_proba(X_test)[:, 1]
margin = model.decision_function(X_test) # log-odds, any real number
auc_proba = roc_auc_score(y_test, proba)
auc_margin = roc_auc_score(y_test, margin)
auc_cubed = roc_auc_score(y_test, proba ** 3)
print(np.isclose(auc_proba, auc_margin)) # True
print(np.isclose(auc_proba, auc_cubed)) # TrueAll three score sets rank the examples the same way, so the AUC is the same. A calibration step, such as isotonic regression, also does not change AUC if it strictly preserves order. It does change which threshold corresponds to which error rate.
Edge cases to watch
- Ties. Several examples can share one score. A rule of
score >= tflags all tied examples together, so ties can never be split by moving the threshold. Models that output coarse scores, such as a shallow decision tree with few leaves, produce many ties and a ROC curve with few points. >=versus>. This chapter predicts positive when the score is at or above the threshold. Some libraries use a strict>. The two rules differ only for examples that sit exactly on the threshold. Know which one your tool uses before you compare results.- Label encoding. The positive class must be the one the score favors. If your labels are strings such as
"spam"and"ham", passpos_labelto the scikit-learn metric functions, or encode the labels as 0 and 1 first. - Flipped scores. A score that increases with the negative class, such as a distance to the nearest known positive, must be negated before it is used. Otherwise ROC analysis will report a result below chance.
- Only one class present. If
y_truecontains only zeros or only ones, ROC metrics are undefined and scikit-learn raises an error. This can happen with small test folds in cross-validation. - Hard labels as scores. Passing
model.predict(X)instead ofpredict_proba(X)to a ROC function is allowed, but the result has only one useful threshold. The curve collapses to a single point joined to the corners, and the AUC is much less informative.
Common errors
- Using
predictoutput where scores are needed. Always pass probabilities or margins to ROC functions. - Taking
predict_proba(X)[:, 0]when the positive class is column 1. - Believing that a score of 0.5 always means "50% likely". That holds only for calibrated models.
- Choosing a threshold on the test set and then reporting performance on the same test set. Choose thresholds on validation data.
Exercise
A model gives the scores [0.2, 0.9, 0.5, 0.5] for four examples. Using the rule "predict positive if score >= 0.5", what are the predicted labels? What happens if you change the rule to "score > 0.5"?
Show answer
With >=, the labels are [0, 1, 1, 1], because both examples scored 0.5 are flagged. With >, the labels are [0, 1, 0, 0], because the two tied examples fall exactly on the threshold and are no longer flagged. The two rules differ only at scores equal to the threshold, and tied scores always move together.
Exercise
You train a logistic regression and call decision_function on the test set. Which threshold on these values matches the usual 0.5 threshold on predict_proba? Would switching from predict_proba to decision_function change the ROC AUC?
Show answer
The matching threshold is 0, because the sigmoid maps a margin of 0 to a probability of 0.5. The ROC AUC does not change, because the sigmoid is strictly increasing, so both scores rank the examples identically.