a small neural network
how it works
The idea in short steps and three pictures, then the watch page's first run, 3 hidden units, step by step.
Four corners, across (x) and up (y) each 0 or 1: where they agree, 0 0 and 1 1, a triangle; where they differ, a square. This pattern is called XOR. Suppose a straight line had both triangles on one side and both squares on the other. The middle, 0.5 0.5, lies halfway between the two triangles and halfway between the two squares. If both triangles are on one side of a line, so is everything between them, the middle included; the same goes for the squares. The middle cannot be on both sides, so no line works: one line, all a perceptron draws, always leaves a corner wrong. A small network adds a middle column of hidden units: the inputs feed them, and they feed the output. A hidden unit's sum is across times one weight, plus up times another, plus its bias. The squash then turns the sum into a number between 0 and 1, as its curve shows. The output does the same with the hidden units' squashed values, and over 0.5 it says square. A hidden unit's line is where its sum is 0, so its squash is exactly 0.5: over 0.5 on one side of the line, under 0.5 on the other. With one hidden unit, the output's sum is that unit's squashed value times one weight, plus a bias. As the unit's sum climbs, the output's sum only climbs, only falls or stays put. So it passes 0 at one value of the unit's sum at most, and where that sum is one number is a straight line. So the output says square on one side of one line, which the middle point rules out. Or it says square everywhere or nowhere, which gets two corners wrong: this network needs 2 at least. With two or more, the output mixes their lines, so the boundary can bend. It learns in passes. Each pass puts each corner in, works out the output, as the grid does for 0 0, and measures the loss. Then it nudges every weight against its share of the loss's slope, times the step size. In the grid, the output's bias is 0.1. Try it a little lower, at 0, and a little higher, at 0.2: the loss goes from 0.25733 to 0.25154, down 0.00579 over 0.2, a slope of about −0.029. That is the bias's share. Against it means subtract, times the step size, here 4: 0.1 − 4 × (−0.029) = 0.1 + 0.116 = 0.216, so the bias grows. Back propagation finds every share at once, backwards from the output, and gives about the same number. Each hidden unit has 4 weights: 3 in (from across, from up and its bias) and 1 out. With 2 hidden units, as in the grid, and the output's bias, 2 × 4 + 1 = 9 weights are nudged each pass.
The corners, shaded where it says square
The network, each line its weight
3 hidden units, step size 4, 150 passes: a loss of 0.072, and 4 of the 4 corners right.
With scripts on, three sliders set the hidden units, the step size and the passes. The plane, the network, the chart and this line change with them.
| unit | its weights | sum at 0 0 | squashed |
|---|---|---|---|
| hidden 1 | from across: −1, from up: −0.9, bias: 0 | −1 × 0 − 0.9 × 0 + 0 = 0 | 0.5 |
| hidden 2 | from across: 1, from up: 0.4, bias: −0.2 | 1 × 0 + 0.4 × 0 − 0.2 = −0.2 | 0.45 |
| output | from hidden 1: −0.1, from hidden 2: −0.5, bias: 0.1 | −0.1 × 0.5 − 0.5 × 0.45 + 0.1 = −0.175 | 0.456 |
step 1 of 26
3 hidden units, step size 4, 150 passes. The 13 weights start small, from -1 to 1. No one line splits the triangles from the squares.
what it remembers to know where it is
- pass
- not yet
- loss
- not yet
- corners right
- not yet
Where it says not yet, nothing is held there at that moment.
step 2 of 26
Pass 1: feed each corner forward. Each hidden unit adds its inputs, each times its weight, and its bias, and squashes the sum into 0 to 1. The output does the same with the hidden units. 2 of the 4 corners land on their right side of 0.5.
what it remembers to know where it is
- pass
- 1
- loss
- 0.295
- corners right
- 2
step 3 of 26
The loss is the average of each output's squared miss from its answer, 0 for a triangle and 1 for a square: 0.295.
what it remembers to know where it is
- pass
- 1
- loss
- 0.295
- corners right
- 2
step 4 of 26
Nudge each of the 13 weights and biases against its share of the loss, times the step size, 4. The shares are found backwards, from the output to the hidden units.
what it remembers to know where it is
- pass
- 1
- loss
- 0.254
- corners right
- 2
step 12 of 26
Pass 37: the loss is 0.249, and 3 of the 4 corners are right.
what it remembers to know where it is
- pass
- 37
- loss
- 0.249
- corners right
- 3
step 21 of 26
Pass 117: every corner is on its right side for the first time, with a loss of 0.194. The hidden units bend the boundary, which one line never could.
what it remembers to know where it is
- pass
- 117
- loss
- 0.194
- corners right
- 4
step 26 of 26
150 passes, a loss of 0.072. Every corner has been right since pass 117.
what it remembers to know where it is
- pass
- 150
- loss
- 0.072
- corners right
- 4
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- start with small weightsPython lines 12 and 13
- feed each corner forward, through the hidden units to the outputPython lines 18, 19, 20, 21, 33 and 34
- measure the loss, how far the outputs are from the answersPython lines 23 and 24
- nudge every weight against its share of the loss, times the step sizePython lines 31, 32, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45 and 46
- repeat for every passPython lines 30, 47 and 48
- shade the plane where the output says squarePython lines 26 and 27
the same in Python
The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.
from math import exp, floor
def neural_network(units, bias, rate, passes):
"""A small network learning XOR on the four corners, by gradient descent.
Each unit is a tuple (wx, wy, b, v): its weights from across and up,
its bias, and its weight to the output; bias is the output's bias.
Answers with the first pass every corner is right, 0 for none, and
the loss after the last pass, to the thousandth.
"""
corners = [(0, 0, 0), (0, 1, 1), (1, 0, 1), (1, 1, 0)] # across, up, answer
units = [list(u) for u in units]
def squash(z):
return 1 / (1 + exp(-z)) # any sum to between 0 and 1
def forward(x, y):
h = [squash(wx * x + wy * y + b) for wx, wy, b, v in units]
out = squash(sum(hj * u[3] for hj, u in zip(h, units)) + bias)
return h, out
def loss():
return sum((forward(x, y)[1] - a) ** 2 for x, y, a in corners) / 4
def all_right():
return all((forward(x, y)[1] > 0.5) == (a == 1) for x, y, a in corners)
first = 0
for p in range(1, passes + 1):
shares = [[0, 0, 0, 0] for _ in units] # each weight's share
bias_share = 0
for x, y, a in corners: # feed each corner forward
h, out = forward(x, y)
d_out = 2 * (out - a) * out * (1 - out) / 4
for j, u in enumerate(units): # back to each hidden unit
d_h = d_out * u[3] * h[j] * (1 - h[j])
shares[j][0] += d_h * x
shares[j][1] += d_h * y
shares[j][2] += d_h
shares[j][3] += d_out * h[j]
bias_share += d_out
for u, s in zip(units, shares): # nudge every weight
for k in range(4):
u[k] -= rate * s[k]
bias -= rate * bias_share
if first == 0 and all_right():
first = p # the first pass every corner is right
return [first, floor(loss() * 1000 + 0.5) / 1000]
how it scales
How the weights nudged grow, from ten passes to two thousand, with the fewest and the most hidden units.
Each step across or up is ten times the one before. From 10 to 100 passes, 4 hidden units nudge 170, then 1,700 weights: ten times across, ten times up. 170 ÷ 10 and 1,700 ÷ 100 are both 17, the weights one pass nudges. So both lines climb one step up for each step across. A slope of 1 means the count grows as , as section 4 works out.
weights nudged, ten times more at each mark up
, n, ten times more at each mark to the right
- 4 hidden units, the most the watch page allows, 17 weights a passsolid where measured by running it; dashed where its formula carries it on to ten millionslope 1: ten times n, 10 times the work
- 2 hidden units, the fewest this network needs, 9 weights a passsolid where measured by running it; dashed where its formula carries it on to ten million
| weights nudged | time | |
|---|---|---|
| 1,000 | 17,000 | about 17 microseconds |
| 100,000 | 1,700,000 | about 1.7 milliseconds |
| 10,000,000 | 170,000,000 | about 170 milliseconds |
The weights nudged are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.
make these counts yourself
Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.
"""Count a small network's nudges yourself, as the plot on this page does.
Run it with Python 3.12 or later. For each n it trains the network for n
passes twice, from the watch page's own starting weights: with 2 hidden
units, the fewest this network needs, and with 4, the most the box takes.
It prints how many weights each run nudges, up to n = 2000, in a few
seconds. The counts are the same on any computer, and for any starting
weights or step size: each pass nudges every weight once.
"""
from math import exp, floor
def neural_network(units, bias, rate, passes):
"""A small network learning XOR on the four corners, by gradient descent.
Each unit is a tuple (wx, wy, b, v): its weights from across and up,
its bias, and its weight to the output; bias is the output's bias.
Answers with the first pass every corner is right, 0 for none, and
the loss after the last pass, to the thousandth.
"""
corners = [(0, 0, 0), (0, 1, 1), (1, 0, 1), (1, 1, 0)] # across, up, answer
units = [list(u) for u in units]
def squash(z):
return 1 / (1 + exp(-z)) # any sum to between 0 and 1
def forward(x, y):
h = [squash(wx * x + wy * y + b) for wx, wy, b, v in units]
out = squash(sum(hj * u[3] for hj, u in zip(h, units)) + bias)
return h, out
def loss():
return sum((forward(x, y)[1] - a) ** 2 for x, y, a in corners) / 4
def all_right():
return all((forward(x, y)[1] > 0.5) == (a == 1) for x, y, a in corners)
first = 0
for p in range(1, passes + 1):
shares = [[0, 0, 0, 0] for _ in units] # each weight's share
bias_share = 0
for x, y, a in corners: # feed each corner forward
h, out = forward(x, y)
d_out = 2 * (out - a) * out * (1 - out) / 4
for j, u in enumerate(units): # back to each hidden unit
d_h = d_out * u[3] * h[j] * (1 - h[j])
shares[j][0] += d_h * x
shares[j][1] += d_h * y
shares[j][2] += d_h
shares[j][3] += d_out * h[j]
bias_share += d_out
for u, s in zip(units, shares): # nudge every weight
for k in range(4):
u[k] -= rate * s[k]
bias -= rate * bias_share
if first == 0 and all_right():
first = p # the first pass every corner is right
return [first, floor(loss() * 1000 + 0.5) / 1000]
def count(units, bias, rate, passes):
"""The same method, counting every weight and bias nudged."""
corners = [(0, 0, 0), (0, 1, 1), (1, 0, 1), (1, 1, 0)]
units = [list(u) for u in units]
nudged = 0
def squash(z):
return 1 / (1 + exp(-z))
def forward(x, y):
h = [squash(wx * x + wy * y + b) for wx, wy, b, v in units]
return h, squash(sum(hj * u[3] for hj, u in zip(h, units)) + bias)
for _ in range(passes):
shares = [[0, 0, 0, 0] for _ in units]
bias_share = 0
for x, y, a in corners:
h, out = forward(x, y)
d_out = 2 * (out - a) * out * (1 - out) / 4
for j, u in enumerate(units):
d_h = d_out * u[3] * h[j] * (1 - h[j])
shares[j][0] += d_h * x
shares[j][1] += d_h * y
shares[j][2] += d_h
shares[j][3] += d_out * h[j]
bias_share += d_out
for u, s in zip(units, shares):
for k in range(4):
u[k] -= rate * s[k]
nudged += 1
bias -= rate * bias_share
nudged += 1 # and the output's bias
return nudged
def cheapest(n):
"""2 hidden units, the watch page's starting weights, step size 4, n passes."""
return [(-1, -0.9, 0, -0.1), (1, 0.4, -0.2, -0.5)], 0.1, 4, n
def dearest(n):
"""4 hidden units, the watch page's starting weights, step size 4, n passes."""
units = [(-0.6, 0.7, -0.8, -0.5), (-0.8, 0.7, 0.3, 0.9), (0.5, 0.4, 0.4, -0.4), (-0.5, 0.9, 0.2, 0.5)]
return units, 0.3, 4, n
if __name__ == "__main__":
print(f"{'n':>5} {'2 hidden units':>15} {'4 hidden units':>15}")
for n in (10, 20, 50, 100, 200, 500, 1000, 2000):
print(f"{n:>5} {count(*cheapest(n)):>15} {count(*dearest(n)):>15}")
best, worst and average
Best is 2 hidden units, the fewest this network needs: 9 weights a pass. Worst is 4, the most the watch page allows: 17 a pass. The step size and the starting weights change what the network learns, never how many weights a pass nudges. So no average is worked out: every run of passes with the same number of hidden units costs the same.
A case is one kind of input, here how many hidden units the network has. A bound says how fast that case's cost grows as more passes are made.
Each pass nudges every weight once, 9 with 2 hidden units and 17 with 4: a fixed number times the passes, so all three bounds grow as .
| best2 hidden units, the fewest this network needs, 9 weights a pass | worst4 hidden units, the most the watch page allows, 17 weights a pass | |
|---|---|---|
| weights nudged | ||
| corners fed through | ||
| how the weights nudged grow in each case | ||
| tight, | ||
| ceiling, | ||
| floor, | ||
extra memory: the weights, 4 for each hidden unit and 1 more, and each one's share while a pass is worked out
Extra memory is the room it needs on top of the input itself, while it runs.
where the formula comes from
The counts above, each worked out in small steps naming the line it comes from.
the move: count one pass
the line:weights how many into the hidden units, 3 each 12 from the hidden units to the output 4 the output's bias 1 a pass 17 The 17 lines of the network with 4 hidden units, as the watch page draws them. Each is nudged once a pass. why it is allowed: is the weights nudged. Each of the 4 hidden units has 3 weights in, from across, from up and its bias, and 1 out to the output. The output has its bias. A pass nudges each once, and there are passes.
the move: work out the bracket
the line:why it is allowed: By line 1, 3 × 4 = 12, and 12 + 4 + 1 = 17. For 10 passes, 170.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 2, is exactly , so never above it.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 3, is at most 17 times , a fixed number times , which is what says.
guess it, thenthe move: a floor
the line:why it is allowed: By line 2 again, never below it either.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 5, never drops below 17 times , which is what says.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 4 and 6 bound by the same growth, .
guess it, then
try it with a small : at , line 1 gives , which you can work out by hand
the move: count one pass
the line:why it is allowed: is the weights nudged. Each of the 2 hidden units has 3 weights in and 1 out, and the output has its bias, as in the ladder above.
the move: work out the bracket
the line:why it is allowed: By line 1, 3 × 2 = 6, and 6 + 2 + 1 = 9. For 10 passes, 90.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 2, is exactly , so never above it.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 3, is at most 9 times , a fixed number times , which is what says.
guess it, thenthe move: a floor
the line:why it is allowed: By line 2, is exactly , so never below it.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 5, never drops below 9 times , which is what says.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 4 and 6 bound by the same growth, .
guess it, then
try it with a small : at , line 1 gives , which you can work out by hand
the move: count one pass
the line:passes corners fed 1 4 2 8 5 20 10 40 Each pass feeds the same 4 corners, whatever the hidden units. Ten passes feed 40, the last row of the count table below. why it is allowed: is the corners fed. Each pass feeds each of the 4 corners forward once, and there are passes, with any number of hidden units.
the move: a ceiling
the line:why it is allowed: By line 1, is exactly , so never above it.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 2, is at most 4 times , a fixed number times , which is what says.
guess it, thenthe move: a floor
the line:why it is allowed: By line 1, is exactly , so never below it.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 4, never drops below 4 times , which is what says.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 3 and 5 bound by the same growth, .
guess it, then
try it with a small : at , line 1 gives , which you can work out by hand
count it yourself
2; 4; 10 means 2 hidden units, step size 4 and 10 passes. Count every step. The table's counts are running totals: each row is the one above plus the new work, 4 more corners fed and 9 more weights nudged each pass. The run draws passes 1 to 5, then every tenth. So from the row for pass 5 to the row for pass 10, the weights nudged jump by 5 × 9 = 45. Then check the nudges against the formula.
| step | what happens | corners fed through | weights nudged |
|---|---|---|---|
| 1 | 2 hidden units, step size 4, 10 passes. The 9 weights start small, from -1 to 1. No one line splits the triangles from the squares. | 0 | 0 |
| 2 | Pass 1: feed each corner forward. Each hidden unit adds its inputs, each times its weight, and its bias, and squashes the sum into 0 to 1. The output does the same with the hidden units. 2 of the 4 corners land on their right side of 0.5. | 4 | 0 |
| 3 | The loss is the average of each output's squared miss from its answer, 0 for a triangle and 1 for a square: 0.254. | 4 | 0 |
| 4 | Nudge each of the 9 weights and biases against its share of the loss, times the step size, 4. The shares are found backwards, from the output to the hidden units. | 4 | 9 |
| 5 | Pass 2: the loss is 0.25, and 2 of the 4 corners are right. | 8 | 18 |
| 6 | Pass 3: the loss is 0.25, and 2 of the 4 corners are right. | 12 | 27 |
| 7 | Pass 4: the loss is 0.25, and 2 of the 4 corners are right. | 16 | 36 |
| 8 | Pass 5: the loss is 0.25, and 2 of the 4 corners are right. | 20 | 45 |
| 9 | Pass 10: the loss is 0.249, and 3 of the 4 corners are right. | 40 | 90 |
| 10 | 10 passes, a loss of 0.249. Only 3 of the 4 corners are right: these settings did not learn XOR in time. | 40 | 90 |
In all, 90 weights nudged. The formula from section 4, , gives at : the same.
where you meet it
Hidden units are what let a network learn shapes one line cannot split, and back propagation is how they are trained.
Perceptrons, by Marvin Minsky and Seymour Papert
Their 1969 book proved limits on what a perceptron can do. One: it cannot tell whether an odd or an even number of its inputs are 1. XOR is the smallest such case. The corners 0 0, 0 1, 1 0 and 1 1 hold 0, 1, 1 and 2 ones, and the odd ones are the squares.
source: Minsky and Papert, Perceptrons, MIT Press, 1969
Rumelhart, Hinton and Williams
In 1986 David Rumelhart, Geoffrey Hinton and Ronald Williams showed back propagation training hidden units. XOR, learnt with hidden units between the inputs and the output, was among their first examples.
source: Rumelhart, Hinton and Williams, Learning internal representations by error propagation, in Parallel Distributed Processing, volume 1, MIT Press, 1986
scikit-learn, a Python library for machine learning
Its MLPClassifier tool, MLP for multilayer perceptron, is a network with hidden units, trained by back propagation, as on this page. Its setting hidden_layer_sizes says how many hidden units each middle column has, and it can have more than one column. Its hidden units use this page's squash, which it calls logistic, only if you ask for it. With two kinds of points, its output always uses it.
source: scikit-learn's documentation, the user guide's section on neural network models and the MLPClassifier reference
| hidden units | step size 1 | step size 4 | step size 8 |
|---|---|---|---|
| 2 | 3 of 4 | 4 of 4 | 4 of 4 |
| 3 | 3 of 4 | 4 of 4 | 4 of 4 |
| 4 | 2 of 4 | 4 of 4 | 4 of 4 |
what is used instead
When one straight line splits the points, the perceptron, on this site, needs no hidden units and checks each point once a pass. A decision tree, also here, cuts the plane across and up and needs no step size at all.
how it compares
The network beside the perceptron on the same four corners. One straight line against lines joined.
| method | passes | corners right | counted |
|---|---|---|---|
| the perceptron | 6 | 2 of 4 | 23 nudges, each moving 3 numbers (the weights for across and up, and the bias): 69 in all |
| the network, 2 hidden units | 200 | 4 of 4 | 1,800 weights nudged |