Khush Shah

A Neural Network from Scratch: Four Versions

Khush Shah 26 min read Machine Learning, Python, Tutorials

Writing a neural network by hand is the quickest way I know to see what nn.Linear and optim.Adam do for you. In this post I fit a straight line, $y = 4 + 3x$, with a tiny network (one input, two ReLU units in a hidden layer, one output) and build it four times in PyTorch: from eight scalar tensors, through helper functions and a list of layers, to nn.Sequential. The first three versions never learn the line, and not because of a bug: the inputs run up to 100 and the targets up to about 300, and plain gradient descent cannot cope with that scale. I show why with three small experiments (the scale of the gradients, the learning rate and dead ReLUs), and then fix it in three steps: normalise the data, choose a sensible learning rate and switch to Adam. On the way I write out the backward pass by hand and check it against autograd.

First we import the necessary libraries, and fix the seed of the random number generator so that every run of the notebook gives the same numbers.

import torch as t
import matplotlib.pyplot as plt

t.manual_seed(0);

Here we define the dataset to use.

x - 1,000 numbers from 0 to 99.9 with a step of 0.1

f - a function that we will use to generate the y values, $f(x) = 4 + 3x$

y - a collection of y values generated from the x values using the function f and adding some noise (t.randn(len(x), 1), standard normal, so the noise has variance 1)

So the targets run from about 4 to about 304, and no model can get the mean squared error much below 1, the variance of the noise.

x = t.arange(0, 100, 0.1, dtype=t.float32).reshape(-1, 1)

def f(x):
    return 4 + 3 * x

f_vals = f(x)
eps = t.randn(len(x), 1)

y = f_vals + eps

Check the shapes: x, y and f_vals are each a column of 1,000 values

x.shape, y.shape, f_vals.shape
(torch.Size([1000, 1]), torch.Size([1000, 1]), torch.Size([1000, 1]))

Plot the data and the function used to generate it

plt.scatter(x.ravel(), y.ravel(), label='data')
plt.plot(x.ravel(), f_vals.ravel(), color='red', label='True function')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.show()
Scatter plot of the 1,000 data points, y against x for x from 0 to 100. They lie in a narrow band along the red true line y = 4 + 3x, which rises from 4 to about 304.

Define a function to plot the data for visualisation

def graph(y_hat):
    """
    This is a function to graph the data
    y_hat - tensor of the predicted values by training (in the units of y)
    """
    plt.scatter(x, y, label='data')
    plt.plot(x, f_vals, color='red', label='True function')
    plt.plot(x, y_hat.detach().numpy(), color='green', label='Pred')
    plt.xlabel('x')
    plt.ylabel('y')
    plt.legend()
    plt.show()

Define the loss function. I use the mean squared error,

$$L = \frac{1}{N}\sum_{i=1}^{N}(y_i - \hat{y}_i)^2,$$

the usual loss for regression with Gaussian noise. Loss Functions for Regression and Classification shows where it comes from and how it compares with MAE and the Huber loss.

def loss_function(y, y_hat):
    """
    This is a function to calculate the loss with "Mean Squared Error"
    y - tensor of the actual values
    y_hat - tensor of the predicted values
    """
    return t.mean(t.square(y - y_hat))

The network

Every version below builds the same network: one input, a hidden layer of two ReLU units and one output (a 1-2-1 network). With $\operatorname{relu}(z) = \max(0, z)$ the forward pass is

$$\begin{aligned} a_1 &= \operatorname{relu}(w_{11}x + b_{11}),\\ a_2 &= \operatorname{relu}(w_{12}x + b_{12}),\\ \hat{y} &= w_{21}a_1 + w_{22}a_2 + b_2. \end{aligned}$$

In the code, $w_{1j}$ and $b_{1j}$ (w11, w12, b11, b12) belong to the hidden layer and $w_{21}$, $w_{22}$ to the output. Versions 1 and 2 give each output term its own bias, b21 and b22, but only their sum $b_2 = b_{21} + b_{22}$ matters.

Why two hidden units? Two ReLUs can represent $a\max(0, x) + b\max(0, -x) + c$, and since $x = \max(0, x) - \max(0, -x)$, the choice $a = 3$, $b = -3$, $c = 4$ (that is, $w_{11} = 1$, $w_{12} = -1$, $b_{11} = b_{12} = 0$, $w_{21} = 3$, $w_{22} = -3$ and $b_2 = 4$) gives exactly $4 + 3x$ for every $x$. So the target is learnable. Here all the inputs are positive, so a single unit with a positive slope would already be enough; that matters below, because the network needs only one of its two units to stay alive.

Version 1

Define the neural network weights and biases, one scalar tensor each, and keep a copy of their starting values for the experiments further down

w11 = t.randn(1, requires_grad=True)
w12 = t.randn(1, requires_grad=True)
w21 = t.randn(1, requires_grad=True)
w22 = t.randn(1, requires_grad=True)

b11 = t.randn(1, requires_grad=True)
b12 = t.randn(1, requires_grad=True)
b21 = t.randn(1, requires_grad=True)
b22 = t.randn(1, requires_grad=True)

start_1 = [p.detach().clone() for p in (w11, w12, w21, w22, b11, b12, b21, b22)]

The backward pass by hand

l.backward() in the training loop below computes the gradient of the loss with respect to every parameter. For this network it is short enough to write out. With $z_{j} = w_{1j}x + b_{1j}$ for unit $j$, the chain rule gives, for the output weights,

$$\frac{\partial L}{\partial w_{2j}} = -\frac{2}{N}\sum_{i=1}^{N}(y_i - \hat{y}_i)\,a_{j,i},$$

and for the hidden weights, where the derivative of the ReLU is 1 if $z_{j,i} > 0$ and 0 otherwise,

$$\begin{aligned} \frac{\partial L}{\partial w_{1j}} = -\frac{2}{N}\sum_{i=1}^{N}\,&(y_i - \hat{y}_i)\,w_{2j}\\ &\times \mathbb{1}[z_{j,i} > 0]\,x_i. \end{aligned}$$

The biases have the same gradients without the last factor ($a_{j,i}$ or $x_i$). Here are the four weight gradients at the starting values, from autograd and from the formulas:

y_hat = (w21 * t.relu(w11 * x + b11) + b21) + (w22 * t.relu(w12 * x + b12) + b22)
l = loss_function(y, y_hat)

# torch.autograd.grad returns the gradients without storing them in .grad
auto = t.autograd.grad(l, [w11, w12, w21, w22])

with t.no_grad():
    err = y - y_hat
    z1, z2 = w11 * x + b11, w12 * x + b12
    by_hand = [
        -2 * t.mean(err * w21 * (z1 > 0) * x),   # dL/dw11
        -2 * t.mean(err * w22 * (z2 > 0) * x),   # dL/dw12
        -2 * t.mean(err * t.relu(z1)),           # dL/dw21
        -2 * t.mean(err * t.relu(z2)),           # dL/dw22
    ]

for name, a, h in zip(["w11", "w12", "w21", "w22"], auto, by_hand):
    # "or 0.0" prints -0.0 as 0.0
    print(f"dL/d{name}: autograd {(a.item() or 0.0):10.1f}   by hand {(h.item() or 0.0):10.1f}")
dL/dw11: autograd        0.0   by hand        0.0
dL/dw12: autograd   -25122.3   by hand   -25122.3
dL/dw21: autograd        0.0   by hand        0.0
dL/dw22: autograd    -6033.6   by hand    -6033.6

The two agree. The gradients for unit 1, w11 and w21, are exactly zero; the reason is the third problem below.

The training loop. I update each parameter in place inside torch.no_grad(), rather than assigning to w.data. .data changes the tensor behind autograd's back, so if a graph still needed the old value its gradients would be silently wrong; an in-place update under no_grad is not recorded in the graph, and autograd still notices the change and raises an error if the old value was needed. Setting grad to None afterwards clears the gradient, because backward() adds to whatever is already there.

losses_1 = []

lr = 0.0001

for i in range(5000):
    z1 = (w11 * x + b11)
    a1 = t.relu(z1)
    z2 = (w12 * x + b12)
    a2 = t.relu(z2)

    y_hat = ((w21 * a1 + b21) + (w22 * a2 + b22))

    l = loss_function(y, y_hat)

    if i % 100 == 0:
        print(f"{i} loss: {l}")

    losses_1.append(l.item())

    l.backward()

    with t.no_grad():
        w11 -= lr * w11.grad
        w12 -= lr * w12.grad
        w21 -= lr * w21.grad
        w22 -= lr * w22.grad

        b11 -= lr * b11.grad
        b12 -= lr * b12.grad
        b21 -= lr * b21.grad
        b22 -= lr * b22.grad

        w11.grad = None
        w12.grad = None
        w21.grad = None
        w22.grad = None

        b11.grad = None
        b12.grad = None
        b21.grad = None
        b22.grad = None
0 loss: 21543.01171875
100 loss: 29627.1953125
200 loss: 27925.201171875
300 loss: 26354.087890625
400 loss: 24903.79296875
500 loss: 23565.015625
600 loss: 22329.19140625
700 loss: 21188.396484375
800 loss: 20135.333984375
900 loss: 19163.248046875
1000 loss: 18265.916015625
1100 loss: 17437.5859375
1200 loss: 16672.955078125
1300 loss: 15967.1220703125
1400 loss: 15315.568359375
1500 loss: 14714.1162109375
1600 loss: 14158.9140625
1700 loss: 13646.408203125
1800 loss: 13173.3095703125
1900 loss: 12736.5927734375
2000 loss: 12333.4609375
2100 loss: 11961.328125
2200 loss: 11617.8095703125
2300 loss: 11300.708984375
2400 loss: 11007.98828125
2500 loss: 10737.7802734375
2600 loss: 10488.3515625
2700 loss: 10258.103515625
2800 loss: 10045.560546875
2900 loss: 9849.3603515625
3000 loss: 9668.2578125
3100 loss: 9501.0732421875
3200 loss: 9346.74609375
3300 loss: 9204.28515625
3400 loss: 9072.779296875
3500 loss: 8951.3876953125
3600 loss: 8839.330078125
3700 loss: 8735.888671875
3800 loss: 8640.40234375
3900 loss: 8552.2587890625
4000 loss: 8470.8935546875
4100 loss: 8395.78515625
4200 loss: 8326.453125
4300 loss: 8262.451171875
4400 loss: 8203.3720703125
4500 loss: 8148.83447265625
4600 loss: 8098.4921875
4700 loss: 8052.02197265625
4800 loss: 8009.123046875
4900 loss: 7969.5244140625

Plot the losses to see how the model is learning

plt.plot(losses_1, label='Version 1')
plt.yscale('log')
plt.xlabel('Epoch')
plt.ylabel('MSE loss')
plt.legend()
plt.show()
Version 1's training loss on a log scale over 5,000 epochs. It jumps from about 21,500 to about 31,400 in the first two epochs, then falls slowly and smoothly to about 7,900, still falling a little at the end.

Plot the model predictions against the actual data and the function used to generate the data

graph(y_hat)
The data and the red true line, with version 1's prediction as a horizontal green line at about 133 that crosses the data near x = 43.

Version 1 does not learn the line. The loss jumps from 21,543 to about 31,400 in the first two epochs, then falls slowly and smoothly to 7,933 after 5,000 epochs, nowhere near the noise floor of about 1. The prediction is a flat line at about 133: the network has learnt nothing about $x$. A loss close to 7,494 is a warning sign on this data, because 7,494 is the variance of $y$, the loss of predicting the mean of $y$ everywhere.

Why is the loss not falling?

The code has no bug: the backward pass agrees with autograd, and the update is plain gradient descent. Three things work against it, and each one shows up in a small experiment: the scale of the data, the learning rate and dead ReLUs. They are linked. The scale makes some gradients huge, the learning rate turns a huge gradient into a huge step, and a huge step can switch a ReLU unit off for every input, after which it never learns again.

1. Scale

The inputs run up to 100 and the targets to about 300, while the weights start as standard normal numbers. The gradient for a weight is the error times an input (or a hidden activation, which grows with the input), averaged over the data, while the gradient for a bias is the error alone. With inputs averaging 50, the weights get gradients tens or hundreds of times larger than the biases. Here are the eight gradients at version 1's starting values, and the first step each parameter takes with lr = 1e-4:

names = ["w11", "w12", "w21", "w22", "b11", "b12", "b21", "b22"]

def version_1_forward(params, x):
    """Version 1's forward pass, with its eight parameters in a list."""
    w11, w12, w21, w22, b11, b12, b21, b22 = params
    return (w21 * t.relu(w11 * x + b11) + b21) + (w22 * t.relu(w12 * x + b12) + b22)

params = [p.clone().requires_grad_(True) for p in start_1]
y_hat_0 = version_1_forward(params, x)
print(f"At the start the predictions run from {y_hat_0.min():.1f} to {y_hat_0.max():.1f},")
print(f"and the targets from {y.min():.1f} to {y.max():.1f}.")
print()

grads = t.autograd.grad(loss_function(y, y_hat_0), params)
print("parameter  start value   gradient   first step")
for name, p, g in zip(names, params, grads):
    step = -lr * g.item() if g.item() else 0.0
    print(f"{name:>9} {p.item():12.3f} {g.item():10.1f} {step:12.3f}")
At the start the predictions run from -0.8 to 53.2,
and the targets from 2.9 to 304.6.

parameter  start value   gradient   first step
      w11       -1.473        0.0        0.000
      w12        0.379   -25122.3        2.512
      w21       -0.263        0.0        0.000
      w22        1.484    -6033.6        0.603
      b11       -0.291        0.0        0.000
      b12       -1.510     -381.0        0.038
      b21       -0.370     -257.6        0.026
      b22       -0.466     -257.6        0.026

At the start the predictions run from -0.8 to 53 and the targets from 3 to 305, so the errors are in the hundreds. Unit 1 is off for every input (both $w_{11}$ and $b_{11}$ are negative), so w11, w21 and b11 get no gradient at all. For unit 2, the gradient for $w_{12}$ is 66 times the one for $b_{12}$ and about 100 times the ones for the output biases. With lr = 1e-4 the first step moves $w_{12}$ by 2.5, almost seven times its starting value, while the output biases, which have to travel about 150 to reach the targets, move by 0.026. One learning rate cannot suit both kinds of parameter.

2. Learning rate

Still, a different learning rate might do better. The function below is version 1's training loop, and I run it from the same starting values with nine learning rates from 1e-6 to 1e-2, for 5,000 epochs each, printing the final loss and the trained network's predictions at both ends of the data. The dashed line in the plot is the loss of the best constant prediction (the mean of $y$, whose loss is the variance of $y$) and the dotted line is the loss of the true line, which is just the noise.

def version_1(start, lr, epochs=5000):
    """Version 1's training loop, from a copy of the starting values.
    Returns the loss at every epoch and the trained parameters."""
    params = [p.clone().requires_grad_(True) for p in start]
    losses = []
    for i in range(epochs):
        l = loss_function(y, version_1_forward(params, x))
        losses.append(l.item())
        l.backward()
        with t.no_grad():
            for p in params:
                p -= lr * p.grad
                p.grad = None
    return losses, params

learning_rates = [1e-6, 3e-6, 1e-5, 3e-5, 1e-4, 3e-4, 1e-3, 3e-3, 1e-2]
final_losses = []
ends = t.tensor([[0.0], [99.9]])   # the true line gives 4.0 and 303.7 here

print("learning rate   final loss   prediction at x = 0   at x = 99.9")
for rate in learning_rates:
    losses, params = version_1(start_1, rate)
    final_losses.append(losses[-1])
    with t.no_grad():
        at_0, at_end = version_1_forward(params, ends).ravel().tolist()
    print(f"{rate:13.0e} {losses[-1]:12,.1f} {at_0:21.1f} {at_end:13.1f}")
learning rate   final loss   prediction at x = 0   at x = 99.9
        1e-06         16.3                  -0.8         307.6
        3e-06         15.2                  -0.7         307.4
        1e-05         12.3                  -0.4         307.0
        3e-05          7.5                   0.1         306.2
        1e-04      7,933.3                 132.9         132.9
        3e-04      7,494.3                 153.5         153.5
        1e-03      7,494.2                 153.9         153.9
        3e-03      7,494.2                 153.9         153.9
        1e-02      7,494.2                 153.9         153.9
best_constant = loss_function(y, y.mean()).item()   # predict the mean of y everywhere
true_line = loss_function(y, f_vals).item()         # the noise alone

plt.loglog(learning_rates, final_losses, 'o-', label='Version 1, final loss')
plt.axhline(best_constant, color='grey', linestyle='--',
            label=f'Constant prediction (the mean of y): {best_constant:,.0f}')
plt.axhline(true_line, color='black', linestyle=':',
            label=f'True line (noise only): {true_line:.2f}')
plt.xlabel('Learning rate')
plt.ylabel('MSE loss after 5,000 epochs')
plt.legend(loc='center right')
plt.show()
Final loss after 5,000 epochs against the learning rate, both on log scales. From 1e-6 to 3e-5 the loss falls from 16 to 7.5, well above the dotted line at 1.06 for the true line. At 1e-4 it jumps to 7,933, and from 3e-4 to 1e-2 it sits on the dashed line at 7,494, the loss of predicting the mean of y.
Version 1's final loss for nine learning rates, all from the same starting values.

There is a cliff between 3e-5 and 1e-4, and no learning rate gets the loss below 7.5, seven times the noise floor of 1.06.

  • At 3e-5 and below, unit 2 survives and the network fits a line, but the wrong one: it predicts about 0 at $x = 0$ instead of 4, and about 307 at $x = 99.9$ instead of 303.7. The weights, with their large gradients, have found a slope that fits the data, but the intercept depends on the biases, whose gradients are a hundred times smaller, and they have hardly moved; the slope comes out a little too steep to make up for it.
  • At 1e-4, version 1's rate, and above, the network predicts the same value everywhere: 132.9 at 1e-4, and the mean of $y$, 153.9, from 1e-3 up, where the loss is exactly the variance of $y$.

