← MAIN
LAB // NEURAL NETWORKS

NEURAL NET LAB

Drop pink and cyan points, then watch a small neural network learn where to draw the line between them.
STATUS LIVE EPOCH 0 TRAIN ACC — TEST ACC —

HOW TO USE

The goal is to teach a small network to tell the pink points from the cyan ones. The plane shows where the network currently draws the boundary between them.

Click or drag on the plane to drop points of the chosen colour, or pick a preset. Training runs by itself; PAUSE and STEP control it.

Change the layers or neurons and press RESET WEIGHTS to train again from scratch. Hover a neuron in the network to see what it detects.

THE PLANE
Points 0. Hover the plane to read the network's answer at that spot.
THE NETWORK
positive weight negative weight thicker edge = larger weight
Neurons light up for the point under the pointer on the plane. The bright bar sweeps the layers each epoch.
NEURON DETECTOR
Hover a hidden neuron in the network to see its own heat map. Pink is where it fires positive, cyan where it fires negative. Click to pin it.
LOSS CURVE
Loss now —. Pink solid: training points. Cyan dashed: held-out test points, never trained on, so a gap between them means overfitting.
DATA
BRUSH COLOUR
BRUSH MODE
ARCHITECTURE
HIDDEN LAYERS: 2
NEURONS PER LAYER: 6
PLAYBACK
More settings
INPUT FEATURES
ACTIVATION
LEARNING RATE
BATCH SIZE
OPTIMISER
L2 REGULARISATION (λ)
TEST SHARE (HELD OUT)
NOISE: 0.00
EPOCHS PER SECOND: 20
SEED 0

HOW IT WORKS

A neural network is a stack of weighted sums, each followed by a fixed bend. Training changes the weights a little at a time so that the predictions become less wrong. Everything on this page runs in JavaScript1, a port of the NumPy package, and gives the same numbers as the Python code for the same seed.

Forward pass and activations

The network has input layer a^{(0)} = x, hidden layers and one output unit. The input is the point's position, optionally widened by the chosen features. The weights W^{(l)} and biases b^{(l)} of layer l give each neuron a pre-activation, and an activation f bends it. The output is a sigmoid, so it is a probability.23

2
z^{(l)} = W^{(l)} a^{(l-1)} + b^{(l)}, \qquad a^{(l)} = f\bigl(z^{(l)}\bigr) \ \text{for hidden } l, \qquad p = \sigma\bigl(z^{(L)}\bigr)

Here L is the number of weight layers, W^{(l)} has one row per output neuron and one column per input, and \sigma(z) = 1 / (1 + e^{-z}) is the sigmoid. p is the probability that the point is pink, and z^{(L)} is its logit, the output before the sigmoid. Without a bend, a stack of weighted sums is one weighted sum, so the activation is what lets the network draw curves.

Three activations are offered. tanh squashes to (−1, 1) and is centred on 0. ReLU is \max(0, z): linear for positive input and off for negative. Sigmoid squashes to (0, 1). Each derivative is written in terms of the output a = f(z), because that value is already stored during the forward pass45.

4
f'(z) = \begin{cases} 1 - a^2 & \text{tanh} \\ a(1 - a) & \text{sigmoid} \\ [\,a > 0\,] & \text{ReLU} \end{cases}

The tanh slope is 1 at 0 and falls toward 0 at the ends. The sigmoid slope is at most 0.25, so deep sigmoid stacks learn slowly. The ReLU slope is 0 or 1. The output unit is always a sigmoid.

Datasets and input features

The page draws 200 points for each preset, with labels alternating between cyan (0) and pink (1), except XOR, whose label depends on the quadrant. Every point has a base position, a jitter pair (j_x, j_y) of standard normal draws, and a split draw u67. The base positions are these formulas, with \varepsilon standing for a standard normal draw:

