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.
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.
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
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.
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.
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:
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).
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.
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.
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.
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 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.
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.
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
constants: none
function LOSS-AND-GRADS(net, X, y, n, λ):
A(0) ← X # the inputs of the batch
for each weight layer l from 1 to L: # forward pass
for each sample s and unit j:
z(l)[s, j] ← sum over i of W(l)[j, i] · A(l−1)[s, i] + b(l)[j]
A(l)[s, j] ← sigmoid(z(l)[s, j]) if l = L, else f(z(l)[s, j])
z ← z(L) # the output logits
data ← 0
for each sample s:
data ← data + max(z[s], 0) − z[s] · y[s] + log(1 + exp(−|z[s]|))
data ← data / n
reg ← (λ / 2) · sum of W(l)[j, i]² over every weight layer # biases not penalised
δ[s] ← (sigmoid(z[s]) − y[s]) / n for each sample s
for l ← L down to 1:
for each unit j in layer l:
db(l)[j] ← sum over s of δ[s, j]
for each input i:
dW(l)[j, i] ← sum over s of δ[s, j] · A(l−1)[s, i] + λ · W(l)[j, i]
if l > 1:
for each sample s and each input i of layer l:
da ← sum over j of δ[s, j] · W(l)[j, i]
δnew[s, i] ← da · f′(A(l−1)[s, i]) # slope from the stored activation
δ ← δnew
return data, reg, 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.
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.
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.
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̂ + ε)
constants: β1 = 0.9, β2 = 0.999, ε = 1e−8
function OPTIMISER-STEP(opt, net, gW, gb):
t ← t + 1 # once per mini-batch
for each weight layer l:
UPDATE(net.W(l), gW(l), mW(l), vW(l))
UPDATE(net.b(l), gb(l), mb(l), vb(l))
function UPDATE(θ, g, m, v):
if the optimiser is plain gradient descent:
for each entry k of θ:
θ[k] ← θ[k] − η · g[k]
return
c1 ← 1 − β1^t; c2 ← 1 − β2^t
for each entry k of θ:
m[k] ← β1 · m[k] + (1 − β1) · g[k]
v[k] ← β2 · v[k] + (1 − β2) · g[k]²
θ[k] ← θ[k] − η · (m[k] / c1) / (√(v[k] / c2) + ε)
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.
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
function TRAIN-EPOCH(net, opt, X, y, n, rng, batch, λ):
if n = 0: return
B ← n if batch ≤ 0 or batch ≥ n, else batch
order ← [0, 1, …, n − 1]
for i from n − 1 down to 1: # Fisher-Yates shuffle
j ← floor(rng.random() · (i + 1))
swap order[i] and order[j]
for start ← 0 to n − 1 in steps of B:
idx ← order[start] … order[min(n, start + B) − 1]
Xb ← rows idx of X; yb ← entries idx of y
data, reg, gW, gb ← LOSS-AND-GRADS(net, Xb, yb, length of idx, λ)
OPTIMISER-STEP(opt, net, gW, gb)
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.
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.
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 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.
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.
| Parameter | Default | Why this value |
|---|---|---|
| Dataset35 | circles, 200 points | Two 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. |
| Features36 | x, y | The 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 layers37 | 2 | Two 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 layer | 6 | Each neuron contributes one bend, and the ring needs several. More neurons add knobs to fit on 200 points. |
| Activation39 | tanh | Centred on 0 and smooth, so the early steps are well scaled, and its output in (−1, 1) maps directly onto the neuron colours. |
| Weight init28 | Glorot uniform; He for ReLU | The 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 rate40 | 0.03 | With 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 size41 | 16 | About 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. |
| Optimiser42 | Adam (β₁ 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 λ43 | 0 (off) | Off so the first run shows the unregularised boundary. Try 0.01 to see the shape tighten. |
| Test share44 | 20% | A fifth of the points are held out, so the test accuracy is measured on points the network never trained on. |
| Noise45 | 0 | Clean data first. Noise moves each point by noise × a normal draw, so the classes overlap more. |
| Epochs per second46 | 20 | Fast enough that the boundary visibly moves, slow enough to follow each change. At most 12 epochs run in one frame. |
| Seed47 | 0 | The 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. |
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.