So lr = 1e-4 is at the same time too large for the weights and too small for the biases, and no rate in between suits both. A larger rate does not make the loss blow up to infinity, as it would for a linear model. The reason is the third problem.

3. Dead ReLUs

A ReLU unit outputs $\max(0, z)$. If its pre-activation $z = w_{1j}x + b_{1j}$ is negative for every input, its output is 0 everywhere and so is its derivative, and by the formulas in the backward pass the gradients for $w_{1j}$, $b_{1j}$ and $w_{2j}$ are all exactly 0. The unit is dead: no gradient step can bring it back. With $x \ge 0$ this happens as soon as $w_{1j} \le 0$ and $b_{1j} \le 0$. Here is how many of the 1,000 inputs switch each unit of version 1 on, at the start, after one and two steps, and at the end:

def inputs_on(w, b):
    """How many of the 1,000 inputs switch a hidden unit on (pre-activation above 0)."""
    return int((w * x + b > 0).sum())

print(f"At the start:      unit 1 is on for {inputs_on(start_1[0], start_1[4])} inputs, "
      f"unit 2 for {inputs_on(start_1[1], start_1[5])}")
for steps in (1, 2):
    _, p = version_1(start_1, lr, epochs=steps)
    print(f"After {steps} step{'s' if steps > 1 else ' '}:     unit 1 is on for {inputs_on(p[0], p[4])} inputs, "
          f"unit 2 for {inputs_on(p[1], p[5])} (w12 = {p[1].item():.3f})")
print(f"After 5,000 steps: unit 1 is on for {inputs_on(w11, b11)} inputs, unit 2 for {inputs_on(w12, b12)}")
print(f"The trained prediction runs from {y_hat.min().item():.2f} to {y_hat.max().item():.2f}")
At the start:      unit 1 is on for 0 inputs, unit 2 for 960
After 1 step :     unit 1 is on for 0 inputs, unit 2 for 994 (w12 = 2.892)
After 2 steps:     unit 1 is on for 0 inputs, unit 2 for 0 (w12 = -1.163)
After 5,000 steps: unit 1 is on for 0 inputs, unit 2 for 0
The trained prediction runs from 132.92 to 132.92

Unit 1 was dead from the start. The first step made $w_{12}$ almost eight times larger (and $w_{22}$ grew from 1.48 to 2.09), so the slope of the network jumped to about $2.89 \times 2.09 \approx 6$, twice the true slope, and the second step threw $w_{12}$ down to -1.163, which switched unit 2 off for every input. After two steps both units were dead, and the network has predicted a constant ever since. That is what the loss curve shows. The jump to about 31,400 is the moment the prediction became a constant near 0. The slow fall after it is the two output biases creeping towards the mean of $y$: each step moves $b_{21} + b_{22}$ by $4 \times \text{lr} = 0.0004$ of the remaining distance, so after 5,000 steps they have covered $1 - e^{-2} \approx 86\%$ of it and reached 132.9, and the loss is the variance of $y$, 7,494, plus $(153.9 - 132.9)^2 \approx 440$.

To check that this is the whole story, here is a run that starts dead: the same starting values as version 1, except that $w_{12}$ is negative, so both units are off for every input.

dead = [p.clone() for p in start_1]
dead[1] = -dead[1]   # w12 < 0 and b12 < 0, so w12 * x + b12 < 0 for every x >= 0

params = [p.clone().requires_grad_(True) for p in dead]
grads = t.autograd.grad(loss_function(y, version_1_forward(params, x)), params)
print("Gradients at the start:")
print(", ".join(f"{name} {(g.item() or 0.0):.1f}" for name, g in zip(names, grads)))

dead_losses, _ = version_1(dead, lr)
print(f"Loss: {dead_losses[0]:,.0f} at the start, {dead_losses[-1]:,.0f} at the end "
      f"(version 1: {losses_1[-1]:,.0f})")
Gradients at the start:
w11 0.0, w12 0.0, w21 0.0, w22 0.0, b11 0.0, b12 0.0, b21 -309.4, b22 -309.4
Loss: 31,431 at the start, 7,933 at the end (version 1: 7,933)

All the gradients are exactly zero except those for the two output biases, so only the biases learn, and after 5,000 epochs this network ends at 7,933, the same loss as version 1. After its second step, version 1 was exactly this network.

So the fix has to make the gradients for the weights and the biases of similar size, so that one learning rate suits all of them and no first step is large enough to kill a unit. Versions 2 and 3 first reorganise the code; they still train on the raw data with lr = 1e-4 and fail in the same ways. The fixes come after them, in Fixing the training.

Version 2

Define a function to initialise the weights and biases of the neural network by giving the number of weights required. It creates the same number of biases and returns the weights first and then the biases, the order in which they are unpacked below.

def init(weights_no):
    """
    This is a function to initialise the weights and biases
    weights_no - number of weights required; the same number of biases is created
    Returns a list of the weights followed by the biases: [w_1, ..., w_n, b_1, ..., b_n]
    """
    weights = []
    biases = []

    for _ in range(weights_no):
        weights.append(t.randn(1, requires_grad=True))

    for _ in range(weights_no):
        biases.append(t.randn(1, requires_grad=True))

    return weights + biases

Define a forward propagation function to calculate the predictions of the neural network

def forward(x, w11, w12, w21, w22, b11, b12, b21, b22):
    """
    This is a function for forward propagation of the neural network
    x - tensor of the input values
    w's - tensors of the weights
    b's - tensors of the biases
    """
    z1 = (w11 * x + b11)
    a1 = t.relu(z1)

    z2 = (w12 * x + b12)
    a2 = t.relu(z2)

    y_a = ((w21 * a1 + b21) + (w22 * a2 + b22))

    return y_a

Define a function to update the weights and biases of the neural network

def update(w11, w12, w21, w22, b11, b12, b21, b22, lr):
    """
    This is a function to update the weights and biases
    w's - tensors of the weights
    b's - tensors of the biases
    lr - learning rate
    """
    with t.no_grad():
        w11 -= lr * w11.grad
        w12 -= lr * w12.grad
        w21 -= lr * w21.grad
        w22 -= lr * w22.grad

        b11 -= lr * b11.grad
        b12 -= lr * b12.grad
        b21 -= lr * b21.grad
        b22 -= lr * b22.grad

        w11.grad = None
        w12.grad = None
        w21.grad = None
        w22.grad = None

        b11.grad = None
        b12.grad = None
        b21.grad = None
        b22.grad = None

Initialise the weights and biases of the neural network using the function defined above

w11, w12, w21, w22, b11, b12, b21, b22 = init(4)

learning_rate = 0.0001

losses_2 = []

The training loop

for i in range(5000):
    y_hat = forward(x, w11, w12, w21, w22, b11, b12, b21, b22)

    l = loss_function(y, y_hat)

    if i % 100 == 0:
        print(f"{i} loss: {l}")

    losses_2.append(l.item())

    l.backward()

    update(w11, w12, w21, w22, b11, b12, b21, b22, learning_rate)
0 loss: 30957.1171875
100 loss: 29152.828125
200 loss: 27487.283203125
300 loss: 25949.818359375
400 loss: 24530.58203125
500 loss: 23220.484375
600 loss: 22011.12890625
700 loss: 20894.775390625
800 loss: 19864.259765625
900 loss: 18912.990234375
1000 loss: 18034.869140625
1100 loss: 17224.2734375
1200 loss: 16476.01171875
1300 loss: 15785.2919921875
1400 loss: 15147.6884765625
1500 loss: 14559.1142578125
1600 loss: 14015.7978515625
1700 loss: 13514.2578125
1800 loss: 13051.291015625
1900 loss: 12623.923828125
2000 loss: 12229.419921875
2100 loss: 11865.248046875
2200 loss: 11529.078125
2300 loss: 11218.7587890625
2400 loss: 10932.302734375
2500 loss: 10667.8759765625
2600 loss: 10423.7802734375
2700 loss: 10198.4541015625
2800 loss: 9990.4521484375
2900 loss: 9798.4482421875
3000 loss: 9621.2060546875
3100 loss: 9457.58984375
3200 loss: 9306.5537109375
3300 loss: 9167.130859375
3400 loss: 9038.42578125
3500 loss: 8919.6181640625
3600 loss: 8809.9443359375
3700 loss: 8708.7021484375
3800 loss: 8615.2421875
3900 loss: 8528.9658203125
4000 loss: 8449.3212890625
4100 loss: 8375.796875
4200 loss: 8307.923828125
4300 loss: 8245.267578125
4400 loss: 8187.423828125
4500 loss: 8134.02587890625
4600 loss: 8084.72998046875
4700 loss: 8039.224609375
4800 loss: 7997.21044921875
4900 loss: 7958.42333984375

Plot the losses to see how the model is learning

plt.plot(losses_2, label='Version 2')
plt.yscale('log')
plt.xlabel('Epoch')
plt.ylabel('MSE loss')
plt.legend()
plt.show()
Version 2's training loss on a log scale, falling slowly and smoothly from about 31,000 to about 7,900 over 5,000 epochs.

Plot the model predictions against the actual data and the function used to generate the data

graph(y_hat)
The data and the red true line, with version 2's prediction as a green horizontal line at about 133, with a tiny kink at the far left.

