Machine learning from zero · Lesson 7.1 · 32 of 33 lessons ready · 12 min
Neural networks: many simple units together
In short
A neural network stacks simple units that each draw one line and bend it. More hidden units let the decision regions curve around iris flowers.
Warm-up Two questions from earlier lessons. A minute, and it never blocks the lesson.
Logistic regression from lesson 5 can only draw a straight boundary. Trees can draw only boxes. But what if the classes curl around each other? You could try to invent the right curve by hand for every problem — or you could build a model out of pieces so simple that each one can only draw a straight line, and let the combination draw anything. That is the bet behind neural networks.
Choose an answer and how sure you are.
Answer to unlock the lab.
Interactive lab
This interactive lab runs in a browser with JavaScript enabled. The text around it describes what the lab shows.
Show the answer
Correct answer: It does not rise, and may even fall, although training gets better
Two neurons score 81.3% on the test set and 32 neurons 70.7%, although training accuracy rises from 81.3% to 94.7%. The bigger network fits chance details of the 75 training flowers. Two of the three species overlap in these two measurements, so a perfect split does not exist anyway.
Try this
- Set the hidden-units slider to its smallest value and press Train. Look at the decision regions: how many straight edges can you see?
- Increase the number of hidden units and press Train again. Watch the boundaries bend and compare the accuracy.
- Set the hidden-units slider to its largest value and train. Do the regions start to bend around individual flowers? Ask yourself whether a new flower in such a pocket would really belong to that species.
- Look at the flowers where two species overlap. Can any boundary separate them using only these two measurements?
Now that you've tried it, let's see what was actually going on.
The idea in plain words
A neural network is made of small units called neurons. Each neuron does something we already know: it takes a weighted sum of its inputs, adds an intercept, and passes the result through a simple bending function called an activation. One neuron on its own is nearly logistic regression; it can separate the plane with one straight line.
Neurons are arranged in layers. The inputs (here, two flower measurements) feed a hidden layer of neurons, each of which draws its own line and reports how far, and on which side, a point lies. The output layer combines those reports into the final decision. Because each hidden neuron bends its signal, combining them produces boundaries with corners and curves.
Picture a team of very simple lookouts guarding a field. Each lookout can only say "the intruder is on my left" or "on my right" of a single straight fence. One lookout is not much use. But a supervisor who listens to many lookouts, each with a fence in a different place, can pin down regions of almost any shape.
Why it works
One neuron computes
output = f(w · x + b)
where x is the list of inputs, w the weights, b the intercept, and f the activation. Without f, stacking layers would be pointless: a weighted sum of weighted sums is still just one weighted sum, so the whole network would draw a single straight line. The activation is the crease that stays. With it, each hidden neuron adds one bend, and enough bends can approximate any reasonable boundary. More hidden units mean more possible bends — more flexibility, which, as lesson 7 taught, cuts both ways.
The weights are learned with the tools from lessons 4 and 5. The network makes predictions, the log loss measures how wrong they are, and gradient descent nudges every weight downhill. The only new trick is how to find the gradient for weights deep inside the network: an algorithm called backpropagation applies the chain rule of calculus backwards from the output, layer by layer, telling each weight how much it contributed to the error.
The example in this lesson is the Iris dataset: 150 flowers of three species, 50 of each, made famous by Ronald Fisher's 1936 paper. We take two of the four measurements, so every flower is a point on a plane, and the trained network assigns a predicted species to every spot on that plane.
The idea is old — Frank Rosenblatt built the perceptron, a single trainable neuron, in 1958 — but networks became dominant only when data, computing power and training tricks grew large enough to train many layers.
Common mistake
"Neural" suggests a brain, and that suggestion misleads. An artificial neuron is a weighted sum with a bend, not a model of a biological cell, and a network does not understand flowers; it fits a function to examples. The practical mistake is to assume bigger is always better. A network with many hidden units on a small dataset can memorise exactly as a deep tree or a high-degree polynomial does. Its size has to be chosen with validation data, and its training watched for the same gap between training and test performance we met in lesson 7.
Stack enough layers, feed them enough text, and one prediction task turns into something that writes. In the final lesson we see how a network learns language by guessing the next word.
Want to go deeper? The NN course starts from a single neuron (PL).
Quiz
Three questions to check yourself. Pick an answer, or open the answer under a question. Keyboard: arrow keys choose, Enter or Space confirms.
Key takeaways
- A neuron is a weighted sum plus a bending activation function.
- A hidden layer combines many simple lines into curved boundaries.
- Weights are learned with gradient descent; backpropagation supplies the gradient for every layer.
- More hidden units mean more flexibility, which must be controlled with validation data.
Going further: formula, code, practice
The math
One neuron computes a = f(w·x + b), where x holds the inputs, w the weights, b the intercept and f the activation. A hidden layer with h neurons is the same thing in matrix form: a = f(W₁x + b₁). The output layer then computes ŷ = softmax(W₂a + b₂).
- Without
f, the layers collapse:W₂(W₁x + b₁) + b₂ = (W₂W₁)x + (W₂b₁ + b₂), which is a single linear map. The activation is what makes depth useful. - Training minimises the log loss
L = −(1/n) Σ log ŷᵢ,yᵢ, whereŷᵢ,yᵢis the probability the model gave to the true species of flower i. - Backpropagation is the chain rule applied from the output backwards:
∂L/∂W₁ = ∂L/∂ŷ · ∂ŷ/∂a · ∂a/∂W₁. - Gradient descent then updates every weight:
w ← w − η · ∂L/∂w, whereηis the learning rate.
In code (Python)
A small network on the lab's data: two sepal measurements, half of the flowers for training (75), standardised inputs, tanh units, 2 and 32 hidden units. This is scikit-learn's trainer, not the lab's:
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_iris(return_X_y=True)
X = X[:, :2] # sepal length and sepal width, as in the lab
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.5, stratify=y, random_state=1)
for h in (2, 32):
net = make_pipeline(StandardScaler(), MLPClassifier(hidden_layer_sizes=(h,), activation="tanh", solver="lbfgs", max_iter=5000, random_state=0))
net.fit(X_tr, y_tr)
print(f"{h:2d} hidden units: train {net.score(X_tr, y_tr):.1%}, test {net.score(X_te, y_te):.1%}")
Output
2 hidden units: train 84.0%, test 74.7%
32 hidden units: train 96.0%, test 66.7%
The pattern is the lesson's: the bigger network fits the training flowers better and does worse on the test flowers. The lab's own trainer (gradient descent with momentum) gives 81.3% and 70.7% on the test set for 2 and 32 units, so the numbers differ but the pattern does not.
Download the notebook (.ipynb). Open it in Jupyter or upload it to Google Colab; it fetches any missing data itself.
For practitioners
- Standardise the inputs before training (subtract the training mean, divide by the training standard deviation). Unscaled features make gradient descent slow or unstable.
- Choose the number of hidden units on validation data, not on training accuracy. A bigger network almost always fits the training set better (96.0% against 84.0% above).
- Small datasets, like 75 training flowers, are easy to memorise. Try a smaller network, weight decay or early stopping before adding units.
- Different random initial weights give different networks. For a fair comparison, fix the seeds you use, and compare over several of them.
- On table-shaped data, gradient-boosted trees are often the stronger baseline. Try it before reaching for a network.
Was this helpful?
Thanks! This helps us improve the Atlas.
Go deeper in the Atlas
Encyclopedia entries on the ideas in this lesson: