Chapter 11 — Assignment Project: Choosing the Metric for a Screening Test
Overview¶
A health service wants a model that flags patients for a follow-up test for a rare disease (about 2% of patients). A missed case is serious; a false alarm costs one extra appointment. Your job is not only to train a model, but to decide how it should be judged and where its threshold should be, and to tell the service what to expect.
The data are generated below (so that everyone has the same), with a fixed test set you must use only in Part D.
| Part | Task | Points |
|---|---|---|
| A | Why accuracy fails here | 15 |
| B | Curves: ROC against precision–recall | 20 |
| C | Remedies: threshold, weights, resampling | 25 |
| D | A threshold from the costs, and an honest report | 25 |
| E | A one-page memo | 15 |
import numpy as np
import warnings
import matplotlib.pyplot as plt
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split, cross_val_predict, StratifiedKFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import (confusion_matrix, accuracy_score, precision_score, recall_score, f1_score, fbeta_score,
roc_auc_score, average_precision_score, roc_curve, precision_recall_curve, brier_score_loss)
warnings.filterwarnings('ignore')
X, y = make_classification(n_samples=15000, n_features=25, n_informative=8, weights=[0.98], flip_y=0.005, class_sep=0.9, random_state=21)
X_dev, X_test, y_dev, y_test = train_test_split(X, y, test_size=0.25, random_state=0, stratify=y)
print(f'{y.mean():.1%} positives; development set {len(y_dev)} ({y_dev.sum()} positives); test set {len(y_test)} ({y_test.sum()} positives)')Part A — Why Accuracy Fails (15 points)¶
Compute the cross-validated accuracy (5-fold, stratified, on the development set) of a model that always predicts “healthy”, and of a logistic regression at threshold 0.5.
For the logistic regression, give the confusion matrix (from
cross_val_predict), the precision, the recall and the balanced accuracy.In three sentences, explain to a non-specialist why the accuracy is misleading here.
# Your code hereYour explanation:
Part B — ROC Against Precision–Recall (20 points)¶
Add a random forest (300 trees) and compute its cross-validated probabilities the same way.
For both models, report ROC AUC and average precision, and plot both curves side by side.
Which metric separates the two models more clearly? Which would you show the health service, and why?
# Your code hereYour answer:
Part C — Remedies (25 points)¶
For the better model of Part B, compare on the development set (cross-validated):
the default threshold of 0.5;
the threshold that maximises (recall counts twice as much as precision);
class_weight='balanced'(or'balanced_subsample'for a forest) with the threshold 0.5.
Report precision, recall, and the mean predicted probability for each. What does the last column tell you about the probabilities of option 3?
# Your code hereYour comparison:
Part D — A Threshold From the Costs (25 points)¶
The service estimates that a missed case costs as much as 40 unnecessary appointments.
On the development set’s cross-validated probabilities, find the threshold that minimises .
Refit the chosen model on the whole development set, and apply that threshold to the test set, once. Report the confusion matrix, recall, precision and the total cost.
Give a 95% bootstrap interval for the test recall (1 000 resamples).
# Your code hereYour report:
Part E — Memo (15 points)¶
One page for the health service: the metric you optimised and why; the threshold and what it means in patients (out of 1 000 patients, how many flagged, how many cases found, how many missed); the uncertainty; and one thing that would make you change the threshold.
Grading Rubric¶
| Criterion | Excellent | Adequate | Insufficient |
|---|---|---|---|
| A (15) | correct numbers, a clear plain-language explanation | numbers only | accuracy defended |
| B (20) | both curves, the right metric argued from the imbalance | numbers without argument | ROC only |
| C (25) | three options compared, the probability distortion explained | options without interpretation | missing |
| D (25) | threshold chosen on development data, test used once, interval given | no interval | threshold chosen on the test set |
| E (15) | concrete, in patients, honest about uncertainty | generic | missing |