Version 2 does the same arithmetic as version 1, from different random numbers, and fails in the same way: the loss falls slowly from 30,957 to 7,923 and the prediction is flat at about 133, apart from the small kink at the left edge, where unit 2 is still on for the eight smallest inputs. Tidier code does not change the optimisation.

Version 3

Define a function to initialise the weights and biases of the neural network by giving the tuple of the number of neurons in each layer

def init(weight_bias_no):
    """
    This is a function to initialise the weights and biases
    weight_bias_no - tuple of the number of neurons in each layer (inclusive of input and output layers)
    Each weight matrix has the shape (neurons in the next layer, neurons in this layer),
    like nn.Linear.weight, and each bias is a column
    """
    weights = []
    biases = []

    for i in range(len(weight_bias_no)-1):
        weights.append(t.randn((weight_bias_no[i+1], weight_bias_no[i]), requires_grad=True, dtype=t.float32))
        biases.append(t.randn((weight_bias_no[i+1], 1), requires_grad=True, dtype=t.float32))

    return weights, biases

Define a forward propagation function to calculate the predictions of the neural network

def forward(x, weights, biases):
    """
    This is a function for forward propagation of the neural network
    x - tensor of the input values
    weights - list of tensors of the weights
    biases - list of tensors of the biases
    """
    z = []
    a = [x]
    n = len(weights)

    for i in range(n-1):
        z.append(t.matmul(a[i], weights[i].t()) + biases[i].t())
        a.append(t.relu(z[i]))

    y_a = t.matmul(a[-1], weights[-1].t()) + biases[-1].t()

    return y_a

Shapes and transposes

init stores each weight matrix as (outputs, inputs), the same layout as nn.Linear.weight, and each bias as a column. The data has one row per example, so x is (1000, 1). To get one row of pre-activations per example, forward multiplies by the transpose of the weight matrix, (1000, 1) times (1, 2) gives (1000, 2), and adds the bias as a row of shape (1, 2), which broadcasts down all 1,000 rows. .t() swaps rows and columns:

a = t.arange(1, 9).reshape(4, 2)   # 4 rows, 2 columns
a, a.t()                           # .t() gives 2 rows, 4 columns
(tensor([[1, 2],
         [3, 4],
         [5, 6],
         [7, 8]]),
 tensor([[1, 3, 5, 7],
         [2, 4, 6, 8]]))
W1, b1 = t.zeros(2, 1), t.zeros(2, 1)   # the shapes init gives the hidden layer of a 1-2-1 network
x.shape, W1.t().shape, b1.t().shape, (x @ W1.t() + b1.t()).shape
(torch.Size([1000, 1]),
 torch.Size([1, 2]),
 torch.Size([1, 2]),
 torch.Size([1000, 2]))

Define a function to update the weights and biases of the neural network

def update(weights, biases, lr):
    """
    This is a function to update the weights and biases
    weights - list of tensors of the weights
    biases - list of tensors of the biases
    lr - learning rate
    """
    with t.no_grad():
        for weight in weights:
            weight -= lr * weight.grad
            weight.grad = None

        for bias in biases:
            bias -= lr * bias.grad
            bias.grad = None

Initialise the weights and biases of the neural network using the function defined above. In version 1 the large errors at the start produced the huge first steps that killed both units. The targets have a mean of about 154 while a random output bias starts near 0, so here I add 50 to the output bias: the predictions start nearer the targets, and the first steps are smaller. 50 is a hand-tuned number for this data set; standardising the targets, in Fixing the training, does the same job for any data without a magic number. I also keep a copy of the starting values without the 50, for the experiments below.

weights, biases = init((1, 2, 1))
start_3 = [p.detach().clone() for p in weights + biases]   # a copy, for the experiments below

with t.no_grad():
    biases[-1] += 50.0   # start the output nearer the targets (see above)

learning_rate = 0.0001

losses_3 = []
biases
[tensor([[-1.1143],
         [-0.2877]], requires_grad=True),
 tensor([[50.3998]], requires_grad=True)]

The training loop

for i in range(5000):
    y_hat = forward(x, weights, biases)

    l = loss_function(y, y_hat)

    if i % 100 == 0:
        print(f"{i} loss: {l}")

    losses_3.append(l.item())

    l.backward()

    update(weights, biases, learning_rate)
0 loss: 11766.0126953125
100 loss: 816.9451293945312
200 loss: 4557.73876953125
300 loss: 7177.482421875
400 loss: 16833.3359375
500 loss: 1509.658447265625
600 loss: 513.4253540039062
700 loss: 12562.8701171875
800 loss: 3728.819580078125
900 loss: 737.185791015625
1000 loss: 5388.60595703125
1100 loss: 1170.11767578125
1200 loss: 15620.173828125
1300 loss: 5097.11962890625
1400 loss: 5483.97412109375
1500 loss: 12966.1962890625
1600 loss: 1392.5162353515625
1700 loss: 8338.0810546875
1800 loss: 526.0313720703125
1900 loss: 3282.36279296875
2000 loss: 5060.57568359375
2100 loss: 2764.1630859375
2200 loss: 10986.353515625
2300 loss: 880.66552734375
2400 loss: 14641.263671875
2500 loss: 3133.822509765625
2600 loss: 4326.0947265625
2700 loss: 2793.03955078125
2800 loss: 4843.48291015625
2900 loss: 13302.2275390625
3000 loss: 4388.88916015625
3100 loss: 4642.78955078125
3200 loss: 13343.263671875
3300 loss: 3508.115966796875
3400 loss: 4387.43603515625
3500 loss: 2153.24560546875
3600 loss: 2520.51953125
3700 loss: 4117.52099609375
3800 loss: 3866.26416015625
3900 loss: 504.0680236816406
4000 loss: 1595.4049072265625
4100 loss: 2279.694091796875
4200 loss: 2312.04541015625
4300 loss: 2628.932861328125
4400 loss: 11966.1318359375
4500 loss: 701.8838500976562
4600 loss: 1495.31005859375
4700 loss: 7462.615234375
4800 loss: 2074.06005859375
4900 loss: 2910.693603515625

Plot the losses to see how the model is learning

plt.plot(losses_3, label='Version 3')
plt.yscale('log')
plt.xlabel('Epoch')
plt.ylabel('MSE loss')
plt.legend()
plt.show()
Version 3's training loss on a log scale over 5,000 epochs. It jumps between about 500 and 17,000 at almost every step for the whole run, a dense band with no downward trend, apart from a stretch between about epochs 2,700 and 3,400 where the low points rise to a few thousand.

Plot the model predictions against the actual data and the function used to generate the data

graph(y_hat)
The data and the red true line, with version 3's prediction in green: flat at about 61 up to x of about 9, then rising slowly in a straight line to about 92 at x = 100, far below the data for most x.

Version 3 keeps its units alive (the + 50 did its job), but now the loss jumps up and down between about 500 and 17,000, it is 12,288 at the end, and the prediction at the last epoch is a bent line far below most of the data. The oscillation does not come from the list-of-layers architecture, which computes the same function as versions 1 and 2. It comes from a learning rate that is too high for the unnormalised inputs. With both units on for most inputs, the loss is very steep along the hidden weights, whose gradients are multiplied by inputs of up to 100, so a step of lr = 1e-4 along them jumps right across the valley to the far side, where the gradient is as large again and points back. The loss bounces from one side of the valley to the other instead of going down it; this is the same imbalance as in the learning-rate sweep for version 1. To check, here is the same start with lr = 1e-5, and, for comparison, the same random numbers without the + 50:

def train_version_3(start, x_train, y_train, lr, epochs=5000):
    """Version 3's training loop, from a copy of the starting values.
    Returns the loss at every epoch, the weights and the biases."""
    n = len(start) // 2
    weights = [p.clone().requires_grad_(True) for p in start[:n]]
    biases = [p.clone().requires_grad_(True) for p in start[n:]]
    losses = []
    for i in range(epochs):
        l = loss_function(y_train, forward(x_train, weights, biases))
        losses.append(l.item())
        l.backward()
        update(weights, biases, lr)
    return losses, weights, biases

with_50 = start_3[:-1] + [start_3[-1] + 50.0]
runs = [("+ 50, lr = 1e-4 (version 3)", with_50, 1e-4),
        ("+ 50, lr = 1e-5", with_50, 1e-5),
        ("no + 50, lr = 1e-4", start_3, 1e-4)]

for label, start, rate in runs:
    losses, w, b = train_version_3(start, x, y, rate)
    rises = sum(later > earlier for earlier, later in zip(losses, losses[1:]))
    on = (x @ w[0].t() + b[0].t() > 0).sum(dim=0).tolist()
    print(f"{label}: final loss {losses[-1]:,.0f}, the loss rose at {rises:,} of 4,999 steps,")
    print(f"    inputs that switch each hidden unit on at the end: {on}")
+ 50, lr = 1e-4 (version 3): final loss 12,288, the loss rose at 3,232 of 4,999 steps,
    inputs that switch each hidden unit on at the end: [912, 912]
+ 50, lr = 1e-5: final loss 372, the loss rose at 0 of 4,999 steps,
    inputs that switch each hidden unit on at the end: [951, 974]