8
\begin{aligned} \text{blobs:}\quad & x = \pm 0.45 + 0.25\,\varepsilon_x, \quad y = \pm 0.45 + 0.25\,\varepsilon_y \\ \text{xor:}\quad & (x, y) = (s_x,\ s_y) + 0.2\,\varepsilon, \quad s_x, s_y \in \{\pm 0.5\} \\ \text{circles:}\quad & r = r_0 + 0.05\,\varepsilon, \quad \theta \sim U(0, 2\pi), \quad (x, y) = (r\cos\theta,\ r\sin\theta) \\ \text{spiral:}\quad & t \sim U(0, 1), \quad \theta = 3.2\pi t + \text{label}\,\pi, \quad r = 0.1 + 0.8t, \quad (x, y) = (r\cos\theta,\ r\sin\theta) \\ \text{moons:}\quad & t \sim U(0, \pi), \quad (x, y) = \begin{cases} (0.6\cos t - 0.3,\ 0.6\sin t - 0.15) & \text{cyan} \\ (-0.6\cos t + 0.3,\ -0.6\sin t + 0.15) & \text{pink} \end{cases} \end{aligned}

Here r_0 = 0.4 for cyan points and r_0 = 0.85 for pink ones, so the circles preset is two concentric rings. The spiral adds 0.03\,\varepsilon to each coordinate, and the moons add 0.06\,\varepsilon to each coordinate9. Pink and cyan spiral arms are half a turn apart, because the label adds \pi. The moons are two arcs, one per class. The features are chosen from a fixed list, and each one is computed from the point's effective position (x, y).

10
\phi(x, y) = \bigl(x,\ y,\ x^2,\ y^2,\ xy,\ \sin \pi x,\ \sin \pi y\bigr)

The page feeds the network the components of \phi that are switched on. The default is (x, y). Curved features let a small network draw curved boundaries without more layers. The default needs none, because the circles are already curved in the plain coordinates.

The plane colours each grid cell by the network's probability p: cyan at 0, pink at 1, and a blend between. The brightness grows with confidence, and a bright band marks the boundary where p \approx 0.511.

11
c_k(p) = \bigl((1 - p)\, C_k + p\, P_k\bigr)\bigl(0.14 + 0.5\,|2p - 1|\bigr) + 216.75\, e^{-((p - 0.5)/0.06)^2}, \qquad k \in \{R, G, B\}

Here C = (0, 245, 255) is cyan, P = (255, 0, 160) is pink, and 216.75 = 0.85 \cdot 255 is the strength of the boundary band. The alpha channel is always 255.

Loss and accuracy

The loss measures how wrong the network is. The lab uses binary cross-entropy, which is small when the network is confident and right, and large when it is confident and wrong. For a point with logit z and label y \in \{0, 1\}, the code uses the stable form below, which is the same as -[y \log p + (1 - y) \log(1 - p)] with p = \sigma(z), but never takes the log of a number near 01213.

12
\ell(z, y) = \max(z, 0) - z\,y + \log\bigl(1 + e^{-|z|}\bigr), \qquad L = \frac{1}{n} \sum_{s=1}^{n} \ell(z_s, y_s) + \frac{\lambda}{2} \sum_{l} \lVert W^{(l)} \rVert_F^2

Here n is the number of points in the batch, \lVert \cdot \rVert_F is the Frobenius norm, and \lambda is the L2 strength (0 by default). The penalty covers the weights only, not the biases. The curves on the page plot \log_{10} of the mean loss over the training points and over the test points, with the loss floored at 10^{-6} before the log14. The penalty is not part of the plotted curves, which show the data loss.

Accuracy counts a point as correct when the network's probability is on the same side of 0.5 as its label. The code tests the logit instead, since z \ge 0 is the same as p \ge 0.515. The train and test accuracies in the header are the fraction of points correct in each set.

Backpropagation

Backpropagation computes the gradient of the loss with respect to every weight and bias. It runs the chain rule from the output back to the first layer, reusing the values stored during the forward pass. Write \delta^{(l)} for the gradient of the loss with respect to layer l's pre-activations. The output gradient of binary cross-entropy with a sigmoid is simple, and the rest follows layer by layer1613.

16
\delta^{(L)} = \frac{p - y}{n}, \qquad \frac{\partial L}{\partial W^{(l)}} = \bigl(\delta^{(l)}\bigr)^{\!\top} a^{(l-1)} + \lambda W^{(l)}, \qquad \frac{\partial L}{\partial b^{(l)}} = \sum_{s} \delta^{(l)}_s, \qquad \delta^{(l-1)} = \bigl(\delta^{(l)} W^{(l)}\bigr) \odot f'\bigl(z^{(l-1)}\bigr)

