ML Projects Exercises
Fourteen exercises on the skills every project in this course needs: framing, metrics, splits, leakage, baselines, thresholds under a budget, error analysis, data for vision and language, evaluation of detectors and retrieval, shipping and the write-up. They are not tied to one project; most of them could come up in any. Try each before opening the answer. The runnable ones work in your browser: change the numbers and run them again.
1. Pick the metric
For each project, choose the headline metric and say why: a) house prices for estate agents who quote a price range, b) fraud detection with a team that can review 200 payments a day, c) spam detection for a company mailbox, d) sales forecasting for 50 stores of very different size.
Answer
a) MAE in currency (easy to explain) plus the coverage of a prediction interval, since the agents quote a range (regression metrics). b) Recall (or caught amount) at a fixed alert budget of 200 a day: the team's capacity defines the operating point, not a probability threshold. c) Precision at a high threshold, or the false-positive rate on legitimate mail, with recall second: a lost business email costs more than a spam in the inbox. d) A scale-free error such as MASE or a weighted MAPE, so large stores do not dominate and the score is compared with a seasonal-naive forecast (time-series backtesting).
2. Pick the split
Which split imitates real use? a) predicting next month's churn from monthly snapshots of customers, b) a person re-identification model that must work for people it has never seen, c) a defect classifier trained on images from three production lines, to be used on a fourth line, d) student pass/fail predictions for next year's cohort.
Answer
a) A time split: train on earlier months, test on the latest, with a gap if labels look ahead. b) A split by identity: no person in the test set appears in training (person re-ID). c) Leave one line out (group split by line): the honest test is a line the model has not seen (stratified and group CV, project 9). d) A time split by cohort (train on earlier years, test on the latest), because next year's students are new people in a possibly changed course (student performance).
3. Leakage in feature selection
A team has 120 patients and 2,000 noise features with random labels. They pick the 20 features most correlated with the label on all rows, then cross-validate a model on those 20. Predict the cross-validated accuracy before running the code, then compare with the honest version, where selection happens inside each fold.
import numpy as np
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
rng = np.random.default_rng(0)
X = rng.normal(size=(120, 2000))
y = rng.integers(0, 2, 120) # labels have nothing to do with X
leaky_X = SelectKBest(f_classif, k=20).fit_transform(X, y)
leaky = cross_val_score(LogisticRegression(max_iter=1000), leaky_X, y, cv=5).mean()
honest = cross_val_score(make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression(max_iter=1000)),
X, y, cv=5).mean()
print(f"selection before CV: {leaky:.2f}")
print(f"selection inside CV: {honest:.2f} (chance is 0.50)")selection before CV: 0.78
selection inside CV: 0.43 (chance is 0.50)
Answer
Selecting on all rows lets the labels of the validation folds choose the features, so features that happen to correlate with those labels by chance look predictive: 0.78 accuracy on pure noise. Inside a pipeline, each fold selects using its training rows only, and the score drops to chance level (0.43 here; with 120 rows, the noise around 0.50 is large). This is the selection case of the leakage lab; every learned step belongs inside the pipeline (pipelines).
4. Is the forecast any good?
A model forecasts the last 4 weeks of daily sales with MAE 12.0. Is that good? Compute the MASE against a seasonal-naive forecast (same weekday last week) on a generated series.
import numpy as np
rng = np.random.default_rng(1)
days = np.arange(26 * 7)
weekly = np.array([0.8, 0.9, 1.0, 1.0, 1.1, 1.5, 1.3])
sales = 100 * weekly[days % 7] + 0.2 * days + rng.normal(0, 8, len(days))
train, test = sales[:-28], sales[-28:]
naive_in_sample = np.mean(np.abs(train[7:] - train[:-7])) # seasonal-naive error on the training part
seasonal_naive = sales[-35:-7] # each test day = same weekday a week earlier
naive_mae = np.mean(np.abs(test - seasonal_naive))
print(f"seasonal-naive MAE on the test weeks: {naive_mae:.1f}")
print(f"scale (in-sample seasonal-naive MAE): {naive_in_sample:.1f}")
print(f"MASE of a model with MAE 12.0: {12.0 / naive_in_sample:.2f}")seasonal-naive MAE on the test weeks: 8.7
scale (in-sample seasonal-naive MAE): 8.0
MASE of a model with MAE 12.0: 1.50
Answer
MASE divides the model's MAE by the in-sample error of the seasonal-naive forecast. 1.50 means the model's error is 50 % larger than that of "same weekday last week" on the training data, and on the test weeks themselves the seasonal-naive forecast is better too (MAE 8.7 against 12.0): the model is worse than doing almost nothing. Without the baseline, "MAE 12" sounded fine. Always report the naive baseline next to a forecast (sales forecasting).
5. Alerts under a budget
A fraud model scores 1,000 payments a day for 5 days; about 1 % are fraud. The team can review 15 a day. Compare a fixed probability threshold of 0.5 with "review the top 15 each day".
import numpy as np
rng = np.random.default_rng(2)
recall_thr, recall_top, alerts_thr = [], [], []
for day in range(5):
y = rng.random(1000) < 0.01
score = np.clip(rng.normal(0.15, 0.1, 1000) + y * rng.normal(0.25, 0.12, 1000), 0, 1)
flagged = score > 0.5
top = np.argsort(-score)[:15]
alerts_thr.append(int(flagged.sum()))
recall_thr.append(flagged[y].mean() if y.any() else np.nan)
recall_top.append(y[top].sum() / max(y.sum(), 1))
print("alerts per day at threshold 0.5:", alerts_thr)
print(f"recall, threshold 0.5: {np.nanmean(recall_thr):.2f}")
print(f"recall, top 15 a day: {np.mean(recall_top):.2f}")alerts per day at threshold 0.5: [3, 3, 2, 3, 1]
recall, threshold 0.5: 0.28
recall, top 15 a day: 0.60
Answer
The threshold of 0.5 was never chosen for anything; it produces 1 to 3 alerts a day and leaves most of the team's capacity unused, catching 0.28 of fraud. Ranking and taking the top 15 uses the whole budget and catches 0.60. When capacity is fixed, choose the operating point from the capacity (fraud detection, log loss and thresholds); the pump capstone in the mini project does the same with 3 inspections a day.
6. How many segments?
In a customer segmentation, silhouette scores for k = 2…6 are 0.41, 0.38, 0.44, 0.36, 0.33, and the marketing team can run at most four campaigns. Running k-means with ten different seeds at k = 4 gives almost identical segments; at k = 5 two segments swap members from seed to seed. Which k do you choose?
Answer
k = 4: it has the best silhouette, it is stable across seeds, and it matches the number of campaigns the team can act on. k = 2 scores well too but is too coarse to be useful; k = 5 is unstable, so its segments are partly artefacts of the initialisation. Report the stability check and profile each segment in business terms (customer segmentation, cluster evaluation).
7. Augmentations that change the label
For the defect classifier of project 8 (ok, scratch, spot, crack on brushed steel whose streaks always run horizontally), which augmentations are safe: a) horizontal flip, b) rotation by 90 degrees, c) strong blur, d) changing brightness by 10 %, e) cropping 40 % of the image at random?
Answer
a) and d) are safe: a flipped or slightly brighter patch is still a plausible image from the same camera with the same label. b) Rotating by 90 degrees keeps every defect a defect, but it turns the horizontal streaks vertical, which the camera never sees; in project 8 flips plus transposes scored 0.955 on validation against 0.988 for flips alone. An augmentation must preserve the label and stay inside the data the model will meet. c) Strong blur can erase a thin scratch, turning a "scratch" image into an "ok" one with the wrong label. e) A random crop of 40 % can cut the defect out of the frame, again creating a mislabelled "ok" (image augmentation).
8. Freeze or fine-tune?
You have 20 labelled images per class from a new production line and a ResNet-18 pretrained on ImageNet. What do you try first, and when would you fine-tune more layers?
Answer
First, frozen features with a simple classifier on top (feature extraction): with 20 images per class, training millions of parameters overfits easily, while a linear head on pretrained features needs few labels. Fine-tune the last block (and later more) when you have more labels, when the images are far from ImageNet's (so the generic features fit poorly), and when validation shows the frozen model has plateaued; use a small learning rate and early stopping. Also ask which pretrained model is closest to your images: in project 9 the CNN trained on the first production line, fine-tuned, beat frozen ImageNet features at every label budget (feature extraction, partial fine-tuning).
9. Do two annotators agree?
Two annotators drew a box around the same object: A = (10, 10, 50, 40) and B = (14, 12, 54, 44) as (x1, y1, x2, y2). Compute the IoU. Would this pair count as a match at IoU 0.5? At 0.75?
def iou(a, b):
ix = max(0, min(a[2], b[2]) - max(a[0], b[0]))
iy = max(0, min(a[3], b[3]) - max(a[1], b[1]))
inter = ix * iy
area = lambda r: (r[2] - r[0]) * (r[3] - r[1])
return inter / (area(a) + area(b) - inter)
v = iou((10, 10, 50, 40), (14, 12, 54, 44))
print(f"IoU = {v:.3f}; match at 0.5: {v >= 0.5}; at 0.75: {v >= 0.75}")IoU = 0.685; match at 0.5: True; at 0.75: False
Answer
The intersection is 36 × 28 = 1,008 and the union 1,200 + 1,280 − 1,008 = 1,472, so IoU = 0.685. The two human boxes agree at 0.5 but not at 0.75. If people disagree this much, a detector cannot be expected to score well at strict IoU thresholds: measure annotator agreement before reading much into AP at 0.75 or AP50-95 (YOLO object detection, detection metrics).
10. Counting people, responsibly
A shop wants to count visitors with a camera and a person tracker. a) Which error matters more for the count: an identity switch in the middle of the shop or a missed detection at the door line? b) Name three privacy measures for the deployment.
Answer
a) For a line-crossing count, what matters is each person crossing the line once with one identity; an identity switch far from the line does not change the count, while a missed detection or a fragmented track at the line does (double or missed counts). Evaluate the product metric (count error), not only MOTA or IDF1 (person tracking, multi-object tracking project). b) For example: process on the device and keep only counts, not images; no face recognition or re-identification; short retention; signage and a data protection impact assessment; access control and logging (privacy, consent and licensing).
11. Early stopping on the test set
A notebook fine-tunes a language model and keeps the checkpoint with the best test accuracy over 10 epochs, then reports that accuracy. What is wrong, and how big can the bias be?
Answer
The test set was used to choose the epoch, so the reported number is the maximum of 10 noisy measurements, which is optimistic. With a few hundred test examples, epoch-to-epoch noise of a point or two is common, so the reported score can easily be 1–2 points too high. Choose the checkpoint on a validation set and evaluate the chosen one once on the test set (fine-tuned language model, early stopping and checkpointing).
12. When should RAG say "I don't know"?
A retrieval assistant answers questions from a company handbook. List three signals that should make it abstain, and one rule that must hold even when retrieval works perfectly.
Answer
Signals: the best retrieval score is below a threshold tuned on questions with known answers (including unanswerable ones); the retrieved passages do not contain the terms or entities of the question; the extracted or generated answer is not supported by the cited passage (a grounding check). The rule: access control — documents a user may not read must be filtered out before retrieval, not after generation, or the answer can leak them (RAG application, evaluating retrieval and RAG).
13. A canary decision
A new model version serves 5 % of traffic for a week: 2,000 requests, error rate 4.1 %, against 3.6 % for the current version on 38,000 requests. Should it be promoted?
Answer
Not on this evidence. The difference of 0.5 points on 2,000 requests is within noise (a rough 95 % interval for 4.1 % on 2,000 requests is about ±0.9 points), so the canary has not shown it is better, and the point estimate is worse. Either keep the canary running until the planned sample size is reached, or keep the current version. Decide the promotion rule (metric, minimum sample, margin) before the canary starts (deployment strategies, production ML platform).
14. Review a write-up
Find at least five problems in this summary: "Our churn model reaches 96 % accuracy. We used all 50,000 customers, standardised the features, then split 80/20. After trying 30 models we kept the one with the best test accuracy. The model is ready for production."
Answer
- Accuracy alone, with no class balance: if 95 % of customers stay, 96 % is barely better than "nobody churns". 2. No baseline. 3. Standardised before splitting: preprocessing saw the test rows (leakage, small here but a bad habit). 4. A random split of customers over time: churn should be tested on a later period. 5. Thirty models compared on the test set: the "best test accuracy" is optimistic; the test set has become a validation set. 6. No error analysis, no interval, no limitations, no monitoring plan: "ready for production" is not supported (project workflow, presenting your projects).
Test yourself
In exercise 3, feature selection on all 120 rows of pure noise gave a cross-validated accuracy of 0.78. What does the honest pipeline give?
- 0.78 as well
- About chance level (0.43 here)
- 1.00
- It cannot be computed
A forecast has MASE 1.50. What does that mean?
- It is 50 % better than the seasonal-naive forecast
- Its error is 50 % larger than the in-sample error of the seasonal-naive forecast
- It explains 50 % of the variance
- It is unbiased
A review team can handle 15 alerts a day. In exercise 5, what did 'top 15 a day' catch compared with a fixed threshold of 0.5?
- 0.60 against 0.28
- 0.28 against 0.60
- The same
- 0.73 against 0.40
Two annotators' boxes have IoU 0.685. What follows for evaluating a detector?
- Nothing; annotators never matter
- Scores at strict IoU thresholds such as 0.75 are limited by the labels themselves, so measure annotator agreement first
- Use IoU 0.9 for a stricter test
- The detector must reach IoU 1.0