The first artificial neurons · lesson 7 of 7
Parts in this lesson
Aclass Perceptron(Neuron): def activation(self, z): ...a subclass overrides only what differs
Berror = y[i] - self.activation(self.net_input(X[i]))5.5: one update rule for all three
Cscores.argmax(axis=1)one-vs-rest: the most confident neuron wins
Djson.dump(saved, f, indent=2)saving the weights to a file

Project: three neurons from scratch

Last updated

Lesson 5.5 found that the perceptron, Adaline and logistic regression differ in only one box. This project makes that literal: one Python base class, Neuron, holds everything they share, and three small subclasses each supply an activation and a loss. Then you'll combine them, one neuron per species, to tell three kinds of penguin apart, draw their boundaries and loss curves, and save the trained weights to a JSON file and load them back.

By the end of this lesson you can

  • Write a Neuron base class with fit and predict, and three subclasses that override only what differs
  • Use get_ and set_ methods to read and restore a neuron's weights
  • Combine binary neurons into a three-class classifier with one-vs-rest
  • Compare the three on boundaries, loss curves and test accuracy, and save the weights as JSON

Plan it

The question: the three neurons of this stage share one update rule and differ in one box (lesson 5.5). Can you write them so the code says so? And how do they compare on a real three-class problem?

The data: the Palmer penguins, all three species, by bill length and depth.

What you'll make: one notebook that, run from the top,

  1. loads the penguins, splits off a stratified test set, and scales with the training set's numbers,
  2. defines a Neuron base class with fit and predict, and three subclasses,
  3. trains each kind to tell Gentoos from the rest, and prints its loss,
  4. combines three neurons into a three-species classifier, for each kind,
  5. draws the boundaries and the loss curves,
  6. saves the weights to neurons.json and loads them back.

On your own computer, make it in the ml-course folder as 05-neurons.ipynb, in the virtual environment you've used since Stage 0. The design, from lesson 5.5:

Three neuronsRosenblatt, 1958
x₁w₁x₂w₂1bΣz = w·x + bthe same for all threeactivationstep: 0 or 1output = step(z)predict: output itselfloss: perceptron criterion(how far the mistakes are over the line); the step down it isw ← w + η (y − output) x, for all threenew weights

Perceptron: the output used for learning is step(z), and it predicts with that output. With a step, y − output is 0 when it's right, so it only learns from mistakes, always by the same amount. Only the two pink boxes change.

05-neurons.ipynb

256 penguins to train on, 86 to test. The test set is scaled with the training set's mean and standard deviation, so nothing about it leaks into training (lesson 2.10).

A Neuron base class with fit and predict

The base class holds everything the three share:

  • __init__ stores the settings, and starts with no weights. The underscore on _w, _b and the rest says "don't touch these from outside the class": read them with get_weights() and get_history(), and change them with set_weights().
  • net_input(X) is the weighted sum, z=Xw+b, for many rows at once.
  • fit(X, y) is lesson 5.5's rule, w←w+η(y−output)x, one shuffled example at a time, with the loss recorded after every epoch. It calls self.activation and self.loss without knowing which kind of neuron it is.
  • predict(X) gives 1 where the output is at least 0.5, else 0. For the perceptron and the sigmoid, that's the same as z≥0. Adaline's output is z itself, so it predicts 1 where z≥0.5, halfway between its targets 0 and 1.
  • activation and loss raise NotImplementedError: the base class says every neuron must have them, but leaves them to the subclasses.

Labels are 0 and 1 throughout. As a UML class diagram, with the subclasses of step 3 and the one-vs-rest class of step 4:

The classes in this project
100%
OneVsRest
  • #_make_neuron
  • #_classes: list
  • #_neurons: list
  • +__init__(make_neuron)
  • +get_neurons()
  • +set_neurons(classes, neurons)
  • +fit(X, labels)
  • +predict(X)
Neuron
  • #_learning_rate
  • #_epochs
  • #_seed
  • #_w
  • #_b: float
  • #_history: list
  • +__init__(learning_rate, epochs, seed)
  • +get_weights()
  • +set_weights(w, b)
  • +get_history()
  • +net_input(X)
  • +activation(z)
  • +loss(X, y)
  • +fit(X, y)
  • +predict(X)
  • +to_dict()
Perceptron
  • +activation(z)
  • +loss(X, y)
Adaline
  • +activation(z)
  • +loss(X, y)
LogisticNeuron
  • +activation(z)
  • +loss(X, y)
  • Class Neuron; attributes: _learning_rate, _epochs, _seed, _w, _b, _history; methods: __init__, get_weights, set_weights, get_history, net_input, activation, loss, fit, predict, to_dict.
  • Class Perceptron; inherits from Neuron; no attributes of its own; methods: activation, loss.
  • Class Adaline; inherits from Neuron; no attributes of its own; methods: activation, loss.
  • Class LogisticNeuron; inherits from Neuron; no attributes of its own; methods: activation, loss.
  • Class OneVsRest; attributes: _make_neuron, _classes, _neurons; methods: __init__, get_neurons, set_neurons, fit, predict.
  • OneVsRest holds many Neuron in _neurons.

The hollow-headed arrows say "is a kind of": a Perceptron is a Neuron, so it has fit, predict and the getters and setters without writing them again. The line with an open diamond says "holds": a OneVsRest keeps a list of neurons in _neurons, any number of them (*). The # marks attributes whose names start with an underscore.

Three subclasses

Each subclass is a few lines: an activation, and a loss to record.

  • Perceptron: the step, 1 if z≥0, else 0. Its loss is the number of mistakes.
  • Adaline: the identity, z itself. Its loss is 12 the mean squared error.
  • LogisticNeuron: the sigmoid, σ(z)=1/(1+e−z). Its loss is the mean cross-entropy, with the probabilities clipped away from 0 and 1 so the logarithm is always finite (lesson 3.10).

Train each to answer one question, "Gentoo or not?":

05-neurons.ipynb

All three learn. The perceptron goes from 7 mistakes after the first epoch to 3 after 30: a few Gentoos and Chinstraps overlap on these two features, so it never reaches 0. Adaline's loss falls from 0.113 to 0.026, and logistic regression's from 0.115 to 0.046. (The three losses measure different things, so compare each with itself, not with the others.)

Notice what you didn't write: three fit methods. If you find a bug in fit, you fix it once. That's what the base class is for.

One-vs-rest for three species

Each neuron answers a yes-or-no question. For three species, train three neurons: "Adelie or not?", "Chinstrap or not?", "Gentoo or not?". To classify a new penguin, ask all three and pick the species whose neuron is most confident, the one with the biggest weighted sum z. That's one-vs-rest, and scikit-learn's OneVsRestClassifier does the same.

OneVsRest takes a function that makes a fresh neuron, so it works for any kind. It holds its neurons in a list but isn't a neuron itself, which is why the class diagram joins it to Neuron with a diamond, not an arrow: it has neurons, it isn't one.

05-neurons.ipynb

On the 86 test penguins: the perceptron 89.5%, Adaline and logistic regression 91.9% each. The perceptron's lines are wherever it happened to stop (lesson 5.2), which costs it two more penguins. All three see only the two bill measurements, and draw straight lines; "Try next" adds the others.

Plot boundaries and loss curves

To see the boundaries, predict a species at every point of a fine grid, and colour the grid:

05-neurons.ipynb

Every region's edges are straight: each boundary is where two neurons' weighted sums are equal, and that's a line. The penguins the models get wrong sit where two species' clouds overlap, near those edges. The perceptron's lines are wherever its last updates left them (lesson 5.2), so they'd move if you trained it for one more epoch; the other two's would barely change.

And the loss curves, one line per neuron:

05-neurons.ipynb

Lesson 5.4's contrast, nine times over. The perceptron's mistake counts jump up and down from epoch to epoch, most for Chinstrap, which overlaps both others. Adaline's and logistic regression's losses fall quickly and level off.

Save and load the weights

A trained model is only useful if you can keep it. Each neuron's to_dict method returns its kind, weights and bias as plain Python numbers, which json.dump can write to a file (Simple Python, lesson 2.8). To load them, make fresh neurons and restore each one's weights with set_weights:

05-neurons.ipynb

The first saved neuron, logistic regression's "Adelie or not?", has a weight of about −6.9 on bill length and +4.1 on bill depth: short, deep bills mean Adelie. The loaded model gives exactly the same answers on every test penguin as the one that was trained (True). Open neurons.json in an editor on your own computer: it's readable text.

Note what wasn't saved: the scaling. A new penguin must be scaled with the same training mean and standard deviation before it meets these weights. In a real project, save mean and std in the same file (or use a scikit-learn pipeline, lesson 4.1, and save the whole thing).

Finished

You've built three neurons from one class and compared them on a real problem. Your notebook

  • splits and scales the penguins without leaking the test set,
  • defines a Neuron base class and three subclasses that override only the activation and the loss,
  • uses getters and setters to read and restore weights,
  • combines neurons into a three-species classifier with one-vs-rest,
  • draws the boundaries and the loss curves, and
  • saves the trained weights to JSON and loads them back.

Before you call it finished, restart the kernel and run every cell from the top. If the numbers are the same, it's done.

Try next:

  • Add the other two measurements, flipper length and body mass. How much does each kind improve?
  • Write a fourth subclass, HingeNeuron, whose update moves only when yz<1 (with labels ±1): a linear SVM trained one point at a time (lesson 5.5). You'll need to override fit's error as well; what's the neatest way to let a subclass do that?
  • Save mean and std into neurons.json too, and write a function load_model(path) that returns a ready-to-use classifier.

Stage 6 stacks these units into layers, and trains all the layers at once with backpropagation.

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Machine Learning