Artificial Intelligence Fundamentals / Clusters and Neural Networks

Train a small neural network

Lesson 18 of 26. Open to read. No account needed.

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.

  1. Create the exercise folder. macOS and Linux:

    mkdir -p ~/ai-practice/digits-network
    cd ~/ai-practice/digits-network
    

    Windows PowerShell:

    mkdir $HOME\ai-practice\digits-network
    cd $HOME\ai-practice\digits-network
    

    Save this as digits_network.py in 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")
    
  2. Run it. Training takes a few seconds:

    python digits_network.py
    

    Output, 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.png
    

    No warning appears. loss_curve.png shows 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 seeLikely causeNext step
Slightly different numbersrandom_state was changed or removed, or another platform rounds differentlyRestore random_state=5; compare the size of the numbers, not the last digit
A ConvergenceWarningmax_iter was lowered, or the scaler was removedRestore the settings shown
KeyError: 'mlpclassifier'The step name was typed differentlyUse the lowercase class name
The script takes much longer than a minuteVery slow computer, or hidden_layer_sizes was greatly increasedRestore (32,); wait for it to finish
  1. Clean up. macOS and Linux:

    cd ~/ai-practice
    ls
    rm -rf digits-network
    ls
    

    Windows PowerShell:

    cd $HOME\ai-practice
    ls
    Remove-Item -Recurse digits-network
    ls
    

    Check that the first ls shows digits-network before 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

  1. 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?
  2. 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

  1. 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.
  2. 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.

References

Study this course with an account

Course access adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 199 plus 18% GST. 90 days of online access. No auto-renewal.

See course access

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy