Lesson 2 of 9
ROC Curves, PR Curves & AUC: Threshold Tuning for Asymmetric Costs
A classifier's raw output is continuous probability scores; converting them to binary decisions requires choosing a classification threshold t. The Receiver Operating Characteristic (ROC) curve plots True Positive Rate (Sensitivity) vs False Positive Rate (1 - Specificity) across all possible thresholds t in [0, 1]. The Precision-Recall (PR) curve plots Precision vs Recall. Understanding when to use ROC-AUC vs PR-AUC is essential for imbalanced classification.
ROC Curve vs Precision-Recall Curve on Imbalanced Data
import numpy as np
import pandas as pd
from sklearn.metrics import roc_curve, precision_recall_curve, auc, roc_auc_score, average_precision_score
# Simulate imbalanced fraud scenario (99% normal, 1% fraud)
np.random.seed(42)
n = 10_000
y_true = np.random.choice([0, 1], size=n, p=[0.99, 0.01])
# Model generates probabilities
y_scores = np.where(y_true == 1, np.random.beta(4, 2, n), np.random.beta(1, 12, n))
# 1. ROC CURVE METRICS
fpr, tpr, roc_thresholds = roc_curve(y_true, y_scores)
roc_auc = roc_auc_score(y_true, y_scores)
# 2. PRECISION-RECALL CURVE METRICS
precision, recall, pr_thresholds = precision_recall_curve(y_true, y_scores)
pr_auc = average_precision_score(y_true, y_scores)
print("=== ROC-AUC VS PR-AUC BENCHMARK ===")
print(f"ROC-AUC Score : {roc_auc:.4f} (Appears deceptively exceptional!)")
print(f"PR-AUC Score : {pr_auc:.4f} (Reveals true minority precision challenge)")
# 3. THRESHOLD TUNING FOR COST-SENSITIVE BUSINESS OPTIMIZATION
# Cost function: False Negative = $500, False Positive = $20, TP = $0, TN = $0
costs = []
for t in roc_thresholds:
y_pred_t = (y_scores >= t).astype(int)
fn = np.sum((y_true == 1) & (y_pred_t == 0))
fp = np.sum((y_true == 0) & (y_pred_t == 1))
total_cost = fn * 500.0 + fp * 20.0
costs.append(total_cost)
optimal_idx = np.argmin(costs)
optimal_threshold = roc_thresholds[optimal_idx]
min_cost = costs[optimal_idx]
print(f"\nOptimal Business Decision Threshold : {optimal_threshold:.4f}")
print(f"Minimized Expected Cost : ${min_cost:,.2f}")
print(f"Default (t=0.5) Cost : ${costs[np.argmin(np.abs(roc_thresholds - 0.5))]:,.2f}")Pro Tip: When to Use PR-AUC Over ROC-AUC
Always use PR-AUC (Average Precision) when the positive class is rare (<5% prevalence). In severe imbalance, a model can incur 10,000 false positives while maintaining a low False Positive Rate (because the negative class has 1,000,000 samples). ROC-AUC stays high (~0.95), while PR-AUC collapses to ~0.20, exposing the true flood of false alarms.
MlROCCurveAUC Visual Representation
Hands-On Challenge: Find the Equal Error Rate (EER) Threshold
Write a function that calculates the Equal Error Rate (EER) threshold where the False Acceptance Rate (FPR) equals the False Rejection Rate (FNR = 1 - TPR) on a biometric verification dataset.
Quick Quiz & Key Concept Checks
Common Pitfall: Threshold-Tuning on the Held-Out Test Set
Sweeping thresholds to find the minimum cost point directly on the test set causes threshold leakage. Tune the operational decision threshold on your validation set (or cross-validation folds), and evaluate that fixed threshold on the untouched test set.