Sub topic 13
Measuring performance: accuracy, precision, recall, ROC AUC
This chapter assumes you can fit a logistic regression, that you know it outputs a probability which is then compared with a threshold, and that you have used a train/test split. Here you learn which numbers to compute on the held-out set, what each one hides, and how they relate to the threshold.
Start from the confusion matrix
A logistic regression gives a probability. A threshold, 0.5 by default, turns it into a label. Comparing labels with the truth gives four counts for the positive class:
- True positive (TP): predicted positive, actually positive.
- False positive (FP): predicted positive, actually negative.
- False negative (FN): predicted negative, actually positive.
- True negative (TN): predicted negative, actually negative.
Every threshold-based metric below is a ratio of these four counts. Changing the threshold moves examples between cells, so it changes every one of those metrics.
The threshold-based metrics
| Metric | Formula | Question it answers |
|---|---|---|
| Accuracy | (TP + TN) / all | How often is the label right? |
| Precision | TP / (TP + FP) | Of the examples I flagged, how many were real? |
| Recall (sensitivity) | TP / (TP + FN) | Of the real positives, how many did I find? |
| Specificity | TN / (TN + FP) | Of the real negatives, how many did I leave alone? |
| F1 | 2PR / (P + R) | Harmonic mean of precision and recall |
Precision and recall pull against each other. A lower threshold flags more examples, so recall rises and precision usually falls. A higher threshold does the opposite.
The F1 score is a harmonic mean, so it is low if either precision or recall is low. It weights the two equally, which is rarely what your costs say. Use it for a quick comparison, not as a decision rule.
Why accuracy misleads
Suppose 1% of transactions are fraud. A model that always predicts "not fraud" has 99% accuracy and catches no fraud. Accuracy is dominated by the majority class. Whenever classes are imbalanced, or the two error types have different costs, read precision and recall for the positive class instead.
Computing everything from the confusion matrix
This example fits the pipeline from earlier chapters and derives each metric by hand, then checks it against scikit-learn.
from sklearn.datasets import load_breast_cancer
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 (
accuracy_score, confusion_matrix, precision_score, recall_score,
roc_auc_score, average_precision_score,
)
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=0
)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
model.fit(X_train, y_train)
proba = model.predict_proba(X_test)[:, 1]
y_pred = (proba >= 0.5).astype(int)
tn, fp, fn, tp = confusion_matrix(y_test, y_pred).ravel()
print("TN, FP, FN, TP:", tn, fp, fn, tp)
print("accuracy :", (tp + tn) / (tp + tn + fp + fn), accuracy_score(y_test, y_pred))
print("precision:", tp / (tp + fp), precision_score(y_test, y_pred))
print("recall :", tp / (tp + fn), recall_score(y_test, y_pred))
print("ROC AUC :", roc_auc_score(y_test, proba))
print("PR AUC :", average_precision_score(y_test, proba))confusion_matrix returns rows as true labels and columns as predicted labels, in sorted label order. For labels 0 and 1, .ravel() therefore gives TN, FP, FN, TP, in that order.
ROC curves and ROC AUC
The threshold metrics depend on one chosen threshold. The ROC curve removes that dependence by sweeping the threshold from 1 down to 0. At each threshold it plots:
- x-axis: false positive rate, FP / (FP + TN).
- y-axis: true positive rate (recall), TP / (TP + FN).
A random scorer follows the diagonal. A perfect scorer reaches the top-left corner. The area under the curve (ROC AUC) is a single number between 0 and 1, where 0.5 is chance.
AUC has a direct meaning: it is the probability that a randomly chosen positive example gets a higher score than a randomly chosen negative one. It measures ranking quality only. It ignores the threshold and says nothing about whether the probabilities themselves are accurate. A model can have a high AUC and badly miscalibrated probabilities.
Pass roc_auc_score the probabilities (or decision_function scores), not the hard labels. Hard labels collapse the curve to a single point and give a misleadingly low value.
Precision-recall curves for imbalanced data
The false positive rate divides by all negatives. When negatives are very numerous, thousands of false positives barely move that rate, so ROC AUC can look excellent while precision is poor. The precision-recall (PR) curve plots precision against recall and reacts directly to false positives. average_precision_score summarizes it.
The baseline also differs. A random scorer's ROC AUC is 0.5 regardless of class balance. A random scorer's PR curve sits at the positive-class rate, for example 0.01 with 1% positives. Compare PR AUC with that baseline, not with 0.5.
| Situation | Prefer |
|---|---|
| Balanced classes, ranking quality matters | ROC AUC |
| Rare positive class | PR curve and average precision |
| A fixed operating point is required | Precision and recall at that threshold |
Seeing the threshold trade-off
To see the trade directly, evaluate the same probabilities at several thresholds.
for threshold in (0.3, 0.5, 0.7, 0.9):
y_t = (proba >= threshold).astype(int)
print(
threshold,
round(precision_score(y_test, y_t), 3),
round(recall_score(y_test, y_t), 3),
)Recall falls as the threshold rises. Precision tends to rise but is not guaranteed to do so monotonically on a small test set. A later chapter covers choosing the threshold from your costs.
Common errors
- Reporting training-set metrics. The model has already fit those examples. Compute metrics on held-out data, or with cross-validation.
- Tuning the threshold on the test set. Choose it on validation data, then report the test result once.
- Using
predictoutput for AUC. Use probabilities. - Dropping
stratify=yon imbalanced data. A small test set may then contain too few positives for stable estimates. - Averaging across classes without knowing how. In multiclass reports, macro averaging weights classes equally and weighted averaging weights them by support.
Exercise
A test set has 1000 examples. The model produces TP = 40, FP = 10, FN = 20, TN = 930. Compute accuracy, precision and recall. Then explain why accuracy looks good here even though a third of the positives are missed.
Show answer
Accuracy = (40 + 930) / 1000 = 0.97. Precision = 40 / (40 + 10) = 0.80. Recall = 40 / (40 + 20) ≈ 0.667. There are only 60 positives against 940 negatives, so the large TN count dominates accuracy. The 20 missed positives cost only 2 percentage points of accuracy but reduce recall to about two thirds.
Exercise
A fraud model has ROC AUC 0.97 on data with 0.5% positives, but the fraud team complains that most alerts are false. Which metric should you check, and why can the AUC still be high?
Show answer
Check precision, and the precision-recall curve with average precision. The false positive rate divides by the very large number of negatives, so many false positives still give a small rate and a high ROC AUC. Precision divides by the number of flagged examples, so it shows that most alerts are wrong.