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,
- loads the penguins, splits off a stratified test set, and scales with the training set's numbers,
- defines a
Neuronbase class withfitandpredict, and three subclasses, - trains each kind to tell Gentoos from the rest, and prints its loss,
- combines three neurons into a three-species classifier, for each kind,
- draws the boundaries and the loss curves,
- saves the weights to
neurons.jsonand 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:
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.
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,_band the rest says "don't touch these from outside the class": read them withget_weights()andget_history(), and change them withset_weights().net_input(X)is the weighted sum, , for many rows at once.fit(X, y)is lesson 5.5's rule, , one shuffled example at a time, with the loss recorded after every epoch. It callsself.activationandself.losswithout 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 . Adaline's output is itself, so it predicts 1 where , halfway between its targets 0 and 1.activationandlossraiseNotImplementedError: 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:
- #_make_neuron
- #_classes: list
- #_neurons: list
- +__init__(make_neuron)
- +get_neurons()
- +set_neurons(classes, neurons)
- +fit(X, labels)
- +predict(X)
- #_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()
- +activation(z)
- +loss(X, y)
- +activation(z)
- +loss(X, y)
- +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, if , else . Its loss is the number of mistakes.Adaline: the identity, itself. Its loss is the mean squared error.LogisticNeuron: the sigmoid, . 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?":
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 . 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.
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:
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:
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:
The first saved neuron, logistic regression's "Adelie or not?", has a weight of about on bill length and 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
Neuronbase 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 (with labels ): a linear SVM trained one point at a time (lesson 5.5). You'll need to overridefit's error as well; what's the neatest way to let a subclass do that? - Save
meanandstdintoneurons.jsontoo, and write a functionload_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.
- Horst, Hill and Gorman, palmerpenguins: Palmer Archipelago (Antarctica) penguin data, 2020: the penguins, measured by Gorman, Williams and Fraser (2014)
- Python 3.14: Classes, inheritance: subclasses that override methods of their base class
- Python 3.14: json: json.dump and json.load
- scikit-learn: Multiclass and multioutput algorithms, one-vs-the-rest: the same strategy, as OneVsRestClassifier