Skip to content
LeetQuant
QR06 Machine Learning and Model Validation

QR06 · Machine Learning and Model Validation · Lesson 3 of 5

Neural Network Fundamentals

Layers and activations, backpropagation worked through a tiny network with numbers, loss functions, initialisation, regularisation by weight decay, dropout and early stopping, and why neural networks struggle when the signal-to-noise ratio is low.

18 min

Objective

You should be able to write down a feed-forward network, run backpropagation by hand on a small one, explain why initialisation and activation choice matter, and argue clearly about when a neural network is the wrong tool for a return-prediction problem.

Layers and activations

A fully connected network composes affine maps with element-wise non-linearities:

z(ℓ)=W(ℓ)h(ℓ−1)+b(ℓ),h(ℓ)=ϕ(z(ℓ)),h(0)=x.z^{(\ell)} = W^{(\ell)} h^{(\ell-1)} + b^{(\ell)}, \qquad h^{(\ell)} = \phi\big(z^{(\ell)}\big), \qquad h^{(0)} = x .

Without ϕ\phi the composition is a single linear map, however many layers you stack. With a non-linear ϕ\phi, one wide enough hidden layer can approximate any continuous function on a compact set (the universal approximation theorem). That says nothing about how much data you need, which is the real constraint in finance.

Activationϕ(z)\phi(z)ϕ′(z)\phi'(z)Notes
Sigmoid1/(1+e−z)1/(1+e^{-z})ϕ(1−ϕ)≤0.25\phi(1-\phi) \le 0.25Saturates; gradients vanish in deep stacks
tanhtanh⁡z\tanh z1−ϕ2≤11 - \phi^2 \le 1Zero-centred, still saturates
ReLUmax⁡(0,z)\max(0, z)11 if z>0z > 0, else 00Cheap, no saturation for z>0z > 0; units can "die"

The output layer matches the task: linear for regression, sigmoid for a binary probability, softmax for several classes.

Loss functions

  • Mean squared error 12(y^−y)2\tfrac12(\hat y - y)^2 for regression: the Gaussian log-likelihood. Sensitive to fat-tailed targets; Huber loss caps the gradient on large errors.
  • Binary cross-entropy −[ylog⁡p+(1−y)log⁡(1−p)]-[y \log p + (1-y)\log(1-p)] with p=σ(z)p = \sigma(z). Its gradient with respect to the logit is simply p−yp - y.
  • Softmax cross-entropy for KK classes: gradient pk−ykp_k - y_k with respect to each logit.

The clean p−yp - y gradients are why sigmoid and softmax are paired with cross-entropy: MSE on a sigmoid output multiplies the gradient by σ′(z)\sigma'(z), which is tiny when the unit saturates, even if the prediction is badly wrong.

Backpropagation

Backpropagation is the chain rule applied from the loss backwards, reusing each intermediate derivative. For one layer, given δ(ℓ)=∂L/∂z(ℓ)\delta^{(\ell)} = \partial L / \partial z^{(\ell)}:

∂L∂W(ℓ)=δ(ℓ)(h(ℓ−1)) ⁣⊤,∂L∂b(ℓ)=δ(ℓ),δ(ℓ−1)=((W(ℓ)) ⁣⊤δ(ℓ))⊙ϕ′(z(ℓ−1)).\frac{\partial L}{\partial W^{(\ell)}} = \delta^{(\ell)} \big(h^{(\ell-1)}\big)^{\!\top}, \qquad \frac{\partial L}{\partial b^{(\ell)}} = \delta^{(\ell)}, \qquad \delta^{(\ell-1)} = \Big(\big(W^{(\ell)}\big)^{\!\top} \delta^{(\ell)}\Big) \odot \phi'\big(z^{(\ell-1)}\big) .

One forward pass stores the zz and hh values; one backward pass computes every gradient, at roughly twice the cost of the forward pass. That is why training large networks is feasible at all.

Worked example

one backpropagation step by hand

Input x=(2,1)x = (2, 1), target y=2y = 2. Hidden layer with two ReLU units, weights and biases

W1=(0.5−0.5−10.5),b1=(0,0),W_1 = \begin{pmatrix} 0.5 & -0.5 \\ -1 & 0.5 \end{pmatrix}, \quad b_1 = (0, 0),

linear output y^=w2⊤h+b2\hat y = w_2^\top h + b_2 with w2=(2,1)w_2 = (2, 1), b2=0b_2 = 0, and loss L=12(y^−y)2L = \tfrac12(\hat y - y)^2. Compute all gradients and the loss after one gradient step with learning rate 0.050.05.

Show solution

