Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Chapter 11 — Lab: Metrics

Open in Colab

Lab Overview

You will compute the standard metrics from scratch and check them against scikit-learn, then use them to make a decision.

ExerciseTopicPoints
1The confusion matrix10
2Precision, recall and F115
3The ROC curve and its area20
4Average precision20
5Macro F1 for several classes15
6MAE, RMSE and R²20
ChallengeThe 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.


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.


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.


Exercise 3: The ROC Curve and Its Area (20 points)

  1. roc_points(y_true, scores) returns two arrays (fpr, tpr). Sort the distinct scores from highest to lowest; for each one as a threshold tt (positive when score ≥t\ge t) compute the false positive rate and the true positive rate. Put the point (0,0)(0, 0) first.

  2. auc(x, y) returns the area under the polyline by the trapezoid rule: ∑i(xi−xi−1)(yi+yi−1)/2\sum_i (x_{i} - x_{i-1})(y_{i} + y_{i-1})/2.


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 PnP_n and recall RnR_n; then AP=∑n(Rn−Rn−1) Pn\text{AP} = \sum_n (R_n - R_{n-1})\, P_n, starting from R0=0R_0 = 0.


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.


Exercise 6: MAE, RMSE and R² (20 points)

regression_metrics(y, y_hat) returns (mae, rmse, r2), with R2=1−∑(y−y^)2/∑(y−yˉ)2R^2 = 1 - \sum (y - \hat y)^2 / \sum (y - \bar y)^2.


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 ≥t\ge t) and returns (t, cost) with the lowest total cost miss_cost * fn + alarm_cost * fp; on a tie, the highest threshold.


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?