Here \delta^{(l)}_s is the row for sample s, the sums run over the batch, and \odot is the element-wise product. The last formula is the blame passed down a layer: each unit's blame is the weighted sum of the blame of the units it feeds, times its own slope f'. The code writes f' in terms of the stored activation a^{(l-1)}, which is the same number. The gradients are checked against finite differences in the test suite17.

1813
function BACKPROP(network, X, y, λ):
    forward pass: store each layer's input a and pre-activation z
    loss ← mean cross-entropy of the outputs + (λ/2) · sum of squared weights
    δ ← (p − y) / n                              # gradient at the output
    for each layer l from the last to the first:
        dW(l) ← δᵀ a(l−1) + λ W(l)               # weight gradient
        db(l) ← sum of δ over the batch           # bias gradient
        if l is not the first layer:
            δ ← (δ W(l)) × f′(z(l−1))            # pass the blame down one layer
    return loss, dW, db

Ideas in the full version. The forward pass stores every layer's activation, so the backward pass never recomputes it. The data loss uses the logit form, so it is stable for large weights. The L2 penalty is computed separately (reg) for the reported loss, while its gradient is added to each weight (\lambda W). The loss returned for plotting is the data loss only. The output gradient is divided by the batch size, so every gradient is a mean over the batch, and a batch of 16 and a batch of 160 give gradients of the same scale.

Gradient descent, Adam and mini-batches

A mini-batch is a random group of training points used for one weight update. Each epoch shuffles the training points with a Fisher-Yates shuffle, then takes one step per batch. The last batch may be smaller. A batch size of 0 or at least the number of training points means one step per epoch on all the points, which is full batch1920.

Plain gradient descent moves each parameter against its gradient by the learning rate \eta. Adam keeps a running mean of the gradient and of its square, and divides by the root of the square, so every parameter steps by roughly \eta whatever the scale of its gradient. Both are applied to every weight array and every bias array, one step per mini-batch2122.

23
\begin{aligned} \text{SGD:}\quad & \theta \leftarrow \theta - \eta\, g \\ \text{Adam:}\quad & m \leftarrow \beta_1 m + (1 - \beta_1) g, \qquad v \leftarrow \beta_2 v + (1 - \beta_2) g^2 \\ & \hat m = \frac{m}{1 - \beta_1^t}, \qquad \hat v = \frac{v}{1 - \beta_2^t}, \qquad \theta \leftarrow \theta - \eta\, \frac{\hat m}{\sqrt{\hat v} + \varepsilon} \end{aligned}

Here \theta is one parameter, g its gradient on the batch, t the number of steps taken so far, and \eta the learning rate. The code uses \beta_1 = 0.9, \beta_2 = 0.999 and \varepsilon = 10^{-8}. The bias correction 1 - \beta^t matters for the first steps, when the running means have seen only a few gradients and are still close to their starting value of 0.

2425
function ADAM-STEP(θ, g, m, v, t):
    m ← β1 · m + (1 − β1) · g                    # running mean of the gradient
    v ← β2 · v + (1 − β2) · g²                   # running mean of its square
    m̂ ← m / (1 − β1^t)                           # bias correction for the first steps
    v̂ ← v / (1 − β2^t)
    θ ← θ − η · m̂ / (√v̂ + ε)

Ideas in the full version. The step counter t is shared by every parameter and grows once per mini-batch, so the bias correction is the same for all weights. Each array keeps its own m and v, the same size as the array. Plain gradient descent does not update the running means, so it keeps no state.

2627
function TRAIN-EPOCH(net, points, batch):
    order ← the training points, shuffled
    for each batch of consecutive points in order:      # the last batch may be smaller
        gradients ← BACKPROP(net, the points of this batch)
        apply one optimiser step with the gradients

Ideas in the full version. The shuffle is seeded, so the batch order is part of the seed. The last batch is taken as it is, so every training point is used once per epoch. The page runs up to 12 epochs in one frame and carries any fraction over to the next, so the speed setting holds on any frame rate.

Initialisation

Starting every weight at 0 would make all neurons in a layer compute the same thing, so the weights start small and random. The code draws each weight uniformly, with a width chosen so that the signal keeps about the same size from layer to layer. Biases start at 02829.

