Neural network (MLP)

Train a real multilayer neural network in your browser. See what every neuron learns in 2D and 3D, edit weights, replay, and follow the math step by step.

Updated

  • Feed-forward neural networks
  • Backpropagation
  • Gradient descent
  • Activation functions
  • Regularization and overfitting
x₁x₂ŷInputHidden 1Hidden 2Output
Preparing the lab…

Intuition

One straight line is not enough

Start with the simplest case: two kinds of points, one in the centre and one in a ring around it. A network with no hidden layer can do exactly one thing — draw a straight line, calling one side blue and the other orange. The three small networks below are training right now on the same data. They differ only in the number of hidden neurons.

No hidden layer—
2 neurons—
4 neurons—

With no hidden layer, no amount of training gives more than a line, and accuracy is no better than guessing. Two neurons give two lines, which can fence off a strip but not a disc. With three or four neurons the lines close up around the centre, and accuracy gets close to 100%.

That is what a hidden layer does: each hidden neuron draws one soft boundary, and the next layer combines those boundaries into a richer shape. In the lab above, every neuron's little picture is its own boundary. Hover over one and the large picture on the right shows it full size.

Another way in: better features

There is a second route: keep the network, change its inputs. With x12x_1^2 and x22x_2^2 as features, "how far from the centre" becomes a linear question. For XOR a single feature, x1x2x_1x_2, is enough.

Circle: x₁², x₂²—
XOR: x₁x₂—
XOR: x₁, x₂ + 4 ReLU—

The two routes are really the same thing. A hidden layer does feature engineering too; the difference is that it learns the features from data instead of asking you for them.

Math

Forward: from input to output

A neuron does two things: it takes a weighted sum of its inputs and passes it through an activation function. Written for a whole layer ll:

z(l)=W(l)a(l−1)+b(l),a(l)=f(z(l))z^{(l)} = W^{(l)} a^{(l-1)} + b^{(l)}, \qquad a^{(l)} = f\big(z^{(l)}\big)

a(0)a^{(0)} is the input and the last layer's a(L)a^{(L)} is the prediction y^\hat y. Four activation functions are available:

ActivationFormulaDerivative (in terms of the output aa)Character
Tanhtanh⁡(z)\tanh(z)1−a21-a^2Outputs between −1 and 1, flat at both ends
Sigmoid1/(1+e−z)1/(1+e^{-z})a(1−a)a(1-a)Outputs between 0 and 1, even flatter
ReLUmax⁡(0,z)\max(0,z)1 if z>0z>0, else 0Cheap; no gradient on the left half
Linearzz11Many layers collapse into one

Loss: how wrong are we

For one sample the loss is half the squared difference between prediction and label. Training tries to make its average over all samples as small as possible:

L=12 (y^−y)2L = \tfrac12\,(\hat y - y)^2

To reduce the loss we need to know how much it changes when each weight changes a little — the gradient. The chain rule computes it from the output backwards. Define an error term δ=∂L/∂z\delta = \partial L / \partial z for every neuron:

δ(L)=(y^−y) f′(z(L)),δ(l)=(W(l+1)⊤δ(l+1))⊙f′(z(l))\delta^{(L)} = (\hat y - y)\, f'\big(z^{(L)}\big), \qquad \delta^{(l)} = \Big(W^{(l+1)\top}\delta^{(l+1)}\Big)\odot f'\big(z^{(l)}\big)

With δ\delta in hand, the gradients of weights and biases are one step away:

∂L∂W(l)=δ(l) a(l−1)⊤,∂L∂b(l)=δ(l)\frac{\partial L}{\partial W^{(l)}} = \delta^{(l)}\, a^{(l-1)\top}, \qquad \frac{\partial L}{\partial b^{(l)}} = \delta^{(l)}

Everything computed on the way forward — every zz and aa — is used again here, so nothing is computed twice. That is why backpropagation is fast: all the gradients together cost about as much as one forward pass.

Update: one small step downhill

Collect a batch of BB samples, average their gradients and step in the opposite direction. The learning rate η\eta sets the step size:

W←W−ηB∑i=1B∂Li∂W  −  η λ R′(W)W \leftarrow W - \frac{\eta}{B}\sum_{i=1}^{B}\frac{\partial L_i}{\partial W} \;-\; \eta\,\lambda\,R'(W)

The last term is regularization. With L2, R′(W)=WR'(W)=W pulls every weight towards 0. With L1, R′(W)=sign(W)R'(W)=\mathrm{sign}(W) pushes some weights all the way to 0. Momentum and Adam add one more step on top of the mean gradient: the first carries over earlier velocity, the second gives each parameter its own step size.

How it is computed: with real numbers

This is not an illustration. It takes the current weights and one sample from the lab above and works through the formulas step by step. Keep training, switch samples or edit a weight, and these numbers follow.

Numbers after 1 real epoch of training with the default settingsSample 1 / 250
  1. Take one sample

    x₁ = 0.9248x₂ = 1.6396y = +1

  2. Forward: neuron 1 of layer 1

    z1(1)=0.2391⋅0.9248+0.2351⋅1.64+0.1061=0.7127a1(1)=tanh⁡(0.7127)=0.6124\begin{aligned}z^{(1)}_{1} &= 0.2391\cdot0.9248 + 0.2351\cdot1.64 + 0.1061 = 0.7127\\ a^{(1)}_{1} &= \tanh(0.7127) = \mathbf{0.6124}\end{aligned}
  3. Forward: neuron 1 of layer 2

    z1(2)=(−0.247)⋅0.6124+(−0.07265)⋅0.7554+(−0.02624)⋅0.8022+0.3491⋅0.4938+0.09838=0.04353a1(2)=tanh⁡(0.04353)=0.0435\begin{aligned}z^{(2)}_{1} &= (-0.247)\cdot0.6124 + (-0.07265)\cdot0.7554 + (-0.02624)\cdot0.8022 + 0.3491\cdot0.4938 + 0.09838 \\ &= 0.04353\\ a^{(2)}_{1} &= \tanh(0.04353) = \mathbf{0.0435}\end{aligned}
  4. Forward: the output neuron

    z1(3)=(−0.4004)⋅0.0435+(−0.242)⋅(−0.02667)+0.08488=0.07391y^=tanh⁡(0.07391)=0.07378\begin{aligned}z^{(3)}_{1} &= (-0.4004)\cdot0.0435 + (-0.242)\cdot(-0.02667) + 0.08488 = 0.07391\\ \hat y &= \tanh(0.07391) = \mathbf{0.07378}\end{aligned}
  5. Loss

    L=12(y^−y)2=12(0.07378−1)2=0.4289L = \tfrac12(\hat y - y)^2 = \tfrac12(0.07378 - 1)^2 = \mathbf{0.4289}
  6. Backward: the output error term δ

    δ(3)=(y^−y) (1−y^2)=(−0.9262)⋅(1−0.073782)=−0.9212\delta^{(3)} = (\hat y - y)\,(1-\hat y^2) = (-0.9262)\cdot(1 - 0.07378^2) = \mathbf{-0.9212}
  7. Backward: passed to neuron 1 of layer 1

    δ1(1)=(∑jwj1(2) δj(2)) f′(z1(1))=((−0.247)⋅0.3682+0.2368⋅0.2227)⋅0.625=−0.02388\begin{aligned}\delta^{(1)}_1 &= \Big(\sum_j w^{(2)}_{j1}\,\delta^{(2)}_j\Big)\,f'(z^{(1)}_1)\\ &= \big((-0.247)\cdot0.3682 + 0.2368\cdot0.2227\big)\cdot 0.625 = \mathbf{-0.02388}\end{aligned}
  8. Gradient of this link (x₁ → neuron 1 of layer 1)

    ∂L∂w11(1)=δ1(1) a1(0)=(−0.02388)⋅0.9248=−0.02209\frac{\partial L}{\partial w^{(1)}_{11}} = \delta^{(1)}_1\, a^{(0)}_1 = (-0.02388)\cdot 0.9248 = \mathbf{-0.02209}
  9. Update the weight

    w11(1)←w−η gˉ=0.2391−0.03⋅0.008273=0.238851w^{(1)}_{11} \leftarrow w - \eta\,\bar g = 0.2391 - 0.03\cdot 0.008273 = \mathbf{0.238851}

    ḡ is the mean gradient over this batch of 10 samples; each one goes through the steps above.

Experiment

Work through a course

Course

Lesson 1: how a network learns to fence in the centre

