Objective
The fundamentals lesson covered layers, backpropagation, initialisation, weight decay and dropout. This lesson is about the choices that decide whether a network actually trains and generalises: which optimiser, which learning-rate schedule, which normalisation, how to stop, how to remove seed noise and how to feed in categorical variables. You should be able to write the Adam update from memory, explain why batch normalisation behaves differently at test time, and design an out-of-sample evaluation that an interviewer cannot poke holes in.
Optimisers: from SGD to Adam
Plain minibatch SGD steps , where is the gradient on a minibatch. It has two problems: the step is proportional to the raw gradient scale, so one learning rate cannot suit every parameter, and noisy minibatch gradients make it zig-zag across narrow valleys.
Momentum keeps an exponentially weighted velocity, , . Components of the gradient that keep their sign accumulate (effective step up to , i.e. for ); components that flip sign cancel.
Adam keeps running estimates of the first and second moments of each parameter's gradient and divides one by the square root of the other:
Defaults are , , . Three facts interviewers probe:
- Scale invariance. Multiply every gradient by and both and scale by , so the step is unchanged (up to ). The step size is set by , not by the gradient's units.
- Bias correction. , so early moment estimates are biased towards zero. The divisions by remove that bias; without them the first step would be the wrong size.
- Weight decay. Adding to the loss puts the decay gradient through the adaptive scaling, so heavily updated weights are barely decayed. AdamW instead applies separately, which is what "weight decay" should mean.
Worked example
the first two Adam steps
A single weight receives gradients and . With and default , compute the two Adam steps. What changes if the gradients are times larger? What would the first step be without bias correction?
Show solutionHide solution
Step 1. and . Bias correction divides by and , giving and . The step is : the first Adam step always has size (in the direction of ).
Step 2. and . Corrected: and , so . Step , still pushing the weight in the same direction: momentum outweighs the one gradient that changed sign.
Scaling by 1000. Every scales by 1000 and every by , so the ratio and the steps are identical: then .
No bias correction. The first step would be , more than three times too large, because is shrunk towards zero more severely than .
Learning-rate schedules
The learning rate is the most important hyperparameter. A schedule changes it during training:
- Warm-up. Increase linearly from near zero over the first few hundred or thousand steps. Early on the weights are random and Adam's is estimated from few gradients, so full-size steps can throw the network into a bad region. Warm-up is standard for transformers.
- Step decay. Divide by 10 at fixed epochs.
- Cosine decay. Over steps,
With , and , the rate is at , at and at .
Why decay at all: with a constant rate, minibatch noise keeps the weights bouncing around the minimum with a spread that scales with divided by the batch size. Shrinking late in training lets the weights settle. The same reasoning gives the rule of thumb that if you double the batch size you can roughly double the learning rate, because the gradient noise halves.
Batch normalisation and layer normalisation
Batch normalisation standardises each hidden unit over the minibatch, then rescales with learned and :
where are the mean and variance of that unit over the batch. It keeps each layer's inputs on a stable scale, which permits larger learning rates. Two consequences matter in practice:
- Train and test differ. In training the statistics come from the current batch, so one example's output depends on which other examples share its batch. At test time the layer uses running averages accumulated during training. Forgetting to switch to evaluation mode is a classic bug, and small batches make the batch statistics noisy.
- Batch composition is a modelling choice. If each batch is one date's cross-section of stocks, batch norm is doing cross-sectional standardisation in training, but at test time it uses running averages over all dates. The two can disagree badly after a volatility regime change.
Layer normalisation standardises across the units of one example instead, so it does not depend on batch-mates and behaves identically in training and testing. That is why recurrent networks and transformers use it.
Early stopping, done properly
Train while monitoring a validation loss, keep the weights from its minimum, and stop after the loss has failed to improve for a set number of epochs (the patience). With noisy financial targets the validation curve is itself noisy, so use a patience of several epochs and a minimum improvement threshold, and remember that the validation block has now been used for model selection and is no longer an unbiased estimate.
The validation block must come after the training block in time. A random holdout lets the network learn from days that sit between validation days, so the stopping rule rewards memorising the period.
Seed ensembles
A network's fit depends on its random initialisation and minibatch order. Train copies with different seeds and average them. If each copy's prediction has seed-induced variance and pairwise correlation , the average keeps of it, the same formula as for bagged trees. The gain is largest when seeds disagree a lot, which is exactly the low signal-to-noise regime: different seeds fit different noise. Seed ensembling is cheap, embarrassingly parallel and almost never hurts, so a single-seed network result should be treated as one draw, not as "the" result.
Embedding categorical variables
A categorical input with levels (sector, exchange, ticker) can be one-hot encoded, but the first layer then has weights for hidden units. An embedding is a learned lookup table with small : level is represented by row , which is fed into the network like any other features. Mathematically it is a one-hot vector multiplied by a matrix, so it is a low-rank factorisation of the one-hot first layer, and levels that behave alike end up with nearby vectors.
For 5,000 tickers feeding 64 hidden units, one-hot costs first-layer weights; an 8-dimensional embedding costs .
Two warnings. A ticker embedding lets the network memorise each stock's average return over the training period, which is a strong, non-stationary and usually spurious feature. And rare levels get few gradient updates, so group them into an "other" bucket. Without a deep-learning framework, the nearest tool is target encoding (replace a level by the mean target for that level), which must be cross-fitted so a row's own target is never used to encode it; scikit-learn's TargetEncoder does this in fit_transform.
A runnable experiment with honest evaluation
The script plants a weak non-linear signal in noise (best achievable test about 3%) in rows that are treated as time-ordered. It splits them chronologically into train, validation and test blocks, fits the scaler on training rows only, stops each network on the validation block, picks the L2 penalty on the validation block, and touches the test block once.
import copy
import numpy as np
from sklearn.linear_model import Ridge
from sklearn.neural_network import MLPRegressor
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import r2_score
rng = np.random.default_rng(7)
n, p = 8000, 10
X = rng.standard_t(df=5, size=(n, p)) # fat-tailed features, rows in time order
f = 0.25 * np.tanh(X[:, 0]) + 0.15 * X[:, 1] * (X[:, 2] > 0) + 0.05 * X[:, 3]
y = f + rng.normal(size=n) # signal is a few % of variance
tr, va, te = slice(0, 5000), slice(5000, 6500), slice(6500, n)
sc = StandardScaler().fit(X[tr]) # fit the scaler on training rows only
Xs = sc.transform(X)
def fit_mlp(seed, alpha, max_epochs=60, patience=8):
"""Adam + manual early stopping on a *time-ordered* validation block."""
m = MLPRegressor(hidden_layer_sizes=(32, 16), alpha=alpha, batch_size=128,
learning_rate_init=1e-3, random_state=seed)
best, best_loss, wait = None, np.inf, 0
for _ in range(max_epochs):
m.partial_fit(Xs[tr], y[tr])
loss = np.mean((m.predict(Xs[va]) - y[va]) ** 2)
if loss < best_loss - 1e-6:
best, best_loss, wait = copy.deepcopy(m), loss, 0
else:
wait += 1
if wait >= patience:
break
return best
# choose alpha (L2 strength) on the validation block, never on the test block
val_r2 = {}
for alpha in [1e-3, 1e-1, 1.0, 10.0]:
preds = [fit_mlp(s, alpha).predict(Xs[va]) for s in range(3)]
val_r2[alpha] = np.mean([r2_score(y[va], q) for q in preds])
print(f"alpha {alpha:<6g} mean single-seed val R^2 {val_r2[alpha]:+.4f}")
alpha = max(val_r2, key=val_r2.get)
ridge = Ridge(alpha=10.0).fit(Xs[tr], y[tr])
nets = [fit_mlp(s, alpha) for s in range(5)]
test_preds = np.array([m.predict(Xs[te]) for m in nets])
print(f"ridge test R^2 {r2_score(y[te], ridge.predict(Xs[te])):+.4f}")
for s, q in enumerate(test_preds):
print(f"MLP seed {s} test R^2 {r2_score(y[te], q):+.4f}")
print(f"5-seed average test R^2 {r2_score(y[te], test_preds.mean(0)):+.4f}")
print(f"best possible test R^2 {r2_score(y[te], f[te]):+.4f}")
print(f"mean corr between seeds {np.corrcoef(test_preds)[np.triu_indices(5, 1)].mean():.2f}")
Output:
alpha 0.001 mean single-seed val R^2 +0.0284
alpha 0.1 mean single-seed val R^2 +0.0296
alpha 1 mean single-seed val R^2 +0.0354
alpha 10 mean single-seed val R^2 +0.0183
ridge test R^2 +0.0217
MLP seed 0 test R^2 +0.0217
MLP seed 1 test R^2 +0.0214
MLP seed 2 test R^2 +0.0218
MLP seed 3 test R^2 +0.0235
MLP seed 4 test R^2 +0.0176
5-seed average test R^2 +0.0239
best possible test R^2 +0.0301
mean corr between seeds 0.89
How to read it:
- Validation picks a fairly strong penalty (); both weaker and much stronger penalties do worse.
- Single seeds range from 0.0176 to 0.0235, a spread as large as the gap between the network and ridge. Reporting the best seed would be cherry-picking.
- The 5-seed average beats every individual seed and beats ridge, by of . Seed correlation is , so averaging removes only about of the seed variance; the gain is real but small.
- The linear benchmark already captures most of what is available. On real data, a gap this small would need a significance test across many test periods before you believed it.
Knowledge check
You rescale your regression target from returns in decimals to returns in basis points, which multiplies every gradient by 10,000. What happens to the size of Adam's updates?
Knowledge check
A batch-normalised unit sees pre-activation for one example. In training batch A the four values are ; in batch B they are . Ignoring , and , what does the layer output for that example in each batch?
Knowledge check
You train an MLP on daily data from 2010 to 2022 with MLPRegressor(early_stopping=True) and evaluate on 2023. What is the main problem with the stopping rule?
Key takeaways
- Adam divides a bias-corrected momentum by a bias-corrected RMS of the gradient: steps are about in size and invariant to gradient scale. Use AdamW for weight decay.
- Warm up, then decay the learning rate (cosine or steps); late small steps let the weights settle.
- Batch norm uses batch statistics in training and running averages at test time; layer norm is per example and has no such mismatch.
- Early stopping needs a time-ordered validation block and enough patience for a noisy validation curve.
- Average several seeds and report the average; a single seed is one draw.
- Embeddings are low-rank one-hot layers; high-cardinality ones such as tickers can memorise non-stationary averages.
- Always benchmark against ridge on the same features with the same split.
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).