TExcelTAD

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

⌈1000/64⌉=16\lceil 1000 / 64 \rceil = 16 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 ⌊1000/64⌋=15\lfloor 1000 / 64 \rfloor = 15 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 w=(0.5,−0.2)\mathbf{w} = (0.5, -0.2), b=0b = 0 sees one example x=(1,2)\mathbf{x} = (1, 2) with label y=1y = 1. Compute the prediction, the binary cross-entropy loss, the gradient and the parameters after one step with learning rate η=0.1\eta = 0.1.

Answer
z=0.5⋅1−0.2⋅2+0=0.1,p=σ(0.1)≈0.5250L=−log⁡p≈0.6444∇wL=(p−y) x≈−0.4750⋅(1,2)=(−0.4750,−0.9500),∂L∂b=p−y≈−0.4750w←w−0.1∇wL≈(0.5475,−0.1050),b←0.0475\begin{aligned} z &= 0.5 \cdot 1 - 0.2 \cdot 2 + 0 = 0.1, \qquad p = \sigma(0.1) \approx 0.5250 \\ L &= -\log p \approx 0.6444 \\ \nabla_{\mathbf{w}} L &= (p - y)\,\mathbf{x} \approx -0.4750 \cdot (1, 2) = (-0.4750, -0.9500), \qquad \frac{\partial L}{\partial b} = p - y \approx -0.4750 \\ \mathbf{w} &\leftarrow \mathbf{w} - 0.1 \nabla_{\mathbf{w}} L \approx (0.5475, -0.1050), \qquad b \leftarrow 0.0475 \end{aligned}

After the step, z=0.5475−0.21+0.0475=0.385z = 0.5475 - 0.21 + 0.0475 = 0.385: the prediction moved towards the label, as it should.

python · try it yourself
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 2/nin=2/256≈0.088\sqrt{2 / n_{\text{in}}} = \sqrt{2/256} \approx 0.088, which keeps the variance of ReLU activations roughly constant from layer to layer.

Exercise 4: Stable learning rates

Gradient descent minimises f(w)=2w2f(w) = 2w^2 from w0=1w_0 = 1. Write the update as wt+1=c wtw_{t+1} = c\,w_t. For which learning rates does it converge? What happens with η=0.1\eta = 0.1, 0.30.3 and 0.60.6?

Answer

f′(w)=4wf'(w) = 4w, so wt+1=wt−4ηwt=(1−4η)wtw_{t+1} = w_t - 4\eta w_t = (1 - 4\eta) w_t and c=1−4ηc = 1 - 4\eta. It converges when ∣c∣<1\lvert c \rvert < 1, that is 0<η<0.5=2/λ0 < \eta < 0.5 = 2/\lambda with curvature λ=f′′(w)=4\lambda = f''(w) = 4.

  • η=0.1\eta = 0.1: c=0.6c = 0.6, smooth convergence.
  • η=0.3\eta = 0.3: c=−0.2c = -0.2, faster, overshooting zero and back each step with shrinking size.
  • η=0.6\eta = 0.6: c=−1.4c = -1.4, the iterates alternate in sign and grow: divergence.

The gradient-descent lab shows the same threshold, 2/λmax⁡2/\lambda_{\max}, 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 0.62−0.02=0.600.62 - 0.02 = 0.60, 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.

python · try it yourself
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 η0=0.1\eta_0 = 0.1 to 0 over T=100T = 100 epochs: ηt=η02(1+cos⁡πtT)\eta_t = \frac{\eta_0}{2}\left(1 + \cos \frac{\pi t}{T}\right). What is η\eta at epochs 0, 25, 50 and 100?

Answer

η0=0.1\eta_0 = 0.1; η25=0.05(1+cos⁡π4)≈0.05⋅1.7071≈0.0854\eta_{25} = 0.05 (1 + \cos \frac{\pi}{4}) \approx 0.05 \cdot 1.7071 \approx 0.0854; η50=0.05(1+0)=0.05\eta_{50} = 0.05 (1 + 0) = 0.05; η100=0.05(1−1)=0\eta_{100} = 0.05 (1 - 1) = 0. 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 g1=(3,4)\mathbf{g}_1 = (3, 4) and g2=(12)\mathbf{g}_2 = (12). Clip by global norm with max_norm = 5. What are the clipped gradients? What would clipping each value to [−5,5][-5, 5] give instead?

Answer

The global norm is 9+16+144=13>5\sqrt{9 + 16 + 144} = 13 > 5, so every gradient is multiplied by 5/13≈0.3855/13 \approx 0.385: g1≈(1.154,1.538)\mathbf{g}_1 \approx (1.154, 1.538), g2≈(4.615)\mathbf{g}_2 \approx (4.615). The direction is unchanged, only the length shrinks to 5. Clipping by value gives (3,4)(3, 4) and (5)(5): the direction changes, because only the largest component is cut.

Exercise 8: float16 or bfloat16?

