Skip to content
LeetQuant
E06 Advanced Machine Learning

E06 · Advanced Machine Learning · Lesson 1 of 4

Neural Networks in Practice

The training machinery behind a working network: momentum and Adam, learning-rate warm-up and decay, batch and layer normalisation, early stopping on a time-ordered validation block, seed ensembles and embeddings for categorical inputs, ending with an honest scikit-learn MLP experiment.

18 min

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 w←w−η gtw \leftarrow w - \eta\, g_t, where gtg_t 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, vt=βvt−1+gtv_t = \beta v_{t-1} + g_t, w←w−ηvtw \leftarrow w - \eta v_t. Components of the gradient that keep their sign accumulate (effective step up to η/(1−β)\eta/(1-\beta), i.e. 10η10\eta for β=0.9\beta = 0.9); 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:

mt=β1mt−1+(1−β1)gt,vt=β2vt−1+(1−β2)gt2,m_t = \beta_1 m_{t-1} + (1-\beta_1) g_t, \qquad v_t = \beta_2 v_{t-1} + (1-\beta_2) g_t^2, m^t=mt1−β1t,v^t=vt1−β2t,w←w−η m^tv^t+ϵ.\hat m_t = \frac{m_t}{1-\beta_1^t}, \qquad \hat v_t = \frac{v_t}{1-\beta_2^t}, \qquad w \leftarrow w - \eta\, \frac{\hat m_t}{\sqrt{\hat v_t} + \epsilon} .

Defaults are β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999, ϵ=10−8\epsilon = 10^{-8}. Three facts interviewers probe:

  • Scale invariance. Multiply every gradient by c>0c > 0 and both m^\hat m and v^\sqrt{\hat v} scale by cc, so the step is unchanged (up to ϵ\epsilon). The step size is set by η\eta, not by the gradient's units.
  • Bias correction. m0=v0=0m_0 = v_0 = 0, so early moment estimates are biased towards zero. The divisions by 1−βt1-\beta^t remove that bias; without them the first step would be the wrong size.
  • Weight decay. Adding λ∥w∥2\lambda\|w\|^2 to the loss puts the decay gradient through the adaptive scaling, so heavily updated weights are barely decayed. AdamW instead applies w←w−ηλww \leftarrow w - \eta\lambda w separately, which is what "weight decay" should mean.

Worked example

the first two Adam steps

A single weight receives gradients g1=0.2g_1 = 0.2 and g2=−0.1g_2 = -0.1. With η=0.001\eta = 0.001 and default β1,β2\beta_1, \beta_2, compute the two Adam steps. What changes if the gradients are 10001000 times larger? What would the first step be without bias correction?

Show solution

Step 1. m1=0.1×0.2=0.02m_1 = 0.1 \times 0.2 = 0.02 and v1=0.001×0.04=4×10−5v_1 = 0.001 \times 0.04 = 4 \times 10^{-5}. Bias correction divides by 1−0.9=0.11 - 0.9 = 0.1 and 1−0.999=0.0011 - 0.999 = 0.001, giving m^1=0.2\hat m_1 = 0.2 and v^1=0.04\hat v_1 = 0.04. The step is η×0.2/0.2=0.001\eta \times 0.2 / 0.2 = 0.001: the first Adam step always has size η\eta (in the direction of −g1-g_1).

Step 2. m2=0.9×0.02+0.1×(−0.1)=0.008m_2 = 0.9 \times 0.02 + 0.1 \times (-0.1) = 0.008 and v2=0.999×4×10−5+0.001×0.01=4.996×10−5v_2 = 0.999 \times 4 \times 10^{-5} + 0.001 \times 0.01 = 4.996 \times 10^{-5}. Corrected: m^2=0.008/0.19=0.04211\hat m_2 = 0.008 / 0.19 = 0.04211 and v^2=4.996×10−5/0.001999=0.02499\hat v_2 = 4.996 \times 10^{-5} / 0.001999 = 0.02499, so v^2=0.1581\sqrt{\hat v_2} = 0.1581. Step =0.001×0.04211/0.1581=0.000266= 0.001 \times 0.04211 / 0.1581 = 0.000266, still pushing the weight in the same direction: momentum outweighs the one gradient that changed sign.

Scaling by 1000. Every mm scales by 1000 and every vv by 10610^6, so the ratio and the steps are identical: 0.0010.001 then 0.0002660.000266.

No bias correction. The first step would be η×0.02/4×10−5=0.001×3.16=0.00316\eta \times 0.02 / \sqrt{4 \times 10^{-5}} = 0.001 \times 3.16 = 0.00316, more than three times too large, because vv is shrunk towards zero more severely than mm.

Learning-rate schedules

The learning rate is the most important hyperparameter. A schedule changes it during training:

  • Warm-up. Increase η\eta linearly from near zero over the first few hundred or thousand steps. Early on the weights are random and Adam's v^\hat v 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 η\eta by 10 at fixed epochs.
  • Cosine decay. Over TT steps,
ηt=ηmin⁡+12(ηmax⁡−ηmin⁡)(1+cos⁡πtT).\eta_t = \eta_{\min} + \tfrac12(\eta_{\max} - \eta_{\min})\Big(1 + \cos\frac{\pi t}{T}\Big) .

With ηmax⁡=10−3\eta_{\max} = 10^{-3}, ηmin⁡=10−5\eta_{\min} = 10^{-5} and T=100T = 100, the rate is 8.55×10−48.55 \times 10^{-4} at t=25t = 25, 5.05×10−45.05 \times 10^{-4} at t=50t = 50 and 1.55×10−41.55 \times 10^{-4} at t=75t = 75.

Why decay at all: with a constant rate, minibatch noise keeps the weights bouncing around the minimum with a spread that scales with η\eta divided by the batch size. Shrinking η\eta 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 γ\gamma and β\beta:

z^i=zi−μBσB2+ϵ,outi=γz^i+β,\hat z_i = \frac{z_i - \mu_B}{\sqrt{\sigma_B^2 + \epsilon}}, \qquad \text{out}_i = \gamma \hat z_i + \beta,

where μB,σB2\mu_B, \sigma_B^2 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 MM copies with different seeds and average them. If each copy's prediction has seed-induced variance σ2\sigma^2 and pairwise correlation ρ\rho, the average keeps ρσ2+(1−ρ)σ2/M\rho\sigma^2 + (1-\rho)\sigma^2/M 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 KK levels (sector, exchange, ticker) can be one-hot encoded, but the first layer then has K×HK \times H weights for HH hidden units. An embedding is a learned lookup table E∈RK×dE \in \mathbb{R}^{K \times d} with small dd: level kk is represented by row EkE_k, which is fed into the network like any other features. Mathematically it is a one-hot vector multiplied by a K×dK \times d 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 5000×64=320,0005000 \times 64 = 320{,}000 first-layer weights; an 8-dimensional embedding costs 5000×8+8×64=40,5125000 \times 8 + 8 \times 64 = 40{,}512.

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 R2R^2 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 (α=1\alpha = 1); 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 0.0020.002 of R2R^2. Seed correlation is 0.890.89, so averaging removes only about 1−(0.89+0.11/5)≈9%1 - (0.89 + 0.11/5) \approx 9\% 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 33 for one example. In training batch A the four values are (1,2,3,6)(1, 2, 3, 6); in batch B they are (3,4,5,8)(3, 4, 5, 8). Ignoring γ\gamma, β\beta and ϵ\epsilon, 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 η\eta 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).