From Arithmetic to a Working Model
The previous lesson followed one neuron by hand. Here you train a network with 32 hidden neurons to recognise handwritten digits, read its loss curve to see the training happen, and compare the result with a baseline, as with every other model.
The Digits Data
scikit-learn includes a small set of 1,797 images of handwritten digits, collected from 43 people. Each image is a grid of 8 × 8 = 64 squares, and each square holds a number from 0 to 16 for how much ink it contains. So each sample has 64 features, one per square, and a label from 0 to 9. A model never "sees" the picture: it receives those 64 numbers in a row.
The Network in scikit-learn
MLPClassifier is scikit-learn's neural network for classification. MLP
stands for multi-layer perceptron, an older name for this kind of network.
The settings used here:
hidden_layer_sizes=(32,): one hidden layer of 32 neurons. The default is one layer of 100.(64, 32)would mean two hidden layers.max_iter=300: at most 300 passes through the training data. The default is 200. Training stops earlier if the loss stops improving.random_state=5: the starting weights are random, so fixing this makes training repeatable.
Its defaults use the ReLU activation and the Adam method from the previous
lesson. Because networks are sensitive to feature scales, the network goes
into a pipeline after a StandardScaler.
After training, loss_curve_ holds the training loss after each pass, and
n_iter_ the number of passes actually made.
Exercise: Train a Digits Network
You will train the network, compare it with a baseline, and save its loss curve as a chart.
Starting state: the course environment, active in your terminal. The digits data ships with scikit-learn.
-
Create the exercise folder. macOS and Linux:
mkdir -p ~/ai-practice/digits-network cd ~/ai-practice/digits-networkWindows PowerShell:
mkdir $HOME\ai-practice\digits-network cd $HOME\ai-practice\digits-networkSave this as
digits_network.pyin that folder:"""Train a small neural network on the digit images and read its loss curve.""" import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from sklearn.datasets import load_digits from sklearn.dummy import DummyClassifier 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_digits(return_X_y=True) # 1,797 images of 8 x 8 = 64 pixel values, digits 0 to 9 X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=5, stratify=y) baseline = DummyClassifier().fit(X_train, y_train) network = make_pipeline( StandardScaler(), MLPClassifier(hidden_layer_sizes=(32,), max_iter=300, random_state=5), ) network.fit(X_train, y_train) mlp = network.named_steps["mlpclassifier"] print(f"Baseline test accuracy: {baseline.score(X_test, y_test):.3f}") print(f"Network test accuracy: {network.score(X_test, y_test):.3f}") print(f"Iterations: {mlp.n_iter_}; loss at first {mlp.loss_curve_[0]:.3f}, at last {mlp.loss_curve_[-1]:.3f}") fig, ax = plt.subplots() ax.plot(range(1, len(mlp.loss_curve_) + 1), mlp.loss_curve_) ax.set_xlabel("iteration") ax.set_ylabel("training loss") fig.savefig("loss_curve.png") print("Saved loss_curve.png") -
Run it. Training takes a few seconds:
python digits_network.pyOutput, which should match exactly:
Baseline test accuracy: 0.102 Network test accuracy: 0.964 Iterations: 219; loss at first 2.806, at last 0.008 Saved loss_curve.pngNo warning appears.
loss_curve.pngshows the loss dropping steeply at first, then flattening close to zero.
How the Script Works
The split. 1,347 images train the network and 450 test it, stratified so each digit keeps its share.
The pipeline. make_pipeline(StandardScaler(), MLPClassifier(...)) scales
each of the 64 pixel features using training statistics, then trains the
network. The code is split over several lines inside the brackets only for
readability.
Reading the network's records. named_steps["mlpclassifier"] retrieves the
trained network from the pipeline, using the lowercase class name. n_iter_
is 219: training stopped before the 300-pass limit because the loss had
stopped improving, so there is no convergence warning. loss_curve_[0] is the
loss after the first pass, 2.806, and loss_curve_[-1] after the last, 0.008.
The chart. range(1, len(mlp.loss_curve_) + 1) numbers the passes from 1,
and ax.plot draws the loss against them.
What the results show. The baseline, always predicting the most common
digit, is right about one time in ten, 0.102, as expected with ten balanced
classes. The network is right on 0.964 of the 450 test images: about 16
mistakes. The training loss fell almost to zero, but the test accuracy is not
1.000; a falling loss shows the network fitting its training images, while
only the test score shows how it handles new ones. If you changed
hidden_layer_sizes=(32,) to (8,), the network would have far fewer weights
to learn with; try it and compare the test accuracy.
Success: the output matches; you can explain what the loss curve shows, why there is no convergence warning here, and how the network compares with the baseline.
If something differs:
| What you see | Likely cause | Next step |
|---|---|---|
| Slightly different numbers | random_state was changed or removed, or another platform rounds differently | Restore random_state=5; compare the size of the numbers, not the last digit |
A ConvergenceWarning | max_iter was lowered, or the scaler was removed | Restore the settings shown |
KeyError: 'mlpclassifier' | The step name was typed differently | Use the lowercase class name |
| The script takes much longer than a minute | Very slow computer, or hidden_layer_sizes was greatly increased | Restore (32,); wait for it to finish |
-
Clean up. macOS and Linux:
cd ~/ai-practice ls rm -rf digits-network lsWindows PowerShell:
cd $HOME\ai-practice ls Remove-Item -Recurse digits-network lsCheck that the first
lsshowsdigits-networkbefore removing it. Do the independent task first.
Independent task: change max_iter=300 to max_iter=5 and predict three
things before running: whether a warning appears, what happens to the test
accuracy, and how the last loss value compares with 0.008. Run it and explain
what you see.
Check Your Understanding
- A team shows a loss curve that falls smoothly to almost zero and says this proves their network will work well for customers. What does the curve show, and what does it not show?
- Why does the network sit in a pipeline after a
StandardScaler?
Answer and Reasoning
Independent task
A ConvergenceWarning appears: Stochastic Optimizer: Maximum iterations (5) reached and the optimization hasn't converged yet. The script still
finishes. The test accuracy falls to 0.427, and the last loss is 1.863, far
above 0.008: after only five passes the weights are still far from good
values. The warning is telling you exactly that, and the low accuracy
confirms it. Raising max_iter again, as the warning implies, lets training
continue until the loss stops improving.
Understanding check
- The curve shows the network fitting its training data better and better. It does not show how the network handles new data, which needs a test score on held-out data, compared with a baseline. A near-zero training loss can also be a sign of overfitting.
- Networks are sensitive to the scale of their inputs, and scaling makes training's steps work well for every feature. The pipeline fits the scaler on training data only, so scaling does not leak test information.