Lesson 7 of 8 · A First Network
Training a Network in Your Browser
Train a small neural network from scratch in plain Python, right in your browser. It learns XOR, the classic problem that a single neuron cannot solve.
- 6 min read
- Beginner
- Reviewed
- Why a single neuron cannot learn XOR
- How a hidden layer solves it
- How the forward pass, loss, backpropagation and update fit together in real code
- How to read the output of a training run
The XOR problem
XOR ("exclusive or") outputs 1 when its two inputs are different, and 0 when they are the same:
| x1 | x2 | XOR |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
Plot the four points and the 1s sit on one diagonal, the 0s on the other:
x2
1 | 1 0
|
0 | 0 1
+------------------ x1
0 1Try to draw one straight line with both 1s on one side and both 0s on the other. It cannot be done.
A single neuron can only draw one straight line, so it cannot learn XOR. This is what Minsky and Papert pointed out in 1969. The fix is a hidden layer: its neurons each draw a line, and the output neuron combines them.
The network
The network you will train is the smallest one that can learn XOR:
- an input layer with 2 values, x1 and x2
- a hidden layer with 2 neurons, each using a sigmoid
- an output layer with 1 neuron, also using a sigmoid, giving a number between 0 and 1
That is 2 × 2 + 2 = 6 parameters in the hidden layer and 2 + 1 = 3 in the output layer: 9 parameters in total.
Train it
Press Run. The code uses only Python's built-in math and random modules, and trains the network for 5,000 rounds over the four examples.
import math
import random
random.seed(42)
def sigmoid(x):
return 1.0 / (1.0 + math.exp(-max(-500.0, min(500.0, x))))
def sigmoid_slope(output):
# the slope of the sigmoid, written in terms of its output
return output * (1.0 - output)
inputs = [[0.0, 0.0], [0.0, 1.0], [1.0, 0.0], [1.0, 1.0]]
targets = [0.0, 1.0, 1.0, 0.0]
# small random starting weights and biases
w_hidden = [[random.uniform(-1, 1), random.uniform(-1, 1)] for _ in range(2)]
b_hidden = [random.uniform(-1, 1), random.uniform(-1, 1)]
w_output = [random.uniform(-1, 1), random.uniform(-1, 1)]
b_output = random.uniform(-1, 1)
learning_rate = 0.5
for epoch in range(1, 5001):
total_loss = 0.0
for x, target in zip(inputs, targets):
# 1. forward pass
h = [sigmoid(x[0] * w_hidden[j][0] + x[1] * w_hidden[j][1] + b_hidden[j]) for j in range(2)]
y = sigmoid(h[0] * w_output[0] + h[1] * w_output[1] + b_output)
# 2. loss (squared error)
error = target - y
total_loss += error ** 2
# 3. backpropagation: how much each neuron contributed to the error
d_output = error * sigmoid_slope(y)
d_hidden = [d_output * w_output[j] * sigmoid_slope(h[j]) for j in range(2)]
# 4. update every weight and bias a little
for j in range(2):
w_output[j] += learning_rate * d_output * h[j]
w_hidden[j][0] += learning_rate * d_hidden[j] * x[0]
w_hidden[j][1] += learning_rate * d_hidden[j] * x[1]
b_hidden[j] += learning_rate * d_hidden[j]
b_output += learning_rate * d_output
if epoch % 1000 == 0:
print(f"epoch {epoch}: mean squared error {total_loss / 4:.5f}")
print()
for x, target in zip(inputs, targets):
h = [sigmoid(x[0] * w_hidden[j][0] + x[1] * w_hidden[j][1] + b_hidden[j]) for j in range(2)]
y = sigmoid(h[0] * w_output[0] + h[1] * w_output[1] + b_output)
print(f"input {x} -> prediction {y:.4f}, rounded {round(y)}, target {target:.0f}")The error falls from 0.019 after 1,000 rounds to 0.0007 after 5,000. At the end the network predicts about 0.02 for [0, 0], 0.975 for [0, 1] and [1, 0], and 0.03 for [1, 1]. Rounded, all four answers are correct.
What the code is doing
The loop is exactly the training loop from the previous lesson:
- Forward pass: compute the two hidden outputs, then the final prediction.
- Loss: square the error for each example and add them up.
- Backpropagation:
d_outputmeasures how much the output neuron should change. Each hidden neuron gets a share of it, in proportion to the weight connecting it to the output. The slope of the sigmoid,output × (1 − output), appears at each step: that is the chain rule at work. - Update: nudge every weight and bias by learning rate × its share of the blame × its input.
Here the updates use += and the error is written as target − prediction, so the direction is already downhill. It is the same rule as w − learning rate × gradient.
Common mistakes
Solve XOR by hand-setting the weights of a tiny network. Hidden neuron 1 is an OR: it fires when x1 + x2 − 0.5 is above 0. Hidden neuron 2 is an AND: it fires when x1 + x2 − 1.5 is above 0. The output neuron fires when OR is on and AND is off: when h1 − h2 − 0.5 is above 0.
def step(z):
return 1 if z > 0 else 0
def xor_net(x1, x2):
# Build XOR from three step neurons (see the task description).
return 0
for x1, x2 in [(0, 0), (0, 1), (1, 0), (1, 1)]:
print(x1, x2, "->", xor_net(x1, x2))
# Output must be exactly:
# 0 0 -> 0
# 0 1 -> 1
# 1 0 -> 1
# 1 1 -> 0
Why can a single neuron not learn XOR?
Summary
- XOR is not linearly separable, so a single neuron cannot learn it.
- A hidden layer of two neurons is enough: each draws a line, and the output combines them.
- Training repeats forward pass, loss, backpropagation and update thousands of times.
- The same loop, scaled up, trains the largest networks in use today.
Next: the frameworks that compute gradients for you, and how they do it.
Finished reading? Tick it off to track your progress.