ML AUC - ROC Curve
Most classifiers don't really output "yes" or "no". They output a score or probability, and a threshold (0.5 by default) turns it into a class. Move the threshold and the trade-off between catching positives and raising false alarms changes. The ROC curve shows that trade-off for every possible threshold, and the AUC (area under the curve) condenses it into one number.
Thresholds change the confusion matrix
Here are the predicted fraud probabilities for 10 card transactions, and whether each really was fraud:
import numpy as np
from sklearn.metrics import confusion_matrix
actual = np.array([0, 0, 0, 0, 0, 0, 1, 0, 1, 1])
prob = np.array([0.05, 0.10, 0.20, 0.30, 0.35, 0.55, 0.60, 0.70, 0.80, 0.95])
for threshold in [0.25, 0.5, 0.75]:
predicted = (prob >= threshold).astype(int)
tn, fp, fn, tp = confusion_matrix(actual, predicted).ravel()
print(f"threshold {threshold}: TP={tp} FN={fn} FP={fp} TN={tn}")threshold 0.25: TP=3 FN=0 FP=4 TN=3
threshold 0.5: TP=3 FN=0 FP=2 TN=5
threshold 0.75: TP=2 FN=1 FP=0 TN=7
A low threshold catches every fraud but blocks many honest customers; a high threshold rarely bothers honest customers but lets fraud through. Which is better depends on the costs — but to compare models, we want a summary that doesn't depend on one chosen threshold.
The ROC curve
For each threshold the ROC curve plots two rates:
- True Positive Rate (TPR, recall) = TP / (TP + FN): share of real positives caught (y-axis),
- False Positive Rate (FPR) = FP / (FP + TN): share of negatives wrongly flagged (x-axis).
A perfect model reaches the top-left corner (TPR 1, FPR 0). A model that guesses randomly follows the diagonal.
import numpy as np
from sklearn.metrics import roc_curve, roc_auc_score
actual = np.array([0, 0, 0, 0, 0, 0, 1, 0, 1, 1])
prob = np.array([0.05, 0.10, 0.20, 0.30, 0.35, 0.55, 0.60, 0.70, 0.80, 0.95])
fpr, tpr, thresholds = roc_curve(actual, prob)
for f, t, th in zip(fpr, tpr, thresholds):
print(f"threshold {th:5.2f} FPR={f:.3f} TPR={t:.3f}")
print("AUC:", round(roc_auc_score(actual, prob), 3))threshold inf FPR=0.000 TPR=0.000
threshold 0.95 FPR=0.000 TPR=0.333
threshold 0.80 FPR=0.000 TPR=0.667
threshold 0.70 FPR=0.143 TPR=0.667
threshold 0.60 FPR=0.143 TPR=1.000
threshold 0.05 FPR=1.000 TPR=1.000
AUC: 0.952
The first threshold is inf: nothing is predicted positive, so both rates are 0. roc_curve only lists thresholds where the curve actually changes direction.
AUC: area under the curve
AUC ranges from 0.5 (random guessing) to 1.0 (perfect). It has a neat interpretation: the probability that a randomly chosen positive gets a higher score than a randomly chosen negative. In our toy example the frauds outrank most, but not all, honest transactions.
| AUC | Rough meaning |
|---|---|
| 0.5 | no better than a coin flip |
| 0.7–0.8 | acceptable |
| 0.8–0.9 | good |
| > 0.9 | excellent (check for leakage if it looks too good!) |
Comparing two models
Let's generate an imbalanced data set — only 10 % positives, like fraud or rare diseases — and compare a logistic regression with a shallow decision tree:
import matplotlib.pyplot as plt
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import roc_curve, roc_auc_score, accuracy_score
X, y = make_classification(n_samples=1000, n_features=8, n_informative=4,
weights=[0.9, 0.1], random_state=4)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
models = {
"logistic": LogisticRegression(max_iter=1000),
"tree (depth 2)": DecisionTreeClassifier(max_depth=2, random_state=0),
}
for name, model in models.items():
model.fit(X_train, y_train)
scores = model.predict_proba(X_test)[:, 1]
fpr, tpr, _ = roc_curve(y_test, scores)
auc = roc_auc_score(y_test, scores)
acc = accuracy_score(y_test, model.predict(X_test))
plt.plot(fpr, tpr, label=f"{name} (AUC = {auc:.3f})")
print(f"{name:15} accuracy={acc:.3f} AUC={auc:.3f}")
plt.plot([0, 1], [0, 1], "k--", label="random guess")
plt.xlabel("False positive rate")
plt.ylabel("True positive rate")
plt.legend()
plt.show()logistic accuracy=0.920 AUC=0.900
tree (depth 2) accuracy=0.923 AUC=0.863
Accuracy and AUC can tell different stories: on imbalanced data, accuracy is dominated by the large negative class, while AUC measures how well the model ranks positives above negatives.
Why accuracy misleads on imbalanced data
A "model" that always says "not fraud" is about 90 % accurate here — and completely useless. Its AUC exposes it:
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.dummy import DummyClassifier
from sklearn.metrics import accuracy_score, roc_auc_score
X, y = make_classification(n_samples=1000, n_features=8, n_informative=4,
weights=[0.9, 0.1], random_state=4)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
lazy = DummyClassifier(strategy="most_frequent").fit(X_train, y_train)
print("accuracy:", round(accuracy_score(y_test, lazy.predict(X_test)), 3))
print("AUC: ", roc_auc_score(y_test, lazy.predict_proba(X_test)[:, 1]))accuracy: 0.897
AUC: 0.5
DummyClassifier is a useful baseline: any real model should clearly beat it.
Tip: For heavily imbalanced data, also look at the precision–recall curve (
precision_recall_curve,average_precision_score). It focuses on the rare positive class and is less flattered by the many easy negatives.
Go further: ROC-AUC, PR-AUC and Average Precision adds the precision-recall curve and explains why it is the better report when positives are rare.
Test yourself
What does the x-axis of a ROC curve show?
- True positive rate
- False positive rate
- Precision
- Threshold
What AUC does a model that guesses at random have?
- 0
- 0.5
- 0.9
- 1.0
Which input does roc_auc_score need besides the true labels?
- Hard 0/1 predictions only
- Scores or probabilities for the positive class
- The confusion matrix
- The training data