5. ROC Curves & Decision Thresholds
Understanding the ROC Curve and Area Under the Curve (AUC)
The Receiver Operating Characteristic (ROC) curve is a fundamental tool for evaluating binary classification models. It plots the True Positive Rate (TPR), also known as Sensitivity or Recall, against the False Positive Rate (FPR), which is equivalent to 1 minus Specificity. This plotting occurs across all possible classification decision thresholds ranging from 0.0 to 1.0.
The True Positive Rate measures the proportion of actual positive cases that are correctly identified. The False Positive Rate measures the proportion of actual negative cases that are incorrectly flagged as positive. By visualizing the trade-off between these two metrics at every decision threshold, data scientists can understand how well a model separates the positive and negative classes.
The Area Under the Curve (AUC) summarizes the entire ROC curve into a single metric. An AUC of 1.0 indicates a perfect classifier that achieves 100% sensitivity with 0% false positives, while an AUC of 0.5 represents a model with performance no better than random guessing. Mathematically, the AUC represents the probability that a randomly chosen positive instance will be ranked higher by the model than a randomly chosen negative instance.
import numpy as np from sklearn.metrics import roc_curve, auc y_true = np.array([0, 0, 1, 1, 0, 1, 0, 1, 1, 0]) y_scores = np.array([0.1, 0.4, 0.35, 0.8, 0.2, 0.9, 0.05, 0.7, 0.6, 0.15]) fpr, tpr, thresholds = roc_curve(y_true, y_scores) roc_auc = auc(fpr, tpr) print('FPR:', fpr) print('TPR:', tpr) print('AUC:', roc_auc)
Precision-Recall (PR) Curves and When to Prefer Them
While ROC curves are useful for general ranking, they can paint an overly optimistic picture of model performance on datasets with severe class imbalances. In scenarios like fraud detection or rare medical diagnosis, where the negative class represents 99.9% of the dataset, the False Positive Rate can remain very low even if the model produces a high absolute number of false positives.
To address this, we use the Precision-Recall (PR) curve. Precision measures the proportion of positive predictions that are actually correct, directly focusing on the impact of false positives relative to predicted positives. Recall measures how many of the actual positives were successfully found. The PR curve plots Precision against Recall across all thresholds.
Below is a comparison of when to use ROC vs. PR curves:
| Feature | ROC Curve | Precision-Recall (PR) Curve |
|---|---|---|
| Imbalance Sensitivity | Insensitive. Remains stable when negatives dominate. | Highly sensitive. Shows dramatic changes when positives are rare. |
| Focus Area | Overall class separation and general ranking performance. | Correctness of positive predictions (minimizing false positives). |
import numpy as np from sklearn.metrics import precision_recall_curve, auc y_true = np.array([0, 0, 0, 0, 0, 1, 0, 1, 0, 1]) y_scores = np.array([0.05, 0.1, 0.15, 0.2, 0.25, 0.9, 0.3, 0.85, 0.4, 0.75]) precision, recall, thresholds = precision_recall_curve(y_true, y_scores) pr_auc = auc(recall, precision) print('Precision:', precision) print('Recall:', recall) print('PR-AUC:', pr_auc)
Threshold Tuning: Optimizing the Decision Boundary
By default, binary classifiers convert predicted probabilities into hard class predictions using a fixed decision threshold of 0.5. If the model's output probability is greater than or equal to 0.5, it predicts positive; otherwise, it predicts negative. However, 0.5 is rarely the optimal threshold for real-world business scenarios.
Threshold tuning involves shifting this decision boundary to optimize for a specific business goal. For example, in a medical diagnostic model, we may want to lower the threshold (e.g., to 0.2) to capture as many True Positives as possible, even if it increases False Positives. Conversely, in a spam filter, we might raise the threshold to 0.8 to avoid moving important emails to the spam folder.
To find the optimal threshold, we evaluate the model's outputs across a range of thresholds and select the one that maximizes a specific metric, such as the F1-score, or minimizes a custom cost function that assigns financial weight to False Positives and False Negatives.
import numpy as np from sklearn.metrics import f1_score y_true = np.array([0, 1, 0, 0, 1, 1, 0, 1, 0, 1]) y_probs = np.array([0.15, 0.45, 0.2, 0.3, 0.75, 0.6, 0.35, 0.8, 0.1, 0.55]) best_threshold = 0.5 best_f1 = 0.0 for threshold in np.arange(0.1, 0.9, 0.05): preds = (y_probs >= threshold).astype(int) score = f1_score(y_true, preds) if score > best_f1: best_f1 = score best_threshold = threshold print(f'Optimal Threshold: {best_threshold:.2f} with F1-Score: {best_f1:.4f}')
Evaluating Performance in Python: roc_auc_score and average_precision_score
Scikit-Learn provides two primary functions for computing the overall performance of continuous model predictions before thresholding: roc_auc_score and average_precision_score. These functions directly assess the model's ranking ability, allowing you to quantify classification quality without choosing a specific arbitrary threshold.
roc_auc_score calculates the Area Under the Receiver Operating Characteristic curve. It requires the true labels and the predicted probabilities of the positive class. If your model produces multi-class probabilities, you must extract only the column containing the positive class probabilities (typically column index 1).
average_precision_score calculates the average precision across all thresholds, which acts as an excellent approximation of the Area Under the Precision-Recall curve. This metric is computed as the weighted mean of precisions achieved at each threshold, with the increase in recall from the previous threshold serving as the weight.
import numpy as np from sklearn.metrics import roc_auc_score, average_precision_score y_true = np.array([0, 1, 0, 1, 0, 1, 1, 0, 0, 1]) y_probs = np.array([0.1, 0.85, 0.35, 0.9, 0.2, 0.75, 0.65, 0.4, 0.15, 0.8]) auc_score = roc_auc_score(y_true, y_probs) ap_score = average_precision_score(y_true, y_probs) print(f'ROC AUC Score: {auc_score:.4f}') print(f'Average Precision Score: {ap_score:.4f}')
Knowledge Check
Ready to test your understanding of 5. ROC Curves & Decision Thresholds?