Selected work · 13 / 13Machine learning · JavaScript

NeuralFit: an Interactive Neural‑Network Simulator on the Forward Pass, Backpropagation and Learning

The second simulator of this website, for readers who know some machine learning. A small neural network learns to separate two classes of points, and the page shows every number of it: follow one training point through the forward pass, the error, the backward pass and the update, or press Train and watch the border take shape. Seventeen weights, seven steps, written from scratch with no library and no server behind it.

The network learns the circle from random weights, live. Click to restart.
7steps, from the input to the update of every weight
17weights, every one of them on screen
26automated tests: every gradient checked against the measured slope
4problems learned from the same starting rule, in 1 to 156 epochs
0libraries, servers or build steps
01 / The idea

A network you can read.

Backpropagation is four lines of calculus, and most people who have studied it could not compute one step of it by hand. A library hides it behind one call; a textbook shows the formulas with letters. NeuralFit shows it with the numbers: a network small enough that every weight fits on the screen, and one training point followed from the input to the update, with each value computed in front of you.

The same page then runs that step thousands of times. Press Train and the background of the board, which is the answer of the network at every place, bends around the points while the weights change in the matrices. Nothing is simplified: the weighted sums, the activations, the error signals and the update are the ones a library computes, and the tests check every gradient against the slope measured by moving one weight.

The first screen of NeuralFit after training on the circle: on the left the network, two inputs, four hidden units and one output, with the output of each unit inside its circle and a line for each weight; on the right the board, where an orange region closes around the orange squares in a blue background, and the Train button; below, the matrix W of the hidden layer, the vector w of the output unit, and the four numbers with the loss curve
The whole simulator on one screen: the network, the board with its answer, the weights, and the loss on the training points and on new points.
02 / The network

Two inputs, four hidden units, one answer.

  • Units. Two inputs, the coordinates of a point; four hidden units; one output unit. Units are numbered across the network: 1 and 2 are the inputs, 3 to 6 the hidden units, 7 the output. A line is thicker when its weight is larger and dashed when the weight is negative.
  • Weights. The weight wtu arrives at unit t and comes from unit u; u = 0 is the bias, whose input is always 1. The hidden layer has a matrix W with one row for each unit that receives and one column for each unit that sends: 4 × 3. The output is a single unit, so its weights are one row of five numbers, and the page calls them what they are: a vector, w. Seventeen weights in all.
  • What a unit computes. Its net, the sum of what it receives times its weights, and its output, the net passed through the activation: tanh for the hidden units (a sigmoid can be chosen), always a sigmoid for the output, so the answer is a number between 0 and 1. Above 0.5 the network says class 1, below it says class 0.
  • The error. On one point it is half the square of the distance between the target and the answer, E = ½(d − o)²; the loss the page plots is its mean over the points.