28
W^{(l)}_{ji} \sim U(-c_l, c_l), \qquad c_l = \begin{cases} \sqrt{6 / (n_{\text{in}} + n_{\text{out}})} & \text{Glorot, the default} \\ \sqrt{6 / n_{\text{in}}} & \text{He, ReLU and layer } l \text{ not the output} \end{cases}

Here n_{\text{in}} and n_{\text{out}} are the layer's input and output widths. The Glorot scale is used for every layer except the ReLU hidden layers, which use the He scale. The page sets the seed of the initial weights to \text{seed} + 1 and the batch shuffle to \text{seed} + 2, the same as the Python train command30.

Overfitting and regularisation

Overfitting means the network learns the training points, including their noise, and does badly on new points. The held-out test share shows it: if training accuracy keeps rising while test accuracy stalls, the network has memorised. The page holds back the test share at random, using each point's split draw u: a point is a test point when u is below the share31.

Two remedies are on the page. L2 regularisation adds a penalty on the weights, so large weights cost loss, and its gradient is \lambda W (see the loss above). Noise moves every point by its own jitter, scaled by the noise level, which blurs the classes and makes memorising harder3233. The defaults (no L2, no noise) show the boundary bending freely, and raising either one smooths it.

32
\tilde x = x + \sigma_{\text{noise}}\, j_x, \qquad \tilde y = y + \sigma_{\text{noise}}\, j_y, \qquad \text{test point} \iff u < \tau

Here \sigma_{\text{noise}} is the noise level, j_x, j_y are the point's standard normal jitter draws, and \tau is the test share. The jitter is stored per point, so changing the noise moves the points smoothly rather than redrawing them.

Milestone. The first time a network reaches 95% accuracy on its test points (training points if there are none), after at least 20 epochs, the page shows BOUNDARY LOCKED once34.

Parameters and defaults

ParameterDefaultWhy this value
Dataset35circles, 200 pointsTwo concentric rings cannot be split by a straight line, so the default shows what hidden layers add. 200 points keep each epoch cheap enough to run many per second.
Features36x, yThe plain coordinates are enough for the circles, so the default network needs no extra features. The curved features change the boundary's shape, at the cost of more inputs.
Hidden layers372Two hidden layers of six neurons are the default. The test suite requires at least 95% test accuracy on this configuration, which is the bar the default has to clear.38
Neurons per layer6Each neuron contributes one bend, and the ring needs several. More neurons add knobs to fit on 200 points.
Activation39tanhCentred on 0 and smooth, so the early steps are well scaled, and its output in (−1, 1) maps directly onto the neuron colours.
Weight init28Glorot uniform; He for ReLUThe weight scale keeps the signal's size about the same from layer to layer, so no layer starts saturated (flat, with no slope to learn from).
Learning rate400.03With Adam, 0.03 is fast enough to see the boundary move within seconds, and low enough that it does not jump around the ring.
Batch size4116About 10 steps per epoch on the roughly 160 training points. Small batches are cheap and add sampling noise to each step, which is why the page offers 1 to full batch.
Optimiser42Adam (β₁ 0.9, β₂ 0.999, ε 1e−8)The standard defaults from Kingma and Ba (2015). Adam rescales each weight's step by its own gradient history, so one learning rate works across all the weights.
L2 λ430 (off)Off so the first run shows the unregularised boundary. Try 0.01 to see the shape tighten.
Test share4420%A fifth of the points are held out, so the test accuracy is measured on points the network never trained on.
Noise450Clean data first. Noise moves each point by noise × a normal draw, so the classes overlap more.
Epochs per second4620Fast enough that the boundary visibly moves, slow enough to follow each change. At most 12 epochs run in one frame.
Seed470The points, the starting weights and the batch order all come from the seed, so the same seed replays the same run. The browser and the Python package agree on it.

Checks in the test suite

The gradients match finite differences for every activation17. XOR with one hidden layer of four neurons reaches at least 98% training accuracy in 400 epochs48. The default configuration reaches at least 95% test accuracy, and its training loss falls38. The browser core and the Python package agree to within 1e−9 on fixed scenarios49.

Run it from the terminal: python -m nnlab train --data spiral --layers 8,8 --act tanh --epochs 500 trains the same network with the same seed and prints the loss and accuracy, then draws the boundary in text50.