Hands-on: implement a perceptron
Why This Matters
Training a neural network is often described as magic. It is not: it is a loop that nudges numbers. A perceptron is the smallest network there is, and in 25 lines of Python you can watch it learn, epoch by epoch, until the error is zero. And you can watch it fail on a problem it cannot learn, which is the first lesson in why model structure matters.
What you will learn
- How a perceptron calculates its output from weights, a bias and a step function
- How the perceptron learning rule adjusts weights and bias after each error
- Why a perceptron learns AND and OR, but never XOR
Syllabus: HO-3.4.2 (experience the implementation of a perceptron). This is an H1 objective: you follow and run a demonstration; the exam does not ask you to write one.
The perceptron
A perceptron has two inputs, a weight per input, and a bias. It calculates the weighted sum plus the bias and outputs 1 if the sum is above 0, otherwise 0 (a step activation function).
It learns from examples with the perceptron learning rule. For each example:
- error = target − output (so +1, 0 or −1)
- if the error is not 0: every weight += learning rate × error × its input, and bias += learning rate × error
If the output was too low (error +1), the weights of the active inputs and the bias go up; if too high (−1), they go down. Inputs that were 0 do not change their weight: they did not contribute to the mistake.
Hands-on
The logical AND is 1 only if both inputs are 1. Create module-4/test_perceptron.py:
"""Lesson "Hands-on: implement a perceptron": watch a perceptron learn a logical function."""
import pytest
AND = [((0, 0), 0), ((0, 1), 0), ((1, 0), 0), ((1, 1), 1)]
OR = [((0, 0), 0), ((0, 1), 1), ((1, 0), 1), ((1, 1), 1)]
XOR = [((0, 0), 0), ((0, 1), 1), ((1, 0), 1), ((1, 1), 0)]
def predict(weights, bias, inputs):
"""Weighted sum plus bias, then a step activation function: 1 if the sum is above 0."""
total = sum(w * x for w, x in zip(weights, inputs)) + bias
return 1 if total > 0 else 0
def train(examples, learning_rate=0.1, max_epochs=20, show=False):
"""The perceptron learning rule. Returns weights, bias and the number of epochs it took (None if it never learned)."""
weights, bias = [0.0, 0.0], 0.0
for epoch in range(1, max_epochs + 1):
errors = 0
for inputs, target in examples:
error = target - predict(weights, bias, inputs) # +1, 0 or -1
if error:
errors += 1
weights = [w + learning_rate * error * x for w, x in zip(weights, inputs)]
bias += learning_rate * error
if show:
print(f"\n epoch {epoch}: weights {weights[0]:+.1f} {weights[1]:+.1f} bias {bias:+.1f} errors {errors}", end="")
if errors == 0:
return weights, bias, epoch
return weights, bias, None
The weights start at 0 instead of small random values, so that your run gives exactly the same numbers as this lesson.
The tests:
def test_learns_and():
weights, bias, epochs = train(AND, show=True)
assert epochs is not None
assert all(predict(weights, bias, x) == y for x, y in AND)
def test_learns_or():
weights, bias, epochs = train(OR)
assert epochs is not None
assert all(predict(weights, bias, x) == y for x, y in OR)
def test_cannot_learn_xor():
# No straight line separates the 1s from the 0s of XOR, so a single perceptron never gets it right.
_, _, epochs = train(XOR, max_epochs=1000)
assert epochs is None
@pytest.mark.parametrize("learning_rate", [0.01, 0.1, 1.0])
def test_and_is_learned_with_any_learning_rate(learning_rate):
assert train(AND, learning_rate=learning_rate)[2] is not None
Run it
pytest module-4/test_perceptron.py -v -s
module-4/test_perceptron.py::test_learns_and
epoch 1: weights +0.1 +0.1 bias +0.1 errors 1
epoch 2: weights +0.2 +0.1 bias +0.0 errors 3
epoch 3: weights +0.2 +0.1 bias -0.1 errors 3
epoch 4: weights +0.2 +0.2 bias -0.1 errors 2
epoch 5: weights +0.2 +0.1 bias -0.2 errors 1
epoch 6: weights +0.2 +0.1 bias -0.2 errors 0
PASSED
module-4/test_perceptron.py::test_learns_or PASSED
module-4/test_perceptron.py::test_cannot_learn_xor PASSED
module-4/test_perceptron.py::test_and_is_learned_with_any_learning_rate[0.01] PASSED
module-4/test_perceptron.py::test_and_is_learned_with_any_learning_rate[0.1] PASSED
module-4/test_perceptron.py::test_and_is_learned_with_any_learning_rate[1.0] PASSED
============================== 6 passed
Follow the learning
Epoch 1, example by example:
| Input | Sum (w1·x1 + w2·x2 + bias) | Output | Target | Error | Change |
|---|---|---|---|---|---|
| (0, 0) | 0 | 0 | 0 | 0 | none |
| (0, 1) | 0 | 0 | 0 | 0 | none |
| (1, 0) | 0 | 0 | 0 | 0 | none |
| (1, 1) | 0 | 0 | 1 | +1 | w1 = 0.1, w2 = 0.1, bias = 0.1 |
One error in epoch 1. But now the bias is positive, so in epoch 2 the perceptron says 1 where it should say 0, and makes three errors. Each error pushes the bias down and adjusts the weights, until in epoch 6 the weights are 0.2 and 0.1 with a bias of −0.2:
| Input | Sum | Output | Target |
|---|---|---|---|
| (0, 0) | −0.2 | 0 | 0 |
| (0, 1) | −0.1 | 0 | 0 |
| (1, 0) | 0.0 | 0 | 0 |
| (1, 1) | 0.1 | 1 | 1 |
All four correct, zero errors: training stops. The decision boundary is the line 0.2·x1 + 0.1·x2 − 0.2 = 0, with (1, 1) on one side and the other three on the other. Note how close (1, 0) is: exactly on the boundary, classified as 0 only because the step function says “above 0”. A tiny change to a weight and it flips. Real networks have the same property at a much larger scale.
Why XOR fails
XOR is 1 when exactly one input is 1. Plot the four points: (0, 1) and (1, 0) are 1, (0, 0) and (1, 1) are 0. They sit on opposite corners of a square, and no straight line separates the 1s from the 0s. A perceptron can only draw a straight line, so it keeps correcting forever: after 1,000 epochs it still makes errors, and train returns None.
This was a famous result (Minsky and Papert, 1969) that stalled neural network research for years. The solution is a hidden layer: two perceptrons each draw a line, and a third combines them. That is the step from perceptron to multi-layer network (lesson 21).
For testers, the lesson is general: a model whose structure cannot express the pattern underfits, no matter how long you train it (lesson 48). More epochs do not help; a different model does.
Exercise
- The test with
learning_rate0.01, 0.1 and 1.0 passes for all three. Print the result oftrain(AND, learning_rate=1.0). How do the weights compare with those for 0.1, and why does the number of epochs not change? - Change
max_epochsfor XOR to 10 and useshow=True. What pattern do you see in the errors per epoch?
Show suggested answer
([2.0, 1.0], -2.0, 6): exactly 10 times the weights and bias for 0.1 ([0.2, 0.1], -0.2), learned in the same 6 epochs. With weights starting at 0, every update is a multiple of the learning rate, so the whole learning path is scaled, and the step function only looks at whether the sum is above 0, which scaling does not change. With random starting weights, or with a different activation function, the learning rate does change the path. That is why it is a hyperparameter worth tuning.After the first epochs the errors stay at 4 per epoch, and the weights and bias end each epoch where they started (w1 −0.1, w2 0.0, bias +0.1). The perceptron cycles: every correction for one example undoes a correction for another. More epochs will never fix it.
Your project so far
ai-testing-practice/
├── ...
└── module-4/
├── test_metrics.py
├── test_evaluate_model.py
├── test_model_combinations.py
└── test_perceptron.py new in this lesson
The finished version is in the example repository: module-4/test_perceptron.py.