Lesson 08 · 40 minutes
Train a small neural network and watch its loss fall
- Describe layers, weights and a loss in plain words
- Train an MLPClassifier on digits and read its loss curve
- Count the parameters of a network and compare it with the earlier model
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
Your company wants to buy a detector that is "a deep neural network". Your manager asks three plain questions. How big is it? Does it need special hardware? What does "training" look like when it works, and when it does not? You will train a small network on your laptop, read its loss curve, and count its parameters by hand. Then you will build a different network and say its size before the program does.
Recall
What are the parameters of the model in lesson 1, and how many did it have?
The weights and the bias that fit sets: two weights and one bias, so three numbers. A bigger model has more of them, and the idea is the same.
In lesson 7, how can you see that a model overfits?
The training score is high and the test score is much lower: a gap. The free decision tree reached 1.000 on training data and 0.820 on test data.
The idea
A neural network is a stack of simple steps called layers. Each layer takes numbers in, multiplies each one by a weight, adds them up, and passes the result through a simple bend (an activation function). Without the bend, many layers would collapse into one.
The weights start as small random numbers, so the first answers are bad. Training repeats a loop:
- Show the network some examples and see its answers.
- Compute the loss: one number that says how wrong the answers are. Lower is better.
- Change every weight a very small step in the direction that lowers the loss.
One pass over all the training data is an epoch. If training works, the loss falls from epoch to epoch.
A GPU is a chip with thousands of small cores, good at doing many multiplications at once. Giant models with billions of weights need one. The network in this lesson has fewer than 5,000 weights, and a laptop CPU trains it in seconds.
Worked example
1. Train a network
Go to the lab folder and activate the environment. Create mlp.py. MLPClassifier is the neural network of scikit-learn (MLP stands for multi-layer perceptron). Its settings:
hidden_layer_sizes=(64,)means one hidden layer with 64 units. A unit is one weighted sum with its bend. A pair such as(32, 16)would mean two hidden layers.max_iter=300is the largest number of epochs.tol=1e-3lets training stop when the loss no longer improves by much.random_state=0fixes the random start weights.
The pixels are 0 to 16, and networks train better on small numbers, so the program divides by 16. time.time() gives the clock in seconds, so that the program can measure how long fit takes.
import time
from sklearn.datasets import load_digits
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
X, y = load_digits(return_X_y=True)
X = X / 16.0 # pixels are 0..16; scale them to 0..1
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=42, stratify=y
)
t = time.time()
net = MLPClassifier(hidden_layer_sizes=(64,), max_iter=300, tol=1e-3, random_state=0)
net.fit(X_train, y_train)
secs = time.time() - t2. Read the loss curve
The network keeps its loss after every epoch in loss_curve_, and the number of epochs that it ran in n_iter_. Add these lines.
losses = net.loss_curve_
print("epochs run:", net.n_iter_)
for i in (0, 4, 9, 19, 49, len(losses) - 1):
print(f"epoch {i + 1:>3} loss {losses[i]:.4f}")3. Score it, and count the weights
After training, coefs_ holds one table of weights for each layer step, and intercepts_ holds the biases. w.size is the number of items in a table. sum(w.size for w in net.coefs_) adds up the sizes of all the weight tables, one for each layer step. Add these lines.
print("parameters:", sum(w.size for w in net.coefs_) + sum(b.size for b in net.intercepts_))
print("network train", round(net.score(X_train, y_train), 4), "test", round(net.score(X_test, y_test), 4))
print(f"fit time: {secs:.2f} s")4. Compare with logistic regression
The last lines train the model of lesson 3 on the same scaled data.
lr = LogisticRegression(max_iter=2000).fit(X_train, y_train)
print("logistic train", round(lr.score(X_train, y_train), 4), "test", round(lr.score(X_test, y_test), 4))
print("logistic parameters:", lr.coef_.size + lr.intercept_.size)5. Run it
cd ~/krlab/how-ai-works
source .venv/bin/activate
python mlp.pyepochs run: 127
epoch 1 loss 2.3994
epoch 5 loss 1.8858
epoch 10 loss 1.2886
epoch 20 loss 0.5637
epoch 50 loss 0.1713
epoch 127 loss 0.0497
parameters: 4810
network train 0.997 test 0.98
fit time: 1.12 s
logistic train 0.9859 test 0.9622
logistic parameters: 650The loss falls from 2.40 to 0.05. Early on it falls fast, then slowly. A loss of 2.3 is what a random guess among ten digits gives, so the network starts at "no idea". (To check the number, run python -c "import math; print(math.log(10))". It prints 2.302585..., the loss of a guess that gives every digit a 10 percent chance.) The network reaches 0.980 on the test set, against 0.962 for logistic regression. It has about seven times more parameters (4,810 against 650), and it trained on a CPU in about a second. The time will differ. The count of epochs can differ by a few on another machine, and so can the last digits of the losses. The scores and the parameter counts should match, and so should the first decimals of the early losses.
Each unit has one weight for every number that comes in, and one bias (a fixed number that is added to its sum). The hidden layer has 64 inputs and 64 units: 64 x 64 weights and 64 biases. The output layer has 64 inputs and 10 units: 64 x 10 weights and 10 biases. A network with more layers repeats the sum for each pair of layers: inputs x units + units.
The training score of the network (0.997) is above its test score (0.980). A small gap, as in lesson 7, is normal.
6. The finished file
This is the whole file mlp.py as it stands after the steps above. The lab files of the course hold it.
The finished file: mlp.py
mlp.py
import time
from sklearn.datasets import load_digits
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
X, y = load_digits(return_X_y=True)
X = X / 16.0 # pixels are 0..16; scale them to 0..1
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=42, stratify=y
)
t = time.time()
net = MLPClassifier(hidden_layer_sizes=(64,), max_iter=300, tol=1e-3, random_state=0)
net.fit(X_train, y_train)
secs = time.time() - t
losses = net.loss_curve_
print("epochs run:", net.n_iter_)
for i in (0, 4, 9, 19, 49, len(losses) - 1):
print(f"epoch {i + 1:>3} loss {losses[i]:.4f}")
print("parameters:", sum(w.size for w in net.coefs_) + sum(b.size for b in net.intercepts_))
print("network train", round(net.score(X_train, y_train), 4), "test", round(net.score(X_test, y_test), 4))
print(f"fit time: {secs:.2f} s")
lr = LogisticRegression(max_iter=2000).fit(X_train, y_train)
print("logistic train", round(lr.score(X_train, y_train), 4), "test", round(lr.score(X_test, y_test), 4))
print("logistic parameters:", lr.coef_.size + lr.intercept_.size)Your turn
Build a deeper and smaller network, and count its parameters before you run it. There is no code here: adapt mlp.py.
- Split the digits (scaled to 0 to 1) with
test_size=0.3,random_state=7andstratify=y. - Train an
MLPClassifierwith two hidden layers, of 32 and 16 units. Usemax_iter=300,tol=1e-3andrandom_state=1. - Count the parameters by hand with the method that the worked example showed. Then ask the program, and compare.
- Print the loss of the first epoch and the test accuracy.
Last, explain in one sentence to your manager why this network needs no GPU.
Check yourself
What does the loss measure, and what does training do to it?
The loss is one number for how wrong the network's answers are on the training data. Training changes the weights in small steps so that the loss gets smaller.
The loss at epoch 1 is 2.40. Why is that a sensible starting value for ten classes?
A network with random weights has no idea, so it gives each digit about a 10 percent chance. The loss for that is the natural logarithm of 10, which is about 2.30.
The loss keeps falling, but the test score stops improving. What does it suggest?
The network starts to memorise the training data (overfitting, lesson 7). Watch a validation score, not only the training loss, and stop early.
Why does this course not need a GPU?
The models are small, with thousands of weights, and the data is small. A CPU does the work in seconds. A GPU matters when a model has millions or billions of weights, as in large language models.
Field notes
- The weights are the model. A stolen weights file is a stolen product, and an altered one is an attack. Treat weights as an asset with an owner, access control and a hash that you check before use.
- Small changes to an input can flip the answer of a network. These are adversarial examples, and they are a main topic of the attack courses. A high test score does not protect against them.
- Seeds still matter.
random_state=0fixes the starting weights. Change it and the test score changes in the second or third decimal. Report an average over several seeds when a decision depends on a small difference. - A neural network is not always better. On a table of features, simpler models are often as good, quicker and easier to explain. Try the simple model first and keep it as your baseline.
- Scale the features. Networks and many other models train badly on raw inputs with very different ranges. Do the scaling inside a
Pipeline, fitted on training data only.