Forward. z=W1x=(0.5⋅2−0.5⋅1,  −1⋅2+0.5⋅1)=(0.5,−1.5)z = W_1 x = (0.5 \cdot 2 - 0.5 \cdot 1,\; -1 \cdot 2 + 0.5 \cdot 1) = (0.5, -1.5), so h=(0.5,0)h = (0.5, 0). Then y^=2(0.5)+1(0)=1\hat y = 2(0.5) + 1(0) = 1 and L=12(1−2)2=0.5L = \tfrac12(1 - 2)^2 = 0.5.

Backward.

  • ∂L/∂y^=y^−y=−1\partial L/\partial \hat y = \hat y - y = -1.
  • Output layer: ∂L/∂w2=−1⋅h=(−0.5,0)\partial L/\partial w_2 = -1 \cdot h = (-0.5, 0) and ∂L/∂b2=−1\partial L/\partial b_2 = -1.
  • Into the hidden layer: ∂L/∂h=−1⋅w2=(−2,−1)\partial L/\partial h = -1 \cdot w_2 = (-2, -1). The ReLU passes the gradient where z>0z > 0 and blocks it elsewhere, so δ=(−2,0)\delta = (-2, 0).
  • Hidden weights: ∂L/∂W1=δx⊤=(−4−200)\partial L/\partial W_1 = \delta x^\top = \begin{pmatrix} -4 & -2 \\ 0 & 0 \end{pmatrix} and ∂L/∂b1=(−2,0)\partial L/\partial b_1 = (-2, 0).

The second hidden unit gets zero gradient: it is inactive for this input. If it is inactive for every input it never recovers, which is the "dead ReLU" problem.

Update with learning rate 0.050.05: W1W_1's first row becomes (0.7,−0.4)(0.7, -0.4), b1=(0.1,0)b_1 = (0.1, 0), w2=(2.025,1)w_2 = (2.025, 1), b2=0.05b_2 = 0.05. New forward pass: z1=0.7⋅2−0.4⋅1+0.1=1.1z_1 = 0.7 \cdot 2 - 0.4 \cdot 1 + 0.1 = 1.1, y^=2.025×1.1+0.05=2.2775\hat y = 2.025 \times 1.1 + 0.05 = 2.2775, and L≈0.0385L \approx 0.0385, down from 0.50.5.

With learning rate 0.10.1 instead, y^=3.585\hat y = 3.585 and L≈1.256L \approx 1.256: the step overshoots and the loss rises. The step size has to respect the curvature of the loss.

The same computation in NumPy, which is how you would check a hand derivation in an interview take-home:

import numpy as np

x, y = np.array([2.0, 1.0]), 2.0
W1, b1 = np.array([[0.5, -0.5], [-1.0, 0.5]]), np.zeros(2)
w2, b2 = np.array([2.0, 1.0]), 0.0

def forward(W1, b1, w2, b2):
    z = W1 @ x + b1
    h = np.maximum(z, 0.0)              # ReLU
    y_hat = w2 @ h + b2
    return z, h, y_hat, 0.5 * (y_hat - y) ** 2

z, h, y_hat, loss = forward(W1, b1, w2, b2)
d = y_hat - y                           # dL/dy_hat
g_w2, g_b2 = d * h, d
g_z = d * w2 * (z > 0)                  # back through w2, then the ReLU
g_W1, g_b1 = np.outer(g_z, x), g_z
print("loss", loss, "grad W1", g_W1.tolist(), "grad w2", g_w2.tolist())

lr = 0.05
*_, new_loss = forward(W1 - lr * g_W1, b1 - lr * g_b1, w2 - lr * g_w2, b2 - lr * g_b2)
print("loss after one step", round(new_loss, 4))

Output:

loss 0.5 grad W1 [[-4.0, -2.0], [-0.0, -0.0]] grad w2 [-0.5, -0.0]
loss after one step 0.0385

A finite-difference check, (L(θ+ϵ)−L(θ))/ϵ(L(\theta + \epsilon) - L(\theta))/\epsilon for each parameter, is the standard way to test a hand-written backward pass.

Initialisation

Weights cannot all start equal: identical units receive identical gradients and stay identical forever (the symmetry problem). Random weights must also have the right scale. If z=∑i=1nwihiz = \sum_{i=1}^{n} w_i h_i with independent zero-mean weights of variance vv, then Var⁡(z)=n v E[hi2]\operatorname{Var}(z) = n\, v\, \mathbb{E}[h_i^2]. To keep activations from shrinking or exploding layer by layer, vv must scale like 1/n1/n:

  • Xavier/Glorot (tanh, sigmoid): Var⁡(w)=2/(nin+nout)\operatorname{Var}(w) = 2/(n_{\text{in}} + n_{\text{out}}).
  • He (ReLU): Var⁡(w)=2/nin\operatorname{Var}(w) = 2/n_{\text{in}}. The factor 2 compensates for ReLU zeroing half its inputs.

For a ReLU layer with 512 inputs, He initialisation uses standard deviation 2/512=0.0625\sqrt{2/512} = 0.0625.

Worked example

vanishing gradients through sigmoids

A gradient passes back through 10 sigmoid layers. Ignoring the weights (take them to have unit scale), what is the largest factor by which the gradient can be multiplied?

Show solution

Each layer multiplies the gradient by σ′(z)=σ(z)(1−σ(z))\sigma'(z) = \sigma(z)(1 - \sigma(z)), which is maximised at z=0z = 0 with value 0.250.25. Through 10 layers the factor is at most

0.2510≈9.5×10−7.0.25^{10} \approx 9.5 \times 10^{-7} .

Early layers barely learn. The remedies are the modern defaults: ReLU-type activations (derivative 1 on the active side), He initialisation, normalisation layers, and residual connections, which give the gradient an identity path around each block.

Regularisation

Networks have far more parameters than a typical financial dataset can support, so regularisation is not optional.

  • Weight decay (L2). Add λ2∥w∥2\tfrac{\lambda}{2}\|w\|^2 to the loss. The gradient step becomes w←(1−ηλ) w−η ∇Lw \leftarrow (1 - \eta\lambda)\, w - \eta\, \nabla L: every step shrinks the weights geometrically, exactly the ridge idea from the bias–variance lesson. (With adaptive optimisers such as Adam, adding L2 to the loss is not equivalent to shrinking the weights directly; AdamW applies the decay separately.)
  • Dropout. During training, zero each hidden unit independently with probability pp and scale survivors by 1/(1−p)1/(1-p) so expected activations are unchanged ("inverted dropout"); at test time use the full network. It prevents units from co-adapting and behaves like averaging an ensemble of thinned networks.
  • Early stopping. Monitor validation loss and keep the weights from its minimum. For a quadratic loss and gradient descent from small initial weights, stopping early acts much like an L2 penalty, with the number of steps playing the role of 1/λ1/\lambda.
  • Also: smaller networks, batch normalisation (mild regularising noise), and data augmentation, which is hard to do honestly with returns.

Why neural networks struggle with low signal-to-noise

Networks dominate vision and language, where labels are nearly noise-free and data are abundant. Return prediction is the opposite regime:

  • Tiny R2R^2. A daily model with predictive correlation 0.050.05 explains 0.25%0.25\% of the variance. The gradient from the signal is a small bias buried in noisy per-sample gradients, and a flexible network fits the noise first.
  • Small effective samples. Twenty years of daily data is about 5,000 rows per asset, and overlapping labels and cross-sectional correlation make the independent information much smaller.
  • Non-stationarity. The function being learned drifts; a network trained on 2010–2019 may be fitting a relationship that no longer exists.
  • Validation noise. With a tiny signal, the validation loss is itself so noisy that early stopping and hyperparameter search become a source of overfitting.

What works better in practice: strong priors through architecture (shared weights across assets, monotonicity constraints), heavy regularisation, ensembling many seeds, simple targets (ranks or signs rather than raw returns), and benchmarking every network against a ridge regression and a boosted tree on the same features. If the network does not beat both out of sample, it is not adding anything.

Knowledge check

A network with binary cross-entropy loss outputs p = 0.62 (logit 0.5) for an example whose label is 1. What is the gradient of the loss with respect to the logit?

Knowledge check

Every weight in a hidden layer is initialised to the same value 0.01. What happens during training with gradient descent?

Knowledge check

A deep network predicting next-day returns reaches training R² of 40% and validation R² of −2%. Which response is most sensible?

Key takeaways

  • A network alternates affine maps and non-linearities; without the non-linearity depth adds nothing.
  • Backpropagation is the chain rule run backwards: ∂L/∂W=δh⊤\partial L/\partial W = \delta h^\top, and ReLU passes gradient only through active units.
  • Pair sigmoid or softmax outputs with cross-entropy to get the clean gradient p−yp - y.
  • Initialise randomly with variance about 1/nin1/n_{\text{in}} (He: 2/nin2/n_{\text{in}} for ReLU) to keep signals and gradients stable.
  • Weight decay, dropout and early stopping all trade bias for variance; in finance they are essential, and a network must beat simple baselines out of sample to justify itself.

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).