Fire, Miss, Adjust

Neural Network Building BlocksMedium+20 XP+20

Fire, Miss, Adjust

An artificial neuron computes z=∑iwixi+bz = \sum_i w_i x_i + bz=∑i​wi​xi​+b. Give it a hard threshold and it behaves like the biological cell it was modelled on: it fires (outputs 1) when z>0z > 0z>0 and stays quiet (outputs 0) otherwise. A total of exactly 000 counts as quiet.

A neuron like this can learn its own weights from labelled examples, with no gradients at all, by adjusting itself every time it gets one wrong. Visit the examples one at a time, in order:

  1. Compute the neuron's output for example xxx using the current weights and bias.
  2. Compare it with the example's label ttt (0 or 1). The error is e=t−outpute = t - \text{output}e=t−output, so it is +1+1+1, −1-1−1 or 000.
  3. If e≠0e \neq 0e=0 the neuron made a mistake, and every weight and the bias change straight away:
wi←wi+η e xi,b←b+η ew_i \leftarrow w_i + \eta\, e\, x_i, \qquad b \leftarrow b + \eta\, ewi​←wi​+ηexi​,b←b+ηe

where η\etaη is the learning rate. If e=0e = 0e=0, nothing changes.

One trip through all the examples is a pass. Training starts with every weight and the bias at 000. It stops after the first pass in which the neuron makes no mistakes, or after passes passes, whichever comes first.

Task: write train_perceptron(examples, labels, lr, passes).

  • examples is a list of equal-length lists of numbers, and labels holds a 0 or 1 for each one.
  • Return a tuple (weights, bias, mistakes): the final weights as a list and the final bias, each rounded to 4 decimal places, and mistakes, a list holding the number of mistakes made in each pass that ran.

This rule only ever learns from its errors: a correct answer teaches it nothing. Backpropagation, later in the course, keeps that spirit but swaps the all-or-nothing threshold for something smooth enough to have a slope.

Examples

examples = [[0, 0], [0, 1], [1, 0], [1, 1]]
labels = [0, 0, 0, 1]
lr = 1.0
passes = 10
returns ([2.0, 1.0], -2.0, [1, 3, 3, 2, 1, 0])
examples = [[2.0, 0.5], [0.5, 3.0], [3.0, 1.0], [1.0, 2.5]]
labels = [1, 0, 1, 0]
lr = 0.5
passes = 10
returns ([0.75, -1.25], 0.0, [2, 0])

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run