Chapter 11 — Lab: Metrics
Lab Overview¶
You will compute the standard metrics from scratch and check them against scikit-learn, then use them to make a decision.
| Exercise | Topic | Points |
|---|---|---|
| 1 | The confusion matrix | 10 |
| 2 | Precision, recall and F1 | 15 |
| 3 | The ROC curve and its area | 20 |
| 4 | Average precision | 20 |
| 5 | Macro F1 for several classes | 15 |
| 6 | MAE, RMSE and R² | 20 |
| Challenge | The cheapest threshold | +10 |
How it works. Each exercise has a function to complete where you see # TODO. Run the check cell under it: ✅ means your function is right, ❌ tells you what is wrong. Use NumPy and plain Python; scikit-learn appears only in the checks. Do not change the check cells.
import numpy as np
from sklearn import metrics as skm
def check(name, test):
"""Run one self-check: test() must return True; any exception or False is reported."""
try:
ok = test()
except NotImplementedError:
print(f'❌ {name}: not implemented yet'); return
except Exception as e:
print(f'❌ {name}: {type(e).__name__}: {e}'); return
print(f'✅ {name}' if ok else f'❌ {name}: wrong result')
rng = np.random.default_rng(0)
y_true = (rng.random(300) < 0.2).astype(int)
scores = np.clip(0.35 * y_true + rng.normal(0.3, 0.2, 300), 0, 1)
y_pred = (scores >= 0.5).astype(int)
print('Setup complete:', y_true.sum(), 'positives among', len(y_true))Exercise 1: The Confusion Matrix (10 points)¶
confusion(y_true, y_pred) returns (tp, fn, fp, tn) for labels 0 and 1, as plain integers.
def confusion(y_true, y_pred):
# TODO
raise NotImplementedErrorcheck('a small example', lambda: confusion([1, 1, 0, 0, 1], [1, 0, 1, 0, 1]) == (2, 1, 1, 1))
check('the same as scikit-learn', lambda: confusion(y_true, y_pred) == tuple(int(v) for v in skm.confusion_matrix(y_true, y_pred).ravel()[[3, 2, 1, 0]]))Exercise 2: Precision, Recall and F1 (15 points)¶
prf(tp, fn, fp) returns (precision, recall, f1). When a denominator is 0, the metric is 0.
def prf(tp, fn, fp):
# TODO
raise NotImplementedErrortp, fn, fp, tn = confusion(y_true, y_pred)
check('the cancer test of the chapter: 60, 4, 4', lambda: np.allclose(prf(60, 4, 4), [0.9375, 0.9375, 0.9375]))
check('matches scikit-learn', lambda: np.allclose(prf(tp, fn, fp), [skm.precision_score(y_true, y_pred), skm.recall_score(y_true, y_pred), skm.f1_score(y_true, y_pred)]))
check('nothing predicted positive: precision 0', lambda: prf(0, 5, 0) == (0.0, 0.0, 0.0))Exercise 3: The ROC Curve and Its Area (20 points)¶
roc_points(y_true, scores)returns two arrays(fpr, tpr). Sort the distinct scores from highest to lowest; for each one as a threshold (positive when score ) compute the false positive rate and the true positive rate. Put the point first.auc(x, y)returns the area under the polyline by the trapezoid rule: .
def roc_points(y_true, scores):
# TODO
raise NotImplementedError
def auc(x, y):
# TODO
raise NotImplementedErrorf, t = roc_points([0, 0, 1, 1], [0.1, 0.4, 0.35, 0.8])
check('four points', lambda: np.allclose(f, [0, 0, 0.5, 0.5, 1]) and np.allclose(t, [0, 0.5, 0.5, 1, 1]))
check('the area of that curve is 0.75', lambda: abs(auc(f, t) - 0.75) < 1e-12)
check('matches roc_auc_score on 300 examples', lambda: abs(auc(*roc_points(y_true, scores)) - skm.roc_auc_score(y_true, scores)) < 1e-9)Exercise 4: Average Precision (20 points)¶
average_precision(y_true, scores) follows scikit-learn’s definition: for each distinct score threshold from highest to lowest, compute precision and recall ; then , starting from .
def average_precision(y_true, scores):
# TODO
raise NotImplementedErrorcheck('a perfect ranking gives 1', lambda: abs(average_precision([0, 0, 1, 1], [0.1, 0.2, 0.8, 0.9]) - 1) < 1e-12)
check('matches scikit-learn', lambda: abs(average_precision(y_true, scores) - skm.average_precision_score(y_true, scores)) < 1e-9)
check('it is far below ROC AUC on imbalanced data with these scores', lambda: average_precision(y_true, scores) < skm.roc_auc_score(y_true, scores))Exercise 5: Macro F1 (15 points)¶
macro_f1(y_true, y_pred) computes the F1 of each class that appears in y_true (that class as “positive”, all others as “negative”), and returns their plain mean. Use your confusion and prf on binary versions of the labels.
def macro_f1(y_true, y_pred):
# TODO
raise NotImplementedErroryt = np.array([0] * 90 + [1] * 9 + [2] * 1); yp = yt.copy(); yp[95:] = 0
check('a rare class that is always missed drags the macro F1 down', lambda: abs(macro_f1(yt, yp) - skm.f1_score(yt, yp, average='macro')) < 1e-9)
check('while accuracy stays high', lambda: np.mean(yt == yp) > 0.9 and macro_f1(yt, yp) < 0.7)Exercise 6: MAE, RMSE and R² (20 points)¶
regression_metrics(y, y_hat) returns (mae, rmse, r2), with .
def regression_metrics(y, y_hat):
# TODO
raise NotImplementedErroryr = rng.normal(100, 20, 50); yh = yr + rng.normal(0, 10, 50)
m = regression_metrics(yr, yh)
check('matches scikit-learn', lambda: np.allclose(m, [skm.mean_absolute_error(yr, yh), np.sqrt(skm.mean_squared_error(yr, yh)), skm.r2_score(yr, yh)]))
check('predicting the mean gives R² = 0', lambda: abs(regression_metrics(yr, np.full(50, yr.mean()))[2]) < 1e-12)
check('one big error moves RMSE more than MAE', lambda: (lambda a, b: b[1] / a[1] > b[0] / a[0])(regression_metrics(np.arange(10), np.arange(10) + 10), regression_metrics(np.arange(10), np.arange(10) + np.array([10] * 9 + [100]))))Challenge: The Cheapest Threshold (+10 points)¶
cheapest_threshold(y_true, scores, miss_cost, alarm_cost) tries every distinct score as a threshold (positive when score ) and returns (t, cost) with the lowest total cost miss_cost * fn + alarm_cost * fp; on a tie, the highest threshold.
def cheapest_threshold(y_true, scores, miss_cost, alarm_cost):
# TODO
raise NotImplementedErrort1, c1 = cheapest_threshold(y_true, scores, 1, 1); t50, c50 = cheapest_threshold(y_true, scores, 50, 1)
check('expensive misses lower the threshold', lambda: t50 < t1)
check('the cost is the minimum over the thresholds', lambda: c50 == min(50 * np.sum((scores < t) & (y_true == 1)) + np.sum((scores >= t) & (y_true == 0)) for t in np.unique(scores)))Lab Report¶
Submit this notebook with:
every check cell showing ✅,
one paragraph: for a classifier you know of (a spam filter, a medical test, a credit decision), which metric would you optimise, which would you report next to it, and why?