Which of the two 16-bit formats can store 10510^5, 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 10510^5 overflows to infinity, but 1.001 is stored as about 1.0010 (the spacing near 1 is 2−10≈0.000982^{-10} \approx 0.00098). bfloat16 has float32's 8 exponent bits, so 10510^5 fits, but only 7 fraction bits: the spacing near 1 is 2−7≈0.00782^{-7} \approx 0.0078, so 1.001 rounds to 1.0, and 10510^5 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).

python · try it yourself
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 r=y−y^r = y - \hat{y} of a model on three examples are 0.50.5, −1-1 and 44. Compute the mean of MSE, MAE and Huber loss with δ=1\delta = 1 (Huber: 12r2\frac{1}{2}r^2 when ∣r∣≤δ\lvert r \rvert \le \delta, else δ(∣r∣−12δ)\delta(\lvert r \rvert - \frac{1}{2}\delta)). Which loss is dominated by the outlier?

Answer
  • MSE: (0.25+1+16)/3=5.75(0.25 + 1 + 16)/3 = 5.75; the outlier contributes 16 of 17.25, 93 %.
  • MAE: (0.5+1+4)/3≈1.833(0.5 + 1 + 4)/3 \approx 1.833.
  • Huber: 0.125+0.5+1⋅(4−0.5)=4.1250.125 + 0.5 + 1 \cdot (4 - 0.5) = 4.125, mean 1.3751.375.

MSE is dominated by the outlier, and its gradient (2r2r) on that example is 8, while Huber's gradient there is capped at δ=1\delta = 1. 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 (2,1,0)(2, 1, 0) and the true class is the first. Compute the softmax probabilities, the cross-entropy loss and the gradient with respect to the logits.

Answer

e2+e1+e0≈7.389+2.718+1=11.107e^2 + e^1 + e^0 \approx 7.389 + 2.718 + 1 = 11.107, so p≈(0.665,0.245,0.090)\mathbf{p} \approx (0.665, 0.245, 0.090). The loss is −log⁡0.665≈0.408-\log 0.665 \approx 0.408. The gradient is p−y≈(−0.335,0.245,0.090)\mathbf{p} - \mathbf{y} \approx (-0.335, 0.245, 0.090): push the true logit up, the others down, in proportion to their probability.

python · try it yourself
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 −log⁡pt-\log p_t and focal loss −(1−pt)γlog⁡pt-(1 - p_t)^\gamma \log p_t with γ=2\gamma = 2 for an easy example (pt=0.9p_t = 0.9) and a hard one (pt=0.2p_t = 0.2), where ptp_t is the probability given to the true class. By what factor does each example's loss shrink?

Answer
  • Easy: CE =−log⁡0.9≈0.105= -\log 0.9 \approx 0.105; focal =0.12⋅0.105≈0.00105= 0.1^2 \cdot 0.105 \approx 0.00105, 100 times smaller.
  • Hard: CE =−log⁡0.2≈1.609= -\log 0.2 \approx 1.609; focal =0.82⋅1.609≈1.030= 0.8^2 \cdot 1.609 \approx 1.030, 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 d(a,p)=0.4d(a, p) = 0.4 between an anchor and a positive, and d(a,n)=0.7d(a, n) = 0.7 between the anchor and a negative. What is the triplet loss max⁡(0,d(a,p)−d(a,n)+m)\max(0, d(a, p) - d(a, n) + m) with margin m=0.5m = 0.5? With m=0.2m = 0.2? What kind of negative is this?

Answer

With m=0.5m = 0.5: max⁡(0,0.4−0.7+0.5)=0.2\max(0, 0.4 - 0.7 + 0.5) = 0.2. With m=0.2m = 0.2: max⁡(0,−0.1)=0\max(0, -0.1) = 0, no gradient. The negative is farther than the positive but within the margin for m=0.5m = 0.5: 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 vt+1=βvt+gv_{t+1} = \beta v_t + g, wt+1=wt−ηvt+1w_{t+1} = w_t - \eta v_{t+1} and a constant gradient gg, what does vv approach? How much faster than plain gradient descent does the parameter then move with β=0.9\beta = 0.9?

Answer

vt=g(1+β+⋯+βt−1)→g1−βv_t = g(1 + \beta + \dots + \beta^{t-1}) \to \frac{g}{1 - \beta}. With β=0.9\beta = 0.9 that is 10g10g: 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 β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999, η=0.001\eta = 0.001 sees a gradient g=0.003g = 0.003 on one parameter (and ϵ\epsilon is negligible). How large is the update with bias correction, and how large would it be without it?

Answer

m1=0.1gm_1 = 0.1 g, v1=0.001g2v_1 = 0.001 g^2. With bias correction m^=m1/(1−0.9)=g\hat{m} = m_1 / (1 - 0.9) = g and v^=v1/(1−0.999)=g2\hat{v} = v_1 / (1 - 0.999) = g^2, so the step is η g/∣g∣=0.001\eta \, g / \lvert g \rvert = 0.001, whatever the size of gg. Without correction the step is η⋅0.1g/0.001g2=η⋅0.1/0.0316≈3.16η=0.00316\eta \cdot 0.1 g / \sqrt{0.001 g^2} = \eta \cdot 0.1 / 0.0316 \approx 3.16 \eta = 0.00316, more than three times too large, because the two averages start at zero and vv is pulled down far more than mm.