no + 50, lr = 1e-4: final loss 10,689, the loss rose at 4 of 4,999 steps,
    inputs that switch each hidden unit on at the end: [0, 0]

With lr = 1e-5 the loss falls at every one of the 4,999 steps, so the oscillation is the learning rate's doing. But it ends at 372, because a rate small enough for the weights is again too small for the biases, as in the sweep for version 1. Without the + 50, both units are off for every input at the end and the loss is 10,689: the first steps killed them, just as in version 1.

Fixing the training

The three experiments point to three fixes, which I apply in order. First, normalise the inputs and the targets, so that every parameter sees gradients of a similar size. Second, choose a learning rate that suits the normalised problem. Third, use an optimiser that adapts the step for each parameter (Adam); that is version 4. Steps 1 and 2 use version 3's code and its starting values, without the + 50.

Step 1: normalise the inputs and the targets

normalize standardises a tensor: it subtracts the mean and divides by the standard deviation, and returns the mean and the standard deviation as well, so that denormalize can map predictions back to the original units. x.std() on a (1000, 1) tensor takes the standard deviation of all 1,000 values (with the $n - 1$ denominator), which is what we want for a single feature. Here all 1,000 points are training data. With a training and a validation split, the mean and the standard deviation must come from the training data only, and the same numbers are then used to transform the validation data and to map the predictions back.

def normalize(x):
    mean = x.mean()
    std = x.std()
    return (x - mean) / std, mean, std

def denormalize(x, mean, std):
    return x * std + mean
x_n, x_mean, x_std = normalize(x)
y_n, y_mean, y_std = normalize(y)

print(f"x: mean {x_mean:.2f}, std {x_std:.2f}; x_n runs from {x_n.min():.2f} to {x_n.max():.2f}")
print(f"y: mean {y_mean:.2f}, std {y_std:.2f}; y_n runs from {y_n.min():.2f} to {y_n.max():.2f}")
x: mean 49.95, std 28.88; x_n runs from -1.73 to 1.73
y: mean 153.88, std 86.61; y_n runs from -1.74 to 1.74

Both now run from about -1.7 to 1.7. The mean of y_n is 0, so a randomly initialised output bias, near 0, already starts near the mean of the targets: this is the principled version of the + 50.

Next I train version 3 from its starting values on the standardised data, still with lr = 1e-4. The loss is computed on y_n, so I multiply it by the variance of $y$ to get it back in the units of $y$: since $y - \hat{y} = s_y (y_n - \hat{y}_n)$, where $s_y$ is the standard deviation of $y$, the mean squared error scales by $s_y^2$.

on = (x_n @ start_3[0].t() + start_3[2].t() > 0).sum(dim=0).tolist()
print(f"Standardised inputs that switch each hidden unit on at the start: {on}")

losses_n, _, _ = train_version_3(start_3, x_n, y_n, 1e-4)
losses_step_1 = [l * y_std.item() ** 2 for l in losses_n]   # MSE in the units of y

print(f"Loss in the units of y: {losses_step_1[0]:,.0f} at the start, {losses_step_1[-1]:,.0f} at the end")
Standardised inputs that switch each hidden unit on at the start: [0, 361]
Loss in the units of y: 7,398 at the start, 4,262 at the end

Unit 1 happens to be off for every standardised input from the start (its kink is at $x_n = 2.45$, beyond the data), so these runs use unit 2 alone; as noted in The network, one unit is enough for a line. The loss now falls smoothly, but slowly: from 7,398 to 4,262 in 5,000 epochs. On standardised data the gradients are of order 1, so a step of 1e-4 is simply too small. Standardising fixed the balance between the parameters; now the learning rate has to be chosen for the new scale.

Step 2: a sensible learning rate

With every gradient of order 1, a step can be a sizeable fraction of 1. Here are the final losses, in the units of $y$, for five learning rates from the same start:

for rate in (1e-3, 1e-2, 1e-1, 3e-1, 1.0):
    losses_n, _, _ = train_version_3(start_3, x_n, y_n, rate)
    print(f"lr = {rate:<6g} final loss in the units of y {losses_n[-1] * y_std.item() ** 2:12,.2f}")
lr = 0.001  final loss in the units of y       457.68
lr = 0.01   final loss in the units of y         1.70
lr = 0.1    final loss in the units of y         1.06
lr = 0.3    final loss in the units of y     2,617.11
lr = 1      final loss in the units of y   104,563.05
losses_n, fit_weights, fit_biases = train_version_3(start_3, x_n, y_n, 0.1)
losses_step_2 = [l * y_std.item() ** 2 for l in losses_n]

y_hat = denormalize(forward(x_n, fit_weights, fit_biases), y_mean, y_std)
print(f"Final loss {losses_step_2[-1]:.3f}; after the last update, on the original scale: {loss_function(y, y_hat).item():.3f}")

on = (x_n @ fit_weights[0].t() + fit_biases[0].t() > 0).sum(dim=0).tolist()
print(f"Inputs that switch each hidden unit on at the end: {on}")
Final loss 1.056; after the last update, on the original scale: 1.056
Inputs that switch each hidden unit on at the end: [0, 999]
graph(y_hat)
The data and the red true line, with the prediction of version 3 trained on standardised data with learning rate 0.1 and mapped back to the original units. The green line lies on the red true line from x = 0 to 100.

Now 0.01 gets the loss to 1.70 and 0.1 to 1.06, the loss of the true line itself, within about 1,200 epochs (see the plot in Results): what is left is the noise. Above that, at 0.3 and 1, the steps overshoot again. On the raw data no learning rate got below 7.5. The prediction, mapped back with denormalize, lies on the true line, and plain gradient descent, the same update as version 3, did it.

Version 4

The third fix is an adaptive optimiser, and this is where nn.Sequential and optim.Adam come in. Adam keeps a running average of each parameter's gradient and of its square, and divides the first by the square root of the second, so each parameter moves by roughly the learning rate at each step, whatever the size of its gradient. That removes the imbalance between weights and biases that broke versions 1 to 3, and lets the default lr = 1e-3 work without tuning. I train version 4 on the standardised data from step 1. (The last section of Loss Functions for Regression and Classification shows the same effect on a linear model: multiplying $x$ by 100 breaks gradient descent but not Adam.)

Import some more libraries

from torch import nn
import torch.optim as optim

