Understanding AI · lesson 28 of 60 · about 7 minutes
A Neuron That Learns
Nobody sets the weights by hand. Watch a neuron fix its own weights, one mistake at a time.
What you'll learn
- Explain how a neuron updates its weights after a mistake
- Follow a neuron learning a simple rule
- Explain why it stops changing once it's right
Learning from mistakes
We want a neuron that says 1 only when BOTH inputs are 1. We start every weight at 0 and show it the four possible cases, again and again.
After each guess, the error is the right answer minus the guess. If the guess was right, the error is 0 and nothing changes. If it was wrong, each weight moves a little in the direction that would have helped.
A neuron learning both-must-be-1. It counts its mistakes each round; by round 5 it has none.
examples = [((0, 0), 0), ((0, 1), 0), ((1, 0), 0), ((1, 1), 1)]
w1, w2, bias = 0, 0, 0
for round_number in range(7):
mistakes = 0
for (x1, x2), target in examples:
total = x1 * w1 + x2 * w2 + bias
guess = 1 if total > 0 else 0
error = target - guess
if error != 0:
mistakes = mistakes + 1
w1 = w1 + error * x1
w2 = w2 + error * x2
bias = bias + error
print("round", round_number, "mistakes:", mistakes)
print(w1, w2, bias)Output
round 0 mistakes: 1
round 1 mistakes: 3
round 2 mistakes: 3
round 3 mistakes: 2
round 4 mistakes: 1
round 5 mistakes: 0
round 6 mistakes: 0
2 1 -2Nobody chose those weights
It ended with weights 2 and 1 and a bias of -2. Check: only when both inputs are 1 is 2 + 1 - 2 above 0. Nobody worked those numbers out; the neuron found them from its mistakes. Big networks learn the same way, just with billions of weights.
Tip
1 if total > 0 else 0 is a one-line if: 1 when the total is above 0, otherwise 0. And != means not equal.
Now try it yourself
This lesson is free in Codiqo, with 5 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.