5 steps · each one: set up and run → look → answer

  1. 1. What happens with no hidden layer

    Remove the hidden layers so the network is just inputs and an output. Look at the large picture: what shape is the boundary? Is the loss curve still going down?

    Why does the loss stop at about 0.5 after 200 epochs?
  2. 2. Add a layer and see what each neuron learns

    Now add one hidden layer with 4 neurons. When training finishes, hover over each neuron in layer 1 and look at its picture.

    What shape does each neuron in layer 1 learn?
  3. 3. Switch off one link by hand

    When it has finished, click a thick link from layer 1 to "Output" in the network, press "Set to 0" and see which part of the boundary disappears. Then press "Undo".

    What happens to the fenced-off region when you set a link to the output to 0?
  4. 4. A learning rate that is too large

    Set the learning rate to 10 and leave everything else at its default. Watch the loss curve and the neurons' pictures.

    Why does the loss refuse to go down with a learning rate of 10?
  5. 5. Overfitting: learning the rule or memorizing the answers

    This one is deliberately hard: noise 50, only 20% of the data for training, and a large network. Watch the two loss curves: blue is the training set, orange is the test set.

    Training loss keeps falling while test loss goes up. What does that mean?

Try these settings

Press one and it is loaded into the lab above and trained automatically.

The six Sigmoid layers are worth a closer look. When training finishes, read the error terms δ of each layer in the step inspector: they shrink towards the front. Sigmoid's derivative is at most 0.25; multiplied by modest weights layer after layer, the gradient of layer 1 ends up about a hundred thousand times smaller than the output layer's. The early layers barely hear anything. This is the vanishing gradient problem.

Exercises

Exercises

The lab above checks these live and ticks them off.

Exercise 1: separate the circle with as few parameters as you can

You may change the hidden layers and the input features. Goal: at least 98% test accuracy with at most 17 parameters.

Hint

Three hidden neurons: 2 weights and 1 bias each, plus 3 weights and 1 bias for the output — 13 parameters. Can features do better? With x₁² and x₂² and no hidden layer, 3 parameters are enough (if it gets stuck, press "Regenerate" for another seed).

  • Test accuracy ≥ 98.0%
  • at most 17 parameters

Exercise 2: tame the spiral

The default 4-2 network stays below 70% after 500 epochs. Change the structure, the optimizer or the features to reach at least 95% test accuracy.

Hint

Features help most: add sin x₁ and sin x₂ to an 8-8 network and 300 epochs pass 99%. With x₁ and x₂ alone it takes longer: 8-8 reaches about 94% after 1000 epochs, and Adam at 0.01 hovers around 95%.

  • Test accuracy ≥ 95.0%

Exercise 3: hold back overfitting

Leave the noise and the data split alone. Reach at least 74% test accuracy.

Hint

Two ways work: L2 regularization with a rate of 0.03, or stopping early — click the loss curve where the test loss is lowest (around epoch 40).

  • Test accuracy ≥ 74.0%

Quick questions

Can a 2-layer network with linear hidden activations separate XOR?
Roughly what does it cost backpropagation to compute every weight's gradient?

Further reading

Frequently asked questions

What is the difference between a multi-layer perceptron (MLP) and a perceptron?

A perceptron is a single neuron with a step function and can only draw one straight line; a multi-layer perceptron has hidden layers and differentiable activations, can be trained by backpropagation, and can approximate any continuous function (one wide enough hidden layer suffices, Cybenko 1989).

How many hidden layers and neurons should I use?

Start small: for two-dimensional classification, one or two hidden layers of 4–8 neurons are usually enough. Add more if it underfits; if training looks good but test performance drops, remove some or add regularisation. This page's exercises are exactly about finding the smallest network that is good enough under a parameter limit.

Which activation function should I choose?

ReLU is the default for hidden layers: cheap, and its gradient does not decay on the positive side. Tanh is zero-centred and common in small networks; sigmoid makes gradients shrink layer by layer in deep networks (vanishing gradients) and is usually kept for the output of binary classifiers.

What is backpropagation?

Using the chain rule from the output layer backwards, it computes the partial derivative of the loss with respect to every weight, layer by layer. Computing all the gradients costs about as much as one or two forward passes, which is what makes large networks trainable.

What should I do if my neural network overfits?

The sign is training loss still falling while test loss rises. Use fewer neurons or layers, add L2 / L1 regularisation, stop early, get more data, or add noise to the inputs. On this page you can switch between L1 / L2 regularisation and adjust its rate directly, and watch the test curve respond.

Further reading