Exercises
Twenty-four exercises across the whole course, most of them small enough to do on paper. Try each one before opening the answer. Six answers include a program that checks the hand computation, which you can edit and run.
| # | Exercise | Practises |
|---|---|---|
| 1 | Counting steps | Batch Size, Iterations and Epochs |
| 2 | One SGD step by hand | A Training Loop in NumPy |
| 3 | Zero initialisation | Parameters and Initialisation |
| 4 | Stable learning rates | Gradient Descent and the Learning Rate |
| 5 | When does training stop? | Early Stopping and Checkpointing |
| 6 | A cosine schedule | Learning-Rate Schedules |
| 7 | Clip by global norm | Gradient Clipping |
| 8 | float16 or bfloat16? | Mixed Precision |
| 9 | Three losses, one outlier | Regression Losses |
| 10 | Softmax cross-entropy and its gradient | Cross-Entropy |
| 11 | Easy and hard examples | Focal Loss |
| 12 | A triplet | Contrastive and Triplet Losses |
| 13 | Momentum's speed limit | Momentum and Nesterov |
| 14 | Adam's first step | Adam and AdamW |
| 15 | Four regression metrics | Regression Metrics |
| 16 | A rare-event confusion matrix | Classification Metrics |
| 17 | AUC and AP from a ranking | ROC-AUC, PR-AUC and AP |
| 18 | Boxes and masks | Detection Metrics, Segmentation Metrics |
| 19 | Pick the validation strategy | Validation Strategies |
| 20 | Read the learning curves | Underfitting and Overfitting, Bias-Variance |
| 21 | Find the leak | Data Leakage |
| 22 | Why random search works | Grid and Random Search |
| 23 | Expected calibration error | Calibration |
| 24 | A new base rate | Distribution Shift |
Exercise 1: Counting steps
A data set has 1000 training examples and the batch size is 64. How many optimizer steps are there per epoch, and in 10 epochs? How many if the last, incomplete batch is dropped (drop_last=True in PyTorch)?
Answer
steps per epoch: 15 full batches of 64 (960 examples) and one batch of 40. Ten epochs are 160 steps. With drop_last=True there are steps per epoch, 150 in total, and a different 40 examples are left out in each epoch because the data is reshuffled.
Exercise 2: One SGD step by hand
Logistic regression with , sees one example with label . Compute the prediction, the binary cross-entropy loss, the gradient and the parameters after one step with learning rate .
Answer
After the step, : the prediction moved towards the label, as it should.
import numpy as np
w, b, x, y, lr = np.array([0.5, -0.2]), 0.0, np.array([1.0, 2.0]), 1, 0.1
z = w @ x + b
p = 1 / (1 + np.exp(-z))
print(f"z {z:.4f} p {p:.4f} loss {-np.log(p):.4f}")
gw, gb = (p - y) * x, p - y
w, b = w - lr * gw, b - lr * gb
print("gradient", gw.round(4), round(float(gb), 4))
print("new w", w.round(4), " new b", round(float(b), 4), " new z", round(float(w @ x + b), 4))z 0.1000 p 0.5250 loss 0.6444
gradient [-0.475 -0.95 ] -0.475
new w [ 0.5475 -0.105 ] new b 0.0475 new z 0.385
Exercise 3: Zero initialisation
A two-layer MLP has all its weights and biases initialised to zero. What happens during training? And what standard deviation does He initialisation give to the weights of a ReLU layer with 256 inputs?
Answer
All hidden units compute the same value and receive the same gradient, so they stay identical forever: the layer behaves like a single unit (the symmetry is never broken). Worse, with zero output weights the gradient reaching the first layer is exactly zero, so it does not move at all. Random initialisation breaks the symmetry. He initialisation draws weights with standard deviation , which keeps the variance of ReLU activations roughly constant from layer to layer.
Exercise 4: Stable learning rates
Gradient descent minimises from . Write the update as . For which learning rates does it converge? What happens with , and ?
Answer
, so and . It converges when , that is with curvature .
- : , smooth convergence.
- : , faster, overshooting zero and back each step with shrinking size.
- : , the iterates alternate in sign and grow: divergence.
The gradient-descent lab shows the same threshold, , in two dimensions.
Exercise 5: When does training stop?
The validation losses after epochs 1 to 9 are 0.90, 0.70, 0.62, 0.60, 0.61, 0.59, 0.60, 0.62, 0.63. With Keras' rule (an epoch improves if its loss is below the best so far minus min_delta), at which epoch does training stop, and which epoch's weights are restored, for patience 2 and min_delta 0? And for min_delta 0.02?
Answer
With min_delta = 0: the best is 0.60 at epoch 4; epoch 5 (0.61) waits 1; epoch 6 (0.59) improves, wait resets; epochs 7 and 8 do not improve (wait 1, 2), so training stops after epoch 8 and the weights of epoch 6 are restored.
With min_delta = 0.02: epochs 2 and 3 improve by more than 0.02; epoch 4 (0.60) is not below , wait 1; epoch 5 wait 2: stop after epoch 5, restore epoch 3. A larger min_delta stops earlier and ignores the small later gains.
def early_stop(losses, patience, min_delta):
best, best_epoch, wait = float("inf"), 0, 0
for epoch, loss in enumerate(losses, start=1):
if loss < best - min_delta:
best, best_epoch, wait = loss, epoch, 0
else:
wait += 1
if wait >= patience:
return epoch, best_epoch
return len(losses), best_epoch
val = [0.90, 0.70, 0.62, 0.60, 0.61, 0.59, 0.60, 0.62, 0.63]
for d in [0.0, 0.02]:
stop, best = early_stop(val, patience=2, min_delta=d)
print(f"min_delta {d}: stop after epoch {stop}, restore epoch {best}")min_delta 0.0: stop after epoch 8, restore epoch 6
min_delta 0.02: stop after epoch 5, restore epoch 3
Exercise 6: A cosine schedule
A cosine schedule without warm-up decays the learning rate from to 0 over epochs: . What is at epochs 0, 25, 50 and 100?
Answer
; ; ; . The rate falls slowly at first, fastest in the middle and slowly again near the end.
Exercise 7: Clip by global norm
A model has two parameter tensors with gradients and . Clip by global norm with max_norm = 5. What are the clipped gradients? What would clipping each value to give instead?
Answer
The global norm is , so every gradient is multiplied by : , . The direction is unchanged, only the length shrinks to 5. Clipping by value gives and : the direction changes, because only the largest component is cut.
Exercise 8: float16 or bfloat16?
Which of the two 16-bit formats can store , and which can tell 1.0 from 1.001? Check with NumPy (bfloat16 is emulated by rounding a float32 to its top 16 bits).
Answer
float16 has 5 exponent bits (largest finite value 65504) and 10 fraction bits, so overflows to infinity, but 1.001 is stored as about 1.0010 (the spacing near 1 is ). bfloat16 has float32's 8 exponent bits, so fits, but only 7 fraction bits: the spacing near 1 is , so 1.001 rounds to 1.0, and is stored as a nearby multiple of 512. That is why bfloat16 training rarely needs loss scaling (range) and why sums are still accumulated in float32 (precision).
import numpy as np
def to_bfloat16(x):
"""Round float32 values to the nearest bfloat16 (round half to even on the top 16 bits)."""
bits = np.asarray(x, dtype=np.float32).view(np.uint32)
rounded = (bits + 0x7FFF + ((bits >> 16) & 1)) & 0xFFFF0000
return rounded.astype(np.uint32).view(np.float32)
with np.errstate(over="ignore"):
for v in [1e5, 1.001]:
print(f"{v:>8}: float16 {float(np.float16(v))!r:>10} bfloat16 {float(to_bfloat16(v))!r:>10}")
print("float16 max", float(np.finfo(np.float16).max), " spacing at 1:", float(np.spacing(np.float16(1))), 2.0 ** -7)100000.0: float16 inf bfloat16 99840.0
1.001: float16 1.0009765625 bfloat16 1.0
float16 max 65504.0 spacing at 1: 0.0009765625 0.0078125
Exercise 9: Three losses, one outlier
The residuals of a model on three examples are , and . Compute the mean of MSE, MAE and Huber loss with (Huber: when , else ). Which loss is dominated by the outlier?
Answer
- MSE: ; the outlier contributes 16 of 17.25, 93 %.
- MAE: .
- Huber: , mean .
MSE is dominated by the outlier, and its gradient () on that example is 8, while Huber's gradient there is capped at . Huber behaves like MSE for small residuals and like MAE for large ones.
Exercise 10: Softmax cross-entropy and its gradient
A three-class model outputs logits and the true class is the first. Compute the softmax probabilities, the cross-entropy loss and the gradient with respect to the logits.
Answer
, so . The loss is . The gradient is : push the true logit up, the others down, in proportion to their probability.
import numpy as np
z, y = np.array([2.0, 1.0, 0.0]), np.array([1.0, 0.0, 0.0])
def ce(z):
log_p = z - z.max() - np.log(np.sum(np.exp(z - z.max()))) # log-softmax, computed stably
return -log_p @ y
p = np.exp(z - z.max()) / np.sum(np.exp(z - z.max()))
print("p", p.round(3), " loss", round(float(ce(z)), 3), " gradient", (p - y).round(3))
eps = 1e-6 # check the gradient numerically
num = [(ce(z + eps * np.eye(3)[k]) - ce(z - eps * np.eye(3)[k])) / (2 * eps) for k in range(3)]
print("numerical", np.round(num, 3))p [0.665 0.245 0.09 ] loss 0.408 gradient [-0.335 0.245 0.09 ]
numerical [-0.335 0.245 0.09 ]
Exercise 11: Easy and hard examples
Compare binary cross-entropy and focal loss with for an easy example () and a hard one (), where is the probability given to the true class. By what factor does each example's loss shrink?
Answer
- Easy: CE ; focal , 100 times smaller.
- Hard: CE ; focal , only 1.56 times smaller.
Relative to each other, the hard example now weighs about 980 times as much as the easy one, against about 15 times under cross-entropy. That is focal loss's purpose: the many easy examples (typically background or the majority class) stop dominating the gradient.
Exercise 12: A triplet
An embedding model gives distances between an anchor and a positive, and between the anchor and a negative. What is the triplet loss with margin ? With ? What kind of negative is this?
Answer
With : . With : , no gradient. The negative is farther than the positive but within the margin for : a semi-hard negative, the kind that triplet mining looks for, because it still gives a gradient without being so hard that it is probably mislabelled.
Exercise 13: Momentum's speed limit
With momentum , and a constant gradient , what does approach? How much faster than plain gradient descent does the parameter then move with ?
Answer
. With that is : on a long, gentle slope the step is ten times plain gradient descent's. On a direction where the gradient flips sign every step, the contributions cancel instead, which is why momentum damps the zig-zag in narrow valleys.
Exercise 14: Adam's first step
At step 1, Adam with , , sees a gradient on one parameter (and is negligible). How large is the update with bias correction, and how large would it be without it?
Answer
, . With bias correction and , so the step is , whatever the size of . Without correction the step is , more than three times too large, because the two averages start at zero and is pulled down far more than .
Exercise 15: Four regression metrics
Targets , predictions . Compute MAE, MSE, RMSE and .
Answer
Errors . MAE ; MSE ; RMSE . The mean target is 6, so the total sum of squares is and . RMSE is above MAE because the one error of 3 counts more when squared.
Exercise 16: A rare-event confusion matrix
A fraud model on 1000 transactions has TP = 40, FP = 10, FN = 20, TN = 930. Compute accuracy, precision, recall and F1. What accuracy does the model "never fraud" reach?
Answer
Accuracy ; precision ; recall ; . "Never fraud" is right on the 940 legitimate transactions: accuracy 0.94, recall 0. Accuracy separates the two models by only 3 points; recall and precision show the real difference.
Exercise 17: AUC and AP from a ranking
Three positives get scores 0.9, 0.6, 0.4 and four negatives 0.7, 0.3, 0.2, 0.1. Compute ROC-AUC as the share of (positive, negative) pairs ranked correctly, and average precision as the mean of the precision at the rank of each positive.
Answer
Pairs: 0.9 beats all 4 negatives, 0.6 beats 3 (not 0.7), 0.4 beats 3: . Sorted, the list is P, N, P, P, N, N, N; the positives sit at ranks 1, 3, 4 with precision , , , so .
from sklearn.metrics import roc_auc_score, average_precision_score
scores = [0.9, 0.6, 0.4, 0.7, 0.3, 0.2, 0.1]
labels = [1, 1, 1, 0, 0, 0, 0]
print("ROC-AUC", round(roc_auc_score(labels, scores), 3), " AP", round(average_precision_score(labels, scores), 3))ROC-AUC 0.833 AP 0.806
Exercise 18: Boxes and masks
A predicted box spans to and the ground-truth box to (corners, unit grid). Compute their IoU. Treat the boxes as filled masks and compute the Dice coefficient. Is this a correct detection at the usual IoU threshold of 0.5?
Answer
Intersection: the square from to , area 4. Union , so IoU . Dice , which matches . With IoU 0.143 < 0.5 the prediction is a false positive and the object counts as missed (a false negative).
Exercise 19: Pick the validation strategy
Choose holdout/k-fold, stratified k-fold, group k-fold, time-series backtesting or external validation for each case, and say what goes wrong with a plain random split.
- 3000 X-ray images from 800 patients, several per patient.
- Forecasting next week's sales from three years of daily data.
- Fraud detection with 0.5 % fraud cases.
- A model built at one hospital that will be sold to others.
Answer
- Group k-fold by patient: random splits put the same patient in training and validation, and the model gets credit for recognising patients.
- Time-series backtesting (expanding or sliding window, train on the past only): a random split trains on the future.
- Stratified k-fold: random folds of a rare class can contain very few positives, which makes recall and AP swing wildly.
- External validation on data from other hospitals (other scanners, other populations), after internal cross-validation: internal scores overestimate performance at a new site.
Exercise 20: Read the learning curves
Model A: training accuracy 0.99, validation 0.70. Model B: training 0.72, validation 0.70. Which one has high bias and which high variance? Give two remedies for each.
Answer
A has a large generalisation gap (0.29): high variance, overfitting. Remedies: more data, stronger regularisation (weight decay, dropout, smaller trees), early stopping, a simpler model, augmentation. B fits the training data badly and the gap is small: high bias, underfitting. Remedies: a more flexible model, better features, less regularisation, training longer. More data alone helps A, but hardly B.
Exercise 21: Find the leak
Each pipeline reports a validation score that is too good. Name the leak.
- Missing values are imputed with the column mean of the whole data set, then the data is split.
- A feature "number of follow-up visits" is used to predict whether a patient was readmitted.
- 40 features are selected by correlation with the target on all rows, then a model is cross-validated on them.
- A churn model includes the feature "account closed date is not empty".
Answer
- Preprocessing leakage: the validation rows' values shaped the imputer. Fit it inside the pipeline on the training folds.
- Target leakage through time: follow-up visits happen after the readmission decision point, and readmitted patients have more of them.
- Selection leakage: the feature choice saw the validation folds' targets. With many noise features, this alone can produce a high score on pure noise (the
leakagelab shows 0.94 against 0.54). - Target leakage: the feature is a direct consequence of the label.
Exercise 22: Why random search works
Out of the whole search space, the best 5 % of configurations count as "good". How many random trials do you need so that at least one is good with 95 % probability? Why does a grid explore only 3 values of the one hyperparameter that matters, while 9 random trials explore 9?
Answer
gives , so 59 trials (the often-quoted 60). A grid repeats each value of every hyperparameter across the values of the others: with one important and one unimportant hyperparameter, 6 of the 9 grid points re-test values of the important one already tried. Random trials all have different values of every hyperparameter, so the important one gets 9 distinct values.
Exercise 23: Expected calibration error
A model's validation predictions fall into three bins:
| bin | examples | mean predicted probability | observed positive rate |
|---|---|---|---|
| low | 600 | 0.10 | 0.08 |
| middle | 300 | 0.50 | 0.40 |
| high | 100 | 0.90 | 0.70 |
Compute the ECE. Is the model over- or underconfident? Which simple fix would you try first?
Answer
. Predicted probabilities are above the observed rates in every bin, and more so at the high end: overconfident. Try Platt scaling (a logistic regression on the model's scores, fitted on a separate calibration split); with plenty of calibration data, isotonic regression.
Exercise 24: A new base rate
A classifier was trained where 10 % of cases are positive. It is deployed where 30 % are positive, and nothing else changed (pure label shift). For a case where it outputs , what is the corrected probability?
Answer
Under label shift, the odds are multiplied by the ratio of the prior odds:
import numpy as np
def adjust_prior(p, train_rate, new_rate):
odds = p / (1 - p) * (new_rate / (1 - new_rate)) / (train_rate / (1 - train_rate))
return odds / (1 + odds)
for p in [0.1, 0.5, 0.9]:
print(f"p {p} -> {adjust_prior(p, 0.10, 0.30):.3f}")p 0.1 -> 0.300
p 0.5 -> 0.794
p 0.9 -> 0.972
Test yourself
With 1000 examples and batch size 64 (last batch kept), how many optimizer steps are in 10 epochs?
- 10
- 150
- 160
- 640
Gradient descent on diverges for which learning rate?
- 0.1
- 0.3
- 0.45
- 0.6
Three positives score 0.9, 0.6, 0.4 and four negatives 0.7, 0.3, 0.2, 0.1. What is the ROC-AUC?
- 0.75
- 0.806
- 0.833
- 1.0
A model trained at 10 % prevalence outputs 0.5 for a case; the deployment prevalence is 30 %, with nothing else changed. The corrected probability is about…
- 0.5
- 0.6
- 0.79
- 0.9