Lesson 7 of 10 · 3 min
ROC Curve & AUC
WHY: Accuracy, Precision, Recall all depend on the threshold (default 0.5). ROC curve shows how well the model separates classes across ALL thresholds.
Key Terms
| Term | Formula | Meaning |
|---|---|---|
| TPR (True Positive Rate) | TP / (TP + FN) | Same as Recall |
| FPR (False Positive Rate) | FP / (FP + TN) | Rate of false alarms |
How ROC Works
At each threshold value (0.0 to 1.0), calculate TPR and FPR. Plot TPR (y-axis) vs FPR (x-axis). This curve is the ROC curve.
Worked Example — Two Points on the ROC Curve
10 patients, model outputs probabilities. We test two thresholds:
At threshold = 0.8 (strict — only flag very confident positives):
- TP = 3, FP = 1, TN = 4, FN = 2
- TPR = 3 / (3+2) = 0.60 (caught 60% of sick patients)
- FPR = 1 / (1+4) = 0.20 (20% of healthy patients wrongly flagged)
- ROC point: (0.20, 0.60)
At threshold = 0.5 (lenient — flag more as positive):
- TP = 4, FP = 3, TN = 2, FN = 1
- TPR = 4 / (4+1) = 0.80 (caught more sick patients)
- FPR = 3 / (3+2) = 0.60 (but more healthy patients wrongly flagged)
- ROC point: (0.60, 0.80)
Pattern: Lower threshold → catch more real positives (higher TPR) → but also more false alarms (higher FPR). ROC curve plots ALL thresholds. AUC = total area under that curve = how well the model separates classes regardless of threshold.
AUC — Area Under the ROC Curve
| AUC Value | Model Quality |
|---|---|
| 1.0 | Perfect — never makes mistakes |
| 0.9+ | Excellent |
| 0.8–0.9 | Good |
| 0.7–0.8 | Fair |
| 0.5 | Random guessing (diagonal line) |
| < 0.5 | Worse than random |
Analogy: AUC measures how good the model is at ranking a random positive higher than a random negative. AUC = 0.95 means: pick one sick patient and one healthy patient at random — the model ranks the sick patient higher 95% of the time.
from sklearn.metrics import roc_curve, roc_auc_score
import matplotlib.pyplot as plt
# Get probabilities (not class labels)
y_prob = model.predict_proba(X_test)[:, 1] # probability of positive class
# Calculate ROC curve points
fpr, tpr, thresholds = roc_curve(y_test, y_prob)
# Calculate AUC score
auc = roc_auc_score(y_test, y_prob)
print(f"AUC Score: {auc:.4f}")
# Output: AUC Score: 0.9971
# Plot the ROC curve
plt.figure(figsize=(8, 6))
plt.plot(fpr, tpr, label=f'Logistic Regression (AUC = {auc:.3f})', color='blue')
plt.plot([0, 1], [0, 1], 'k--', label='Random Classifier (AUC = 0.5)') # diagonal line
plt.xlabel('False Positive Rate (FPR)')
plt.ylabel('True Positive Rate (TPR / Recall)')
plt.title('ROC Curve')
plt.legend()
plt.grid(True)
plt.show()