Initialise the neural network using the nn.Sequential() function with Linear layers having standard normal distribution weights (the biases keep nn.Linear's default initialisation, uniform on $[-1/\sqrt{n}, 1/\sqrt{n}]$ for $n$ inputs)

l1 = nn.Linear(1, 2)
l2 = nn.Linear(2, 1)

nn.init.normal_(l1.weight, mean=0, std=1.0)
nn.init.normal_(l2.weight, mean=0, std=1.0)

model = nn.Sequential(l1, nn.ReLU(), l2)
start_4 = {k: v.clone() for k, v in model.state_dict().items()}   # a copy, for the comparison of optimisers below

model.to("cpu")
Sequential(
  (0): Linear(in_features=1, out_features=2, bias=True)
  (1): ReLU()
  (2): Linear(in_features=2, out_features=1, bias=True)
)

The parameters it starts with

list(model.named_parameters())
[('0.weight',
  Parameter containing:
  tensor([[-1.4287],
          [-0.8795]], requires_grad=True)),
 ('0.bias',
  Parameter containing:
  tensor([-0.1172, -0.9416], requires_grad=True)),
 ('2.weight',
  Parameter containing:
  tensor([[-0.6802,  0.3323]], requires_grad=True)),
 ('2.bias',
  Parameter containing:
  tensor([0.1697], requires_grad=True))]

Define the optimiser. The loss is the same loss_function as before.

optimizer = optim.Adam(model.parameters(), lr = 0.001)

Check the shapes, and plot the predictions of the untrained model, mapped back to the units of y with denormalize

x_n.shape, model(x_n).shape
(torch.Size([1000, 1]), torch.Size([1000, 1]))
y_hat_untrained = denormalize(model(x_n), y_mean, y_std)
graph(y_hat_untrained.ravel())
The data and the red true line, with version 4's prediction before training, mapped back to the units of y: a bent green line that starts at about 46 at x = 0, rises with kinks near x = 19 and x = 48, and is flat at about 168 from x = 48 to 100.

The training loop, on the standardised data. I record and print the loss in the units of y, so that it can be compared with the other versions.

losses_4 = []
for epoch in range(5000):
    y_hat = model(x_n)

    loss = loss_function(y_n, y_hat)

    losses_4.append(loss.item() * y_std.item() ** 2)

    model.zero_grad()

    loss.backward()

    optimizer.step()

    if epoch % 100 == 0:
        print(f"{epoch} loss: {losses_4[-1]}")
0 loss: 3129.072144607964
100 loss: 2376.0589376149674
200 loss: 1949.4261101902794
300 loss: 1654.007662975544
400 loss: 1424.930768203262
500 loss: 1233.824749071282
600 loss: 1069.6839515821416
700 loss: 928.6341798469165
800 loss: 806.4369352355548
900 loss: 698.3263800013214
1000 loss: 599.6019580178615
1100 loss: 507.50457066354727
1200 loss: 420.99401568076473
1300 loss: 340.54573665150275
1400 loss: 268.25344033897755
1500 loss: 207.05235439411715
1600 loss: 158.63134731231438
1700 loss: 122.11768263652351
1800 loss: 94.94955280653727
1900 loss: 74.50930736920121
2000 loss: 58.904673602266215
2100 loss: 46.84906422839198
2200 loss: 37.485815175772984
2300 loss: 30.142387422293996
2400 loss: 24.350416431540943
2500 loss: 19.793662915661425
2600 loss: 16.196012658105246
2700 loss: 13.330903888035829
2800 loss: 11.032288185956682
2900 loss: 9.206988684294641
3000 loss: 7.727979045148917
3100 loss: 6.522728743896569
3200 loss: 5.558033685818127
3300 loss: 4.776017913804393
3400 loss: 4.1342761458456
3500 loss: 3.6107313399522023
3600 loss: 3.181183002455045
3700 loss: 2.828361222670526
3800 loss: 2.5376481120775165
3900 loss: 2.296171090886821
4000 loss: 2.098394906123617
4100 loss: 1.9347443757693379
4200 loss: 1.7966177302374058
4300 loss: 1.6781204589199747
4400 loss: 1.5791570436071098
4500 loss: 1.4977002058111486
4600 loss: 1.4304439238316518
4700 loss: 1.3732930318086136
4800 loss: 1.3265279712064035
4900 loss: 1.2859870954909012

Plot the losses to see how the model is learning

plt.plot(losses_4, label='Version 4')
plt.yscale('log')
plt.xlabel('Epoch')
plt.ylabel('MSE loss, in the units of y')
plt.legend()
plt.show()
Version 4's training loss on a log scale, falling smoothly from about 3,100 at the start to about 1.3 after 5,000 epochs.

Plot the predictions of the model against the actual data and the function used to generate the data

y_hat = denormalize(model(x_n), y_mean, y_std)
graph(y_hat.ravel())
The data and the red true line, with version 4's prediction in green lying on the true line, except at the far right, above x of about 98, where it flattens slightly.

Adam brings the loss down from 3,129 to 1.25, close to the noise floor of 1.06, and the prediction lies on the true line except for the last few inputs, above about $x = 98$, where it flattens slightly: the kink where one hidden unit switches off started near $x = 48$ (see the untrained plot) and has not quite moved past the end of the data. On this small, well-scaled problem Adam is slower than gradient descent with a tuned learning rate, because steps of about 0.001 take a while to cover distances of order 1; its advantage is that its learning rate needed no tuning.

Results

All losses are mean squared errors in the units of y, so they can be compared directly. The true line itself scores 1.06 on this data, which is as low as any model should go.

Change made Loss at the start Final loss
Version
1 Eight scalar tensors, plain gradient descent, ... 21,543 7,933
2 Helper functions for init, forward and update ... 30,957 7,923
3 List of layers, output bias + 50 11,766 12,288
3, step 1 Inputs and targets standardised, lr = 1e-4 7,398 4,262
3, step 2 Standardised, lr = 0.1 7,398 1.06
4 nn.Sequential and Adam (lr = 1e-3), standardised 3,129 1.25
plt.figure(figsize=(8, 6))
curves = [
    ("Version 1", losses_1, "-"),
    ("Version 2", losses_2, "-"),
    ("Version 3", losses_3, "-"),
    ("Version 3, standardised, lr = 1e-4", losses_step_1, "--"),
    ("Version 3, standardised, lr = 0.1", losses_step_2, "--"),
    ("Version 4 (Adam), standardised", losses_4, "-"),
]
for label, curve, style in curves:
    faint = label == "Version 3"
    plt.plot(curve, style, linewidth=1, label=label,
             alpha=0.35 if faint else 1.0, zorder=1 if faint else 2)
plt.axhline(true_line, color='black', linestyle=':', label='True line (noise only)')
plt.yscale('log')
plt.xlabel('Epoch')
plt.ylabel('MSE loss, in the units of y')
plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.12), ncol=2)
plt.show()
Training loss against epoch on a log scale for six runs. Versions 1 and 2 fall slowly from about 31,000 to about 7,900. Version 3, drawn faint, oscillates between about 500 and 17,000 throughout. Version 3 on standardised data with learning rate 1e-4 falls slowly from about 7,400 to about 4,300. With learning rate 0.1 it drops to the dotted noise floor of 1.06 within about 1,200 epochs. Version 4 with Adam falls smoothly from about 3,100 to 1.25.
Training loss of every run, in the units of y. Version 3's curve is drawn faint because it changes at almost every step.

Only the runs on standardised data learn the line. Versions 1 and 2 end as constant predictions near 133 because both of their units died in the first steps, and version 3 keeps its units but bounces between the sides of the valley because its learning rate is too high for the raw inputs. Standardising alone lets the loss fall smoothly but slowly; standardising with a sensible learning rate, or with Adam, reaches the noise floor. None of the code in versions 1 to 3 was wrong. The data was on the wrong scale for plain gradient descent.

Gradient descent, momentum and Adam

Version 4 switched to nn.Sequential and to Adam at the same time, and nn.Sequential is only a tidier way to write the same network. To see what Adam adds, I train version 4's network from its starting values on the same standardised data with three optimisers from torch.optim: plain gradient descent (SGD), gradient descent with momentum 0.9 (SGD with momentum=0.9) and Adam, each at six learning rates from 1e-3 to 0.3. Momentum keeps a running sum of the gradients, $v \leftarrow 0.9\,v + g$, and steps by the learning rate times $v$. Where the gradient keeps pointing the same way, $v$ grows to about $1/(1 - 0.9) = 10$ times the gradient, so the steps are about ten times longer than those of plain gradient descent at the same learning rate. Adam, as above, scales each parameter's step to about the learning rate.