Exercise 15: Four regression metrics

Targets y=(3,5,7,9)y = (3, 5, 7, 9), predictions y^=(4,5,6,12)\hat{y} = (4, 5, 6, 12). Compute MAE, MSE, RMSE and R2R^2.

Answer

Errors (1,0,−1,3)(1, 0, -1, 3). MAE =5/4=1.25= 5/4 = 1.25; MSE =(1+0+1+9)/4=2.75= (1 + 0 + 1 + 9)/4 = 2.75; RMSE =2.75≈1.658= \sqrt{2.75} \approx 1.658. The mean target is 6, so the total sum of squares is 9+1+1+9=209 + 1 + 1 + 9 = 20 and R2=1−11/20=0.45R^2 = 1 - 11/20 = 0.45. 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 =970/1000=0.97= 970/1000 = 0.97; precision =40/50=0.8= 40/50 = 0.8; recall =40/60≈0.667= 40/60 \approx 0.667; F1=2⋅0.8⋅0.6670.8+0.667≈0.727F_1 = \frac{2 \cdot 0.8 \cdot 0.667}{0.8 + 0.667} \approx 0.727. "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: 10/12≈0.83310/12 \approx 0.833. Sorted, the list is P, N, P, P, N, N, N; the positives sit at ranks 1, 3, 4 with precision 1/11/1, 2/32/3, 3/43/4, so AP=(1+0.667+0.75)/3≈0.806AP = (1 + 0.667 + 0.75)/3 \approx 0.806.

python · try it yourself
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 (0,0)(0, 0) to (4,4)(4, 4) and the ground-truth box (2,2)(2, 2) to (6,6)(6, 6) (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 (2,2)(2, 2) to (4,4)(4, 4), area 4. Union =16+16−4=28= 16 + 16 - 4 = 28, so IoU =4/28≈0.143= 4/28 \approx 0.143. Dice =2⋅416+16=0.25= \frac{2 \cdot 4}{16 + 16} = 0.25, which matches 2 IoU1+IoU=0.2861.143=0.25\frac{2\,\text{IoU}}{1 + \text{IoU}} = \frac{0.286}{1.143} = 0.25. 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.

  1. 3000 X-ray images from 800 patients, several per patient.
  2. Forecasting next week's sales from three years of daily data.
  3. Fraud detection with 0.5 % fraud cases.
  4. A model built at one hospital that will be sold to others.
Answer
  1. Group k-fold by patient: random splits put the same patient in training and validation, and the model gets credit for recognising patients.
  2. Time-series backtesting (expanding or sliding window, train on the past only): a random split trains on the future.
  3. Stratified k-fold: random folds of a rare class can contain very few positives, which makes recall and AP swing wildly.
  4. 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.

  1. Missing values are imputed with the column mean of the whole data set, then the data is split.
  2. A feature "number of follow-up visits" is used to predict whether a patient was readmitted.
  3. 40 features are selected by correlation with the target on all rows, then a model is cross-validated on them.
  4. A churn model includes the feature "account closed date is not empty".
Answer
  1. Preprocessing leakage: the validation rows' values shaped the imputer. Fit it inside the pipeline on the training folds.
  2. Target leakage through time: follow-up visits happen after the readmission decision point, and readmitted patients have more of them.
  3. 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 leakage lab shows 0.94 against 0.54).
  4. 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 3×33 \times 3 grid explore only 3 values of the one hyperparameter that matters, while 9 random trials explore 9?

Answer

P(no good trial in n)=0.95n≤0.05P(\text{no good trial in } n) = 0.95^n \le 0.05 gives n≥ln⁡0.05ln⁡0.95≈58.4n \ge \frac{\ln 0.05}{\ln 0.95} \approx 58.4, 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

ECE=0.6⋅0.02+0.3⋅0.10+0.1⋅0.20=0.012+0.030+0.020=0.062ECE = 0.6 \cdot 0.02 + 0.3 \cdot 0.10 + 0.1 \cdot 0.20 = 0.012 + 0.030 + 0.020 = 0.062. 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 p=0.5p = 0.5, what is the corrected probability?

Answer

Under label shift, the odds are multiplied by the ratio of the prior odds:

p′1−p′=p1−p⋅0.3/0.70.1/0.9=1⋅0.42860.1111≈3.857,p′=3.8574.857≈0.794.\frac{p'}{1 - p'} = \frac{p}{1 - p} \cdot \frac{0.3 / 0.7}{0.1 / 0.9} = 1 \cdot \frac{0.4286}{0.1111} \approx 3.857, \qquad p' = \frac{3.857}{4.857} \approx 0.794 .
python · try it yourself
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?

  1. 10
  2. 150
  3. 160
  4. 640

Gradient descent on f(w)=2w2f(w) = 2w^2 diverges for which learning rate?

  1. 0.1
  2. 0.3
  3. 0.45
  4. 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?

  1. 0.75
  2. 0.806
  3. 0.833
  4. 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…

  1. 0.5
  2. 0.6
  3. 0.79
  4. 0.9