Chapter 11: Metrics — Implementation
A classification report in one call
Choosing a threshold from the costs
Precision at k: when only the top of the list is checked
Calibration: a reliability diagram, and recalibrating a weighted model
Letting scikit-learn tune the threshold
Which constant does each regression metric prefer?
A confidence interval for any metric, by bootstrap
import numpy as np
import warnings
import matplotlib.pyplot as plt
from sklearn.datasets import make_classification, load_diabetes
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 (classification_report, confusion_matrix, precision_score, recall_score, f1_score,
average_precision_score, brier_score_loss)
warnings.filterwarnings('ignore')
X, y = make_classification(n_samples=20000, n_features=20, n_informative=6, weights=[0.99], flip_y=0.002, class_sep=1.0, random_state=3)
X_dev, X_te, y_dev, y_te = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
X_tr, X_va, y_tr, y_va = train_test_split(X_dev, y_dev, test_size=0.3, random_state=1, stratify=y_dev)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=5000)).fit(X_tr, y_tr)
p_va, p_te = model.predict_proba(X_va)[:, 1], model.predict_proba(X_te)[:, 1]
print(f'training {len(y_tr)}, validation {len(y_va)} ({y_va.sum()} frauds), test {len(y_te)} ({y_te.sum()} frauds)')training 9800, validation 4200 (47 frauds), test 6000 (66 frauds)
The chapter’s fraud-like data, split three ways this time: the threshold will be chosen on validation data and reported on the test set.
1. A Classification Report¶
print(classification_report(y_te, (p_te >= 0.5).astype(int), target_names=['normal', 'fraud'], digits=3)) precision recall f1-score support
normal 0.992 0.999 0.996 5934
fraud 0.842 0.242 0.376 66
accuracy 0.991 6000
macro avg 0.917 0.621 0.686 6000
weighted avg 0.990 0.991 0.989 6000
One call gives precision, recall and F1 per class, their macro and weighted averages, and the support (the number of true examples of each class). The fraud row is the one that matters here; the normal row and the accuracy are almost perfect and say nothing.
2. A Threshold From the Costs¶
Suppose a missed fraud costs 50 times a false alarm. The best threshold minimises ; we search it on the validation data, then apply it once to the test data.
def cost(y_true, p, t, miss=50, alarm=1):
tn, fp, fn, tp = confusion_matrix(y_true, (p >= t).astype(int)).ravel()
return miss * fn + alarm * fp
grid = np.round(np.arange(0.01, 0.6, 0.01), 2)
costs = [cost(y_va, p_va, t) for t in grid]
best_t = grid[int(np.argmin(costs))]
pred = (p_te >= best_t).astype(int)
tn, fp, fn, tp = confusion_matrix(y_te, pred).ravel()
print(f'best threshold on validation: {best_t}')
print(f'test: TP {tp} FN {fn} FP {fp}; cost {cost(y_te, p_te, best_t)} against {cost(y_te, p_te, 0.5)} at the default 0.5')best threshold on validation: 0.02
test: TP 47 FN 19 FP 451; cost 1401 against 2503 at the default 0.5
The default threshold of 0.5 assumes both mistakes cost the same. They rarely do. Choosing the threshold is a business decision made with a metric, not a property of the model.
3. Precision at k¶
A fraud team can check 100 transactions a day. What matters is how many of the 100 highest-scored are real frauds:
def precision_at_k(y_true, scores, k):
top = np.argsort(-scores)[:k]
return float(np.mean(y_true[top]))
for k in [10, 50, 100, 200]:
print(f'precision@{k:<3d} {precision_at_k(y_te, p_te, k):.2f} ({int(precision_at_k(y_te, p_te, k) * k)} frauds among the top {k})')precision@10 1.00 (10 frauds among the top 10)
precision@50 0.56 (28 frauds among the top 50)
precision@100 0.35 (35 frauds among the top 100)
precision@200 0.20 (40 frauds among the top 200)
The model’s ranking is very good at the top of the list and degrades further down. When the number of checks is fixed, precision@k is the metric the users actually feel.
4. Calibration¶
A reliability diagram bins the predictions by predicted probability and plots, for each bin, the observed share of positives. A calibrated model follows the diagonal.
from sklearn.calibration import calibration_curve, CalibratedClassifierCV
weighted = make_pipeline(StandardScaler(), LogisticRegression(max_iter=5000, class_weight='balanced')).fit(X_tr, y_tr)
recal = CalibratedClassifierCV(make_pipeline(StandardScaler(), LogisticRegression(max_iter=5000, class_weight='balanced')),
method='isotonic', cv=5).fit(X_dev, y_dev)
for name, m in [('plain', model), ('class weights', weighted), ('class weights, recalibrated', recal)]:
pp = m.predict_proba(X_te)[:, 1]
print(f'{name:28s} mean probability {pp.mean():.4f} (true {y_te.mean():.4f}) Brier {brier_score_loss(y_te, pp):.4f}')plain mean probability 0.0106 (true 0.0110) Brier 0.0076
class weights mean probability 0.2270 (true 0.0110) Brier 0.1045
class weights, recalibrated mean probability 0.0110 (true 0.0110) Brier 0.0088
Source
plt.figure(figsize=(5.2, 4))
for name, m in [('plain', model), ('class weights', weighted), ('recalibrated', recal)]:
frac, mean_p = calibration_curve(y_te, m.predict_proba(X_te)[:, 1], n_bins=8, strategy='quantile')
plt.plot(mean_p, frac, 'o-', label=name)
plt.plot([0, 1], [0, 1], '--', color='gray'); plt.xlabel('predicted probability'); plt.ylabel('observed share of frauds')
plt.xscale('log'); plt.yscale('log'); plt.legend(); plt.title('reliability diagram'); plt.tight_layout(); plt.show()
Class weights push every probability up; isotonic recalibration (fitted inside cross-validation) brings them back in line, while keeping the weighted model’s ranking.
5. Tuning the Threshold in scikit-learn¶
TunedThresholdClassifierCV searches the threshold that maximises a metric by cross-validation, and wraps the result as an ordinary classifier.
from sklearn.model_selection import TunedThresholdClassifierCV
tuned = TunedThresholdClassifierCV(make_pipeline(StandardScaler(), LogisticRegression(max_iter=5000)), scoring='f1', cv=5).fit(X_dev, y_dev)
pt = tuned.predict(X_te)
print(f'threshold chosen for F1: {tuned.best_threshold_:.3f}; test precision {precision_score(y_te, pt):.3f}, '
f'recall {recall_score(y_te, pt):.3f}, F1 {f1_score(y_te, pt):.3f}')threshold chosen for F1: 0.211; test precision 0.636, recall 0.424, F1 0.509
6. Which Constant Does Each Metric Prefer?¶
A regression metric is also a statement about which prediction is “central”. The constant that minimises the mean squared error is the mean; the one that minimises the mean absolute error is the median. On a skewed target the two differ.
_, yd = load_diabetes(return_X_y=True)
cands = np.linspace(yd.min(), yd.max(), 2001)
best_mse = cands[np.argmin([np.mean((yd - c) ** 2) for c in cands])]
best_mae = cands[np.argmin([np.mean(np.abs(yd - c)) for c in cands])]
print(f'constant minimising MSE {best_mse:.1f} (mean {yd.mean():.1f}); minimising MAE {best_mae:.1f} (median {np.median(yd):.1f})')constant minimising MSE 152.1 (mean 152.1); minimising MAE 140.1 (median 140.5)
So a model trained with squared error aims at conditional means, one trained with absolute error at conditional medians: choose the training loss to match the metric you will be judged by.
7. A Confidence Interval for Any Metric¶
A test-set metric is a measurement on a sample (Chapter 10). Resampling the test set with replacement, and recomputing the metric each time, gives a bootstrap interval.
rng = np.random.default_rng(0)
aps = []
for _ in range(1000):
idx = rng.integers(0, len(y_te), len(y_te))
if y_te[idx].sum():
aps.append(average_precision_score(y_te[idx], p_te[idx]))
lo, hi = np.percentile(aps, [2.5, 97.5])
print(f'average precision {average_precision_score(y_te, p_te):.3f}, 95% bootstrap interval [{lo:.3f}, {hi:.3f}]')average precision 0.472, 95% bootstrap interval [0.358, 0.600]
With only 66 frauds in the test set, the average precision could plausibly be anywhere in a wide range. Report the interval, especially when the positives are few.
Summary¶
classification_reportgives per-class precision, recall, F1 and support.Choose the threshold from the costs, on validation data.
Precision@k measures what a team with a fixed budget of checks will see.
Reweighting distorts probabilities; recalibration restores them.
TunedThresholdClassifierCVtunes the threshold for a chosen metric.MSE favours means, MAE medians: train with the loss you will be judged by.
Bootstrap the test set to put an interval around any metric.