The table gives the final loss of each run and the first epoch at which it got within 10% of the noise floor; the plot shows the curves at lr = 1e-3 (Adam's default) and lr = 1e-2.

def train_version_4(make_optimizer, epochs=5000):
    """Version 4's network and training loop, from version 4's starting values,
    with the optimiser that make_optimizer builds. Returns the loss at every epoch
    in the units of y."""
    net = nn.Sequential(nn.Linear(1, 2), nn.ReLU(), nn.Linear(2, 1))
    net.load_state_dict(start_4)
    opt = make_optimizer(net.parameters())
    losses = []
    for epoch in range(epochs):
        loss = loss_function(y_n, net(x_n))
        losses.append(loss.item() * y_std.item() ** 2)
        opt.zero_grad()
        loss.backward()
        opt.step()
    return losses

optimizers = {
    "Gradient descent": lambda params, lr: optim.SGD(params, lr=lr),
    "Momentum (0.9)": lambda params, lr: optim.SGD(params, lr=lr, momentum=0.9),
    "Adam": lambda params, lr: optim.Adam(params, lr=lr),
}
target = 1.1 * true_line   # within 10% of the noise floor
opt_losses = {}

print(f"Final loss after 5,000 epochs, and (in brackets) the first epoch with a loss below {target:.2f}")
print(f"{'lr':>6}" + "".join(f"{name:>26}" for name in optimizers))
for rate in (1e-3, 3e-3, 1e-2, 3e-2, 1e-1, 3e-1):
    row = f"{rate:>6g}"
    for name, make in optimizers.items():
        losses = train_version_4(lambda params: make(params, rate))
        opt_losses[name, rate] = losses
        first = next((i for i, l in enumerate(losses) if l < target), None)
        row += f"{losses[-1]:>18,.2f} ({first if first is not None else 'never':>5})"
    print(row)
print(f"Version 4 itself (Adam, lr = 1e-3) ended at {losses_4[-1]:.3f}; "
      f"the same run here ends at {opt_losses['Adam', 1e-3][-1]:.3f}")
Final loss after 5,000 epochs, and (in brackets) the first epoch with a loss below 1.16
    lr          Gradient descent            Momentum (0.9)                      Adam
 0.001            776.21 (never)              3.56 (never)              1.25 (never)
 0.003             95.44 (never)              1.22 (never)              1.05 ( 2538)
  0.01              3.58 (never)              1.06 ( 1752)              1.06 (  892)
  0.03              1.22 (never)              1.06 (  522)              1.05 (  299)
   0.1              1.07 ( 1818)              1.06 (   94)              1.19 (   69)
   0.3          2,603.45 (never)          7,494.17 (never)              3.67 (   68)
Version 4 itself (Adam, lr = 1e-3) ended at 1.251; the same run here ends at 1.251
plt.figure(figsize=(8, 6))
for (name, colour) in zip(optimizers, ["C0", "C1", "C2"]):
    for rate, style in ((1e-3, "--"), (1e-2, "-")):
        plt.plot(opt_losses[name, rate], style, color=colour, linewidth=1.2,
                 label=f"{name}, lr = {rate:g}")
plt.axhline(true_line, color='black', linestyle=':', label='True line (noise only)')
plt.yscale('log')
plt.xlabel('Epoch')
plt.ylabel('MSE loss, in the units of y')
plt.legend(loc='upper right')
plt.show()
Training loss against epoch on a log scale for version 4's network trained with three optimisers; dashed curves are at learning rate 0.001 and solid ones at 0.01. Gradient descent at 0.001 falls slowly from about 3,100 to about 780. Gradient descent at 0.01 and momentum at 0.001 lie exactly on top of each other and fall to about 3.6. Adam at 0.001 falls to 1.25. Momentum and Adam at 0.01 both drop steeply to the dotted noise floor of 1.06, Adam within about 900 epochs and momentum within about 1,750.
Version 4's network from its starting values on the standardised data, trained with three optimisers at two learning rates.

Three things stand out.

  • Momentum at lr = 1e-3 and plain gradient descent at lr = 1e-2 give the same curve: in the plot the solid blue curve is hidden under the dashed orange one, and they end at 3.58 and 3.56. On this smooth problem momentum 0.9 behaves like gradient descent with a ten times larger learning rate. It does not find a different answer; it takes longer steps where the gradient keeps pointing the same way.
  • Adam gets within 10% of the noise floor first at every learning rate where any of the three does, and it is the only one that survives lr = 0.3, although there it ends at 3.67 after bouncing around. At that rate gradient descent ends at 2,603 and momentum at 7,494, the variance of $y$: a constant prediction, the dead-ReLU failure of version 1 again.
  • Plain gradient descent needs its learning rate tuned: only lr = 0.1 reaches the noise floor within 5,000 epochs, and it takes 1,818 epochs from these starting values.

With a well-chosen learning rate all three get to the noise floor; what differs is how much tuning each needs and how fast it gets there. Here Adam is fastest and least sensitive, then momentum, then plain gradient descent. The Adam run at lr = 1e-3 is version 4 itself, and it ends at the same 1.251.

A curve: when the hidden layer matters

So far the hidden layer has had an easy job: the target is a straight line, which a linear model with no hidden layer could fit just as well, and the two ReLUs only had to stay alive. To end, here is a target where the hidden layer matters: $y = \sin x$ on $[0, 2\pi]$, with noise of standard deviation 0.1. A 1-$H$-1 ReLU network computes

$$\hat{y} = \sum_{j=1}^{H} w_{2j}\operatorname{relu}(w_{1j}x + b_{1j}) + b_2,$$

a sum of $H$ ramps plus a constant. That is a broken line with at most $H$ kinks, one per hidden unit, at $x = -b_{1j}/w_{1j}$, so the number of hidden units limits how closely the network can follow a curve.

I draw 200 points with $x$ uniform on $[0, 2\pi]$ and keep 50 of them aside as validation data, which the network never trains on: the loss on them shows how well a fit carries over to new data from the same curve. As promised in Step 1, the mean and the standard deviation used to standardise $x$ come from the 150 training points only, and the same numbers transform the validation points. The targets are already of order 1 and centred near 0, so I leave them as they are.

import math

t.manual_seed(0)
n_points = 200
x_sin = t.rand(n_points, 1) * 2 * math.pi            # uniform on [0, 2 pi]
y_sin = t.sin(x_sin) + 0.1 * t.randn(n_points, 1)    # noise with standard deviation 0.1

order = t.randperm(n_points)
train_idx, val_idx = order[:150], order[150:]        # 150 for training, 50 for validation

# standardise x with the statistics of the training points only
x_tr, x_sin_mean, x_sin_std = normalize(x_sin[train_idx])
x_va = (x_sin[val_idx] - x_sin_mean) / x_sin_std
y_tr, y_va = y_sin[train_idx], y_sin[val_idx]

noise_tr = loss_function(y_tr, t.sin(x_sin[train_idx])).item()
noise_va = loss_function(y_va, t.sin(x_sin[val_idx])).item()
print(f"x: training mean {x_sin_mean:.3f}, standard deviation {x_sin_std:.3f}")
print(f"Loss of the true curve (noise only): training {noise_tr:.4f}, validation {noise_va:.4f}")
print(f"Loss of predicting the mean of the training targets everywhere: {loss_function(y_tr, y_tr.mean()).item():.4f}")

# the best straight line, by least squares: what a network without a hidden layer can do
design = lambda x: t.cat([x, t.ones_like(x)], dim=1)
coef = t.linalg.lstsq(design(x_tr), y_tr).solution
line_tr = loss_function(y_tr, design(x_tr) @ coef).item()
line_va = loss_function(y_va, design(x_va) @ coef).item()
print(f"Best straight line: training {line_tr:.4f}, validation {line_va:.4f}")
x: training mean 2.845, standard deviation 1.820
Loss of the true curve (noise only): training 0.0107, validation 0.0128
Loss of predicting the mean of the training targets everywhere: 0.5118
Best straight line: training 0.2153, validation 0.1979

A straight line misses the curve badly: its loss is 0.215 on the training points, twenty times the 0.0107 of the true curve. That is the best a network without a hidden layer can do.

The function below builds a 1-$H$-1 network with nn.Linear's default initialisation and trains it with Adam, lr = 0.01, on all 150 training points at once for 5,000 epochs, recording the training and the validation loss at every epoch. Small networks depend a lot on their random start (a unit that starts dead stays dead), so I train each width from five seeds.

def train_net(width, x_train, y_train, x_val, y_val, seed=0, lr=0.01, epochs=5000):
    """A 1-width-1 ReLU network (nn.Linear's default initialisation) trained with
    Adam on the whole training set. Returns the training and validation loss at
    every epoch, and the trained network."""
    t.manual_seed(seed)
    net = nn.Sequential(nn.Linear(1, width), nn.ReLU(), nn.Linear(width, 1))
    opt = optim.Adam(net.parameters(), lr=lr)
    train_losses, val_losses = [], []
    for epoch in range(epochs):
        loss = loss_function(y_train, net(x_train))
        with t.no_grad():
            val_losses.append(loss_function(y_val, net(x_val)).item())
        train_losses.append(loss.item())
        opt.zero_grad()
        loss.backward()
        opt.step()
    return train_losses, val_losses, net

widths = (1, 2, 4, 8, 16)
best_nets = {}
print("width   training loss, seeds 0 to 4                  median validation loss")
for width in widths:
    runs = [train_net(width, x_tr, y_tr, x_va, y_va, seed=s) for s in range(5)]
    finals = [r[0][-1] for r in runs]
    val_median = sorted(r[1][-1] for r in runs)[2]
    best_nets[width] = runs[finals.index(min(finals))][2]   # lowest training loss
    print(f"{width:5}   " + "  ".join(f"{v:.4f}" for v in finals) + f"   {val_median:12.4f}")
width   training loss, seeds 0 to 4                  median validation loss
    1   0.1591  0.1591  0.5118  0.5118  0.1591         0.1827
    2   0.5118  0.1578  0.1927  0.0387  0.5118         0.1696
    4   0.0143  0.1578  0.1591  0.0387  0.1766         0.1226
    8   0.0143  0.0115  0.0108  0.0111  0.0118         0.0184
   16   0.0110  0.0095  0.0108  0.0099  0.0099         0.0153
grid = t.linspace(0, 2 * math.pi, 500).reshape(-1, 1)
grid_n = (grid - x_sin_mean) / x_sin_std

plt.figure(figsize=(8, 5))
plt.scatter(x_sin[train_idx], y_tr, s=12, color='grey', alpha=0.6, label='Training data')
plt.plot(grid, t.sin(grid), color='black', linestyle=':', label='True curve, sin(x)')
plt.plot(grid, design(grid_n) @ coef, color='grey', linestyle='--', label='Best straight line')
with t.no_grad():
    for width in (2, 4, 16):
        plt.plot(grid, best_nets[width](grid_n), linewidth=1.5, label=f'{width} hidden units')
plt.xlabel('x')
plt.ylabel('y')
plt.legend(loc='lower left')
plt.show()
Noisy sine data for x from 0 to 2 pi, with the true curve dotted. The best straight line, dashed, falls from about 0.9 to about -1 and misses the curve almost everywhere. The 2-unit network follows the curve in three straight pieces up to x of about 4, then stays flat at about -0.77, missing the trough and the final rise. The 4-unit network follows the whole curve in straight pieces, overshooting the peak and the trough a little. The 16-unit network follows the curve closely along its whole length.
Fits to a noisy sine curve by networks with 2, 4 and 16 hidden units (for each width, the best of five seeds by training loss), and by the best straight line.

The fit improves with width, and so does its reliability. A single unit, one ramp, gets no lower than 0.1591. With 2 units the best of five seeds reaches 0.0387, the curve of three straight pieces in the plot, but two of the five runs end at 0.5118, the loss of predicting the mean of the targets everywhere: both units died. With 4 units the best run reaches 0.0143, close to the noise floor of 0.0107, but three of the five runs end above 0.15. From 8 units every seed ends between 0.0108 and 0.0143, and with 16 units between 0.0095 and 0.0110. The median validation loss falls from 0.1696 with 2 units to 0.0153 with 16, close to the 0.0128 of the true curve on the same 50 points. More units give more kinks to bend the line with, and more chances that enough of them start alive and in useful places. That 16 units reach a training loss of 0.0095, a little below the noise floor, is a first sign of the network fitting the noise.

Overfitting with a very wide network

A network with many more parameters than data points can fit the noise as well as the curve: the training loss keeps falling, below the noise floor, while the validation loss stops falling and starts to rise. My first try was 1,000 hidden units (3,001 parameters) on the same 150 training points:

wide_tr, wide_va, _ = train_net(1000, x_tr, y_tr, x_va, y_va)
best = min(range(len(wide_va)), key=wide_va.__getitem__)
print(f"1,000 hidden units, 150 training points: final training loss {wide_tr[-1]:.4f}, "
      f"final validation loss {wide_va[-1]:.4f}")
print(f"Lowest validation loss {wide_va[best]:.4f}, at epoch {best:,} "
      f"(noise only: training {noise_tr:.4f}, validation {noise_va:.4f})")
1,000 hidden units, 150 training points: final training loss 0.0081, final validation loss 0.0137
Lowest validation loss 0.0128, at epoch 1,644 (noise only: training 0.0107, validation 0.0128)

It does overfit, but hardly visibly. The training loss ends at 0.0081, below the noise floor of 0.0107, and the validation loss is lowest, 0.0128, at epoch 1,644 and ends at 0.0137, only about 7% higher. With 150 points and little noise, the points pin the curve down too closely for even 1,000 units to wander far between them.

So, to make the overfitting visible, I made the problem harder in two ways: only 20 training points, and noise with standard deviation 0.3 instead of 0.1. I keep 200 validation points, so that the validation loss is a reliable estimate, and train 16 and 1,000 hidden units for 20,000 epochs each, with Adam at lr = 1e-3 (at 0.01 the wide network's training loss jumped about too much to read the plot).

t.manual_seed(0)
n_small, n_val = 20, 200
x_all = t.rand(n_small + n_val, 1) * 2 * math.pi
y_all = t.sin(x_all) + 0.3 * t.randn(n_small + n_val, 1)   # noise with standard deviation 0.3

# the points are drawn independently, so the first 20 are a random training set
x_sm, sm_mean, sm_std = normalize(x_all[:n_small])
x_sm_va = (x_all[n_small:] - sm_mean) / sm_std
y_sm, y_sm_va = y_all[:n_small], y_all[n_small:]
noise_sm_tr = loss_function(y_sm, t.sin(x_all[:n_small])).item()
noise_sm_va = loss_function(y_sm_va, t.sin(x_all[n_small:])).item()
print(f"Loss of the true curve (noise only): training {noise_sm_tr:.4f}, validation {noise_sm_va:.4f}")

small_runs = {}
for width in (16, 1000):
    small_runs[width] = train_net(width, x_sm, y_sm, x_sm_va, y_sm_va, lr=1e-3, epochs=20000)
    tr, va, _ = small_runs[width]
    best = min(range(len(va)), key=va.__getitem__)
    print(f"{width:>5} hidden units: final training loss {tr[-1]:.4f}, final validation loss {va[-1]:.4f}; "
          f"lowest validation loss {va[best]:.4f} at epoch {best:,}, when the training loss was {tr[best]:.4f}")
Loss of the true curve (noise only): training 0.0974, validation 0.1100
   16 hidden units: final training loss 0.0502, final validation loss 0.1357; lowest validation loss 0.1239 at epoch 9,829, when the training loss was 0.0543
 1000 hidden units: final training loss 0.0007, final validation loss 0.1831; lowest validation loss 0.1214 at epoch 114, when the training loss was 0.0652
plt.figure(figsize=(8, 5))
for (width, colour) in zip(small_runs, ["C0", "C1"]):
    tr, va, _ = small_runs[width]
    plt.plot(tr, color=colour, linewidth=1.2, label=f'{width:,} hidden units, training')
    plt.plot(va, '--', color=colour, linewidth=1.2, label=f'{width:,} hidden units, validation')
plt.axhline(noise_sm_va, color='black', linestyle=':', label='True curve on the validation data (noise only)')
plt.xscale('log')
plt.yscale('log')
plt.xlabel('Epoch (log scale)')
plt.ylabel('MSE loss')
plt.legend(loc='lower left')
plt.show()
Training (solid) and validation (dashed) loss against epoch, both axes on log scales, with 20 training points. With 16 hidden units the training loss falls to about 0.05 and the validation loss settles near 0.14, above the dotted noise-only level of 0.11. With 1,000 hidden units the training loss falls steadily to below 0.001 by epoch 20,000, while the validation loss reaches its lowest point, about 0.12, near epoch 100 and then rises slowly to about 0.18.
Training and validation loss on 20 training points with noise of standard deviation 0.3, for networks with 16 and 1,000 hidden units.
grid_sm = (grid - sm_mean) / sm_std
plt.figure(figsize=(8, 5))
plt.scatter(x_all[n_small:], y_sm_va, s=10, color='grey', alpha=0.35, label='Validation data')
plt.scatter(x_all[:n_small], y_sm, s=30, color='black', label='Training data')
plt.plot(grid, t.sin(grid), color='black', linestyle=':', label='True curve, sin(x)')
with t.no_grad():
    for width in small_runs:
        plt.plot(grid, small_runs[width][2](grid_sm), linewidth=1.5, label=f'{width:,} hidden units')
plt.xlabel('x')
plt.ylabel('y')
plt.legend(loc='lower left')
plt.show()
The 20 training points in black, the 200 validation points in grey and the dotted true sine curve. The 16-unit fit is a broken line with a few kinks that follows the general shape of the curve. The 1,000-unit fit wiggles to pass through nearly every training point, with sharp spikes up to about 1.3 near x = 0.9 and down to about -1.8 near x = 4.8, far from the true curve.
The fits after 20,000 epochs on the 20 training points.

Now the overfitting is plain. The 1,000-unit network's validation loss is lowest, 0.1214, at epoch 114, when its training loss is 0.0652, already below the 0.0974 of the true curve on the training points. From there the training loss keeps falling, to 0.0007 after 20,000 epochs, while the validation loss climbs to 0.1831, two thirds above the 0.1100 of the true curve. The plot of the fits shows why: the wide network bends through almost every training point, including the noisy ones near $x = 0.9$, $3.1$ and $4.8$, and those bends are wrong for new data. The 16-unit network overfits too, more mildly: its training loss ends at 0.0502, about half the noise floor, and its validation loss at 0.1357. With 20 noisy points even 16 units are a lot.

The training loss alone cannot tell a good fit from an overfitted one, because both look like success; only data the network has not trained on can. The usual remedies are more data (the 150-point run above barely overfitted), fewer parameters, weight decay, or stopping when the validation loss stops falling: stopping the wide network at epoch 114 would have kept a validation loss of 0.1214 instead of 0.1831.

Takeaways

  • On the raw data, with inputs up to 100 and targets up to about 300, the gradients for the weights were about 100 times those for the biases, so plain gradient descent had no good learning rate. At 1e-4 and above the first steps threw the weights so far that both ReLUs died within two steps; at smaller rates the biases hardly moved. No rate from 1e-6 to 1e-2 got the loss below 7.5, against a noise floor of 1.06.
  • A loss stuck near the variance of the targets (here 7,494) means the network predicts a constant. Check whether the hidden units are dead, with pre-activations negative for every input: a dead ReLU gets exactly zero gradient and never recovers.
  • Standardise the inputs and the targets, with statistics from the training data only, and map predictions back with the same mean and standard deviation. Then plain gradient descent with lr = 0.1 reaches the noise floor, and Adam with its default lr = 1e-3 gets close (1.25) with no tuning. Checking a hand-written gradient against torch.autograd.grad takes a few lines.

References

  1. Y. LeCun, L. Bottou, G. B. Orr and K.-R. Müller, "Efficient BackProp", in Neural Networks: Tricks of the Trade, Springer, 1998. Explains why inputs should be shifted to zero mean and scaled to similar variances before training, and how the scale of the inputs limits the learning rate.
  2. L. Lu, Y. Shin, Y. Su and G. E. Karniadakis, "Dying ReLU and Initialization: Theory and Numerical Examples", Communications in Computational Physics 28(5), 2020. arXiv:1903.06733.
  3. D. P. Kingma and J. Ba, "Adam: A Method for Stochastic Optimization", ICLR, 2015. arXiv:1412.6980.
  4. I. Goodfellow, Y. Bengio and A. Courville, Deep Learning, MIT Press, 2016. Chapter 5 covers capacity, overfitting and validation sets, Chapter 6 feedforward networks, ReLUs and back-propagation, and Chapter 8 optimisation, including momentum and Adam.
  5. PyTorch documentation: Autograd mechanics (including in-place operations), torch.no_grad, torch.autograd.grad, torch.nn.Linear, torch.optim.SGD (including how momentum is applied) and torch.optim.Adam.
  6. A. Karpathy, "The spelled-out intro to neural networks and backpropagation: building micrograd", video, 2022. Builds a tiny autograd engine and a neural network on top of it from scratch, the same idea as this post taken one level deeper.
  7. B. T. Polyak, "Some methods of speeding up the convergence of iteration methods", USSR Computational Mathematics and Mathematical Physics 4(5), 1964, pp. 1-17. The original momentum method.
  8. I. Sutskever, J. Martens, G. Dahl and G. Hinton, "On the importance of initialization and momentum in deep learning", ICML, 2013.