engine/network.js · forward()
export function forward(network, x) {  const o = [[...x]];  const net = [null];  for (let l = 0; l < network.W.length; l++) {    const { f } = activationOf(network, l);    const input = o[l];    const sums = network.W[l].map((row) => {      let sum = row[0]; // the bias: its input is 1      for (let u = 0; u < input.length; u++) sum += row[u + 1] * input[u];      return sum;    });    net.push(sums);    o.push(sums.map(f));  }  return { o, net };}
The forward pass: for each layer, every row of the matrix times what the layer receives, then the activation. The matrix has one row per receiving unit exactly so that this loop is a matrix times a vector.
03 / Seven steps

One point, from the input to the update.

A click on a point of the board makes it the point to follow, and the bar above the network lists its seven steps. Each step shows only what has been computed up to there: the outputs appear in the circles, the lines of the layer at work carry moving dashes, orange and toward the output in the forward pass, blue and toward the input in the backward pass, and the same numbers fill the matrices.

StepNameWhat is computed
1Inputthe two coordinates of the point enter; its class gives the target, 0 or 1
2Hiddenthe net and the output of each hidden unit: the matrix W times the inputs
3Outputthe net and the output of unit 7: the answer of the network
4Errorthe error on the point, and the error signal δ of the output unit
5Backthe δ of each hidden unit, from the δ of the output and the weight between them
6Stepsthe correction of each weight: η · the δ of the unit it arrives at · what it carried
7Updateevery weight moves by its step; the error on the point is measured again

Under the first screen, each step has its explanation in words on the left and the computation with the numbers of that point on the right. A click on any unit or weight, in the drawing or in the matrices, shows how that number was made, and lights the weights that arrive at the unit and the ones that leave it. The steps can be walked in both directions: going back from the update takes it back, so the weights before and after can be compared as many times as needed.

view/explain.js · stepsFor()
export function stepsFor(sizes) {  const last = sizes.length - 1;  const single = last === 2; // one hidden layer  const steps = [{ kind: 'input', short: 'Input', tone: '' }];  for (let layer = 1; layer <= last; layer++) {    steps.push({ kind: 'forward', layer, short: layer === last ? 'Output' : single ? 'Hidden' : `Hidden ${layer}`, tone: 'f' });  }  steps.push({ kind: 'error', short: 'Error', tone: '' });  for (let layer = last - 1; layer >= 1; layer--) {    steps.push({ kind: 'backward', layer, short: single ? 'Back' : `Back to ${layer}`, tone: 'b' });  }  steps.push({ kind: 'steps', short: 'Steps', tone: 'b' }, { kind: 'update', short: 'Update', tone: '' });  return steps;}
The steps are not written by hand: they are built from the sizes of the layers, so the same rule gives seven steps for one hidden layer and nine for two.
04 / The backward pass

Every unit gets its share of the error.

The quantity that travels back is the error signal of a unit, called delta: how much the error would fall if the net of that unit rose a little. For the output unit it is the distance from the target times the slope of the sigmoid. A hidden unit has no target, so its delta comes from the unit it feeds: the delta of the output, times the weight that joins them, times the slope of its own activation. With the deltas known, the step of a weight is a product of three numbers: the learning rate, the delta of the unit the weight arrives at, and the output of the unit it comes from.

engine/network.js · backward()
export function backward(network, pass, target) {  const last = network.W.length;  const delta = new Array(last + 1).fill(null);  const back = new Array(last + 1).fill(null);  const out = pass.o[last];  const error = out.map((ok, k) => target[k] - ok);  const outSlope = activationOf(network, last - 1).slope;  delta[last] = out.map((ok, k) => error[k] * outSlope(ok));  for (let l = last - 1; l >= 1; l--) {    const { slope } = activationOf(network, l - 1);    back[l] = pass.o[l].map((_, j) => {      let sum = 0;      for (let k = 0; k < delta[l + 1].length; k++) sum += delta[l + 1][k] * network.W[l][k][j + 1];      return sum;    });    delta[l] = back[l].map((b, j) => b * slope(pass.o[l][j]));  }  const grad = network.W.map((rows, l) => rows.map((row, t) => row.map((_, u) => delta[l + 1][t] * (u === 0 ? 1 : pass.o[l][u - 1]))));  const loss = 0.5 * error.reduce((sum, e) => sum + e * e, 0);  return { delta, back, grad, error, loss };}
The backward pass in twenty lines: the deltas from the output to the first hidden layer, then the step of every weight. One delta per unit serves all the weights that arrive at it, which is why the cost grows with the number of weights and not with its square.

On the page as it opens, the point to follow is (−0.73, −0.71), of class 0. The untrained network answers 0.67, on the wrong side of 0.5, so the delta of the output is negative: (0 − 0.67) · 0.67 · (1 − 0.67) = −0.148. Hidden unit 3 sent 0.27 through a weight of 0.52, and receives −0.148 · 0.52 · (1 − 0.27²) = −0.072. The weight between them moves by 0.5 · (−0.148) · 0.27 = −0.020. These are the numbers in the figure, and the page writes each of these lines for whatever point and unit you choose.

The backward step of NeuralFit on the page as it opens: the bar of the seven steps with Back selected, the network with blue dashed lines from the output to the four hidden units, the delta of each unit written beside it, minus 0.148 for the output and minus 0.072, 0.039, minus 0.03 and 0.063 for the hidden units, and below the matrix W and the vector w with the columns net, o and delta filled in
Step 5, Back: the delta of the output, −0.148, comes back along the four blue lines, and each hidden unit gets its own. The same numbers are in the δ column of the matrix.
Step 6 of NeuralFit: under every weight of the matrix W and of the vector w its step in small blue digits, and below the explanation Every weight gets its step, with the worked line of the weight from unit 3 to unit 7: 0.50 times minus 0.148 times 0.27 equals minus 0.020
Step 6, Steps: every weight shows its correction under its value, and the box below works one of them out with its numbers.
05 / Four problems

The same network, four borders.

Each problem is a rule that gives a class to every point of the square, and 64 training points drawn from it with a seeded generator, so the page opens on the same points and the same starting weights at every visit. The four rules ask more and more of the hidden layer: a straight line, two straight lines, a border that changes direction, and a border that closes on itself.

ProblemThe border the network must drawEpochs to 100% on trainingNew points right after 400 epochs
Two groupsone straight line: a single unit would be enough199.7%
Stripea vertical band: two borders, one on each side14100%
XORopposite corners share a class: no straight line can do it11896.7%
Circleone class inside, the other around: the border closes on itself15693.7%

The numbers are measured from the page's own starting weights, with tanh hidden units and a learning rate of 0.5. With four hidden units the circle does not come out round: the network closes it with three or four almost straight sides, which is enough to put all 64 training points on the right side and 94% of 300 new ones. One more hidden unit, from the settings, rounds it further.

The four boards of NeuralFit after 400 epochs each: Two groups split by a diagonal line, XOR with two orange corners joined by a curved band, Circle with an orange region with three rounded sides around the squares, Stripe with a vertical orange band; in every board blue circles sit on blue and orange squares on orange
Two groups, XOR, Circle and Stripe after 400 epochs each: the background is the answer of the network, and every training point is on its own color.
06 / Training and new points

What it learned, and what it only memorized.

Training repeats the seven steps on every training point, in a new random order at each pass: one pass is an epoch. The update is made after every point, the on-line form of gradient descent. One epoch on the 64 points takes 0.04 milliseconds, so the page runs a few of them for every frame it draws, and the speed is a setting.

The network learns from the 64 training points only. Next to their loss, the page plots the loss on 300 new points drawn from the same rule, which the network never sees while it learns. The two curves fall together at first, and then part: on XOR, the network puts every training point on the right side after 118 epochs, when it is right on 86% of the new points, and reaches 97% of them only later, as the border straightens between the points. The gap between the two lines is the same question OverFit asks of a decision tree: does it generalize?

  • Learning rate. From 0.05 to 2. A step too long shows at once: at the Update step the page measures the error on the point again and says when it did not fall.
  • Hidden units. From one to five. With one unit the border is a single line, and XOR and the circle cannot be learned: the loss stops falling and the board says why.
  • Activation. Tanh or sigmoid for the hidden units. From the same starting rule the sigmoid needs 532 epochs on XOR where tanh needs 118: its slope is at most 0.25, so every error signal that comes back is smaller.
  • Reset. Another set of starting weights from the next seed: the same problem is learned along a different path.
07 / One screen

Nothing to scroll to see it work.

A visitor decides in a few seconds whether a page is worth the time, so everything that moves is on the first screen: the network on the left, large; on the right the problem, the board and the Train button; below them the weights and the loss curve. The explanation of each step, the settings and the guide to reading the page come after, for those who stay. The first version had two hidden layers and three matrices; one hidden layer shows the same rule with fewer numbers, and leaves room to read them.

The page is plain HTML, SVG for the network and canvas for the board and the curve. It follows the light and dark theme of the site, works with the keyboard (Space or the arrows for the steps, T to train) and on a phone, where the blocks stack and the drawing of the network scrolls sideways at a readable size.

NeuralFit on a phone in the dark theme, after training on the circle: the end of the network panel, then the problem buttons, the board with an orange region around the squares, the Train, plus one epoch and Reset buttons, and the start of the matrix W
On a phone, in the dark theme: the board after training on the circle.
NeuralFit on a phone in the light theme at the Back step: the explanation Backward pass: the hidden layer, and under it the delta of unit 3 worked out with its numbers, line by line
The explanation of a step on a phone: the words, then the computation with the numbers.
08 / Tests and results

26 tests, and every gradient measured.

The tests run in the browser, on the very modules of the simulator. The arithmetic is checked three ways: against a network of five units computed by hand, to four decimals; by moving each weight a little and measuring how the error changes, for every weight and both activations; and by learning, since each of the four problems must be learned from the page's own starting weights.

Test fileTestsWhat they check
engine14the forward and backward pass by hand, the shape of the matrices, seeds, every gradient against the measured slope, the update, the seven steps, the names of W and w, the numbers as the page writes them
learning12the points follow their rule, the same start at every visit, training and new points never shared, the four problems learned with tanh and with sigmoid, XOR not learned without a hidden layer

The page on the site is 15 files and 96 KB, fonts excluded: 1,524 lines of JavaScript in 13 modules, with the network and its learning rule in one file of 151 lines that knows nothing about the screen. The engine takes any number of layers, and the steps and the names follow the sizes; the page uses one hidden layer because it reads better.

Press Train. Watch it learn.

Seven steps, seventeen weights and a 11‑page report, and every number on the page can be checked by hand.

Next case study · 01 / 13High-Performance Mehrotra Lasso Solver