CSCI 379 homework 7: neural networks

In this assignment, you will be getting some practice with neural networks using the PyTorch machine learning library. MNIST is a popular machine learning dataset consisting of many handwritten numbers. Each piece of data is an image of 28x28 resolution with grayscale pixels. For this assignment, it is your job to create a neural network which can predict what number is in one of these images. This is roughly the ML neural network equivalent of “Hello, world!”.

Learning goals

The overall aim here is to gain practice building a neural network machine learning model using PyTorch. But we don’t want your model to be a black box, so you’ll investigate how all the pieces work together.

Some parts of this assignment are a bit more open-ended or ill-specified; you’re expected to fill in the gaps by using the PyTorch documentation and your own Python skills – and asking for help, if needed.

Getting started

The usual file and directory conventions: make a hw7 directory, with the file hw7-writeup.txt. Copy the homework 7 starter Python code to hw7.py.

For this assignment, we will be making use of a few libraries: pytorch, pytorchvision, scikit-learn, and matplotlib. If you haven’t already, we can install these using pip. If you are using the lab machines, make sure the required libraries are installed:

pip install torch torchvision

pip install matplotlib scikit-learn

Some of those libraries may already be installed; pip will note that and keep going.

I saw problems with matplotlib and numpy – the lab machines have an old version of matplotlib that uses an old version of numpy; the above installation will use versions of libraries that depend on newer numpy versions – and because your user’s local Python packages get loaded first, the system matplotlib will load against your user’s too-new numpy and not work. You can fix that with

python -m pip install --user --upgrade matplotlib

Check the imports by running your code:

python hw7.py

In this assignment, you’ll be running long training runs many times, spending a lot of time waiting for it to finish. If you’d like to embody the programmer’s virtue of impatience, use the lab machines, which have an Nvidia GPU available. I saw about a 30% speedup there – 80 seconds versus 115 seconds.

You can ssh to rns20{2,3}-N.cs.stolaf.edu. RNS 202 has 21 computers – N from 1 to 21 – and 203 has 17. They have a shared file system, so you can connect to any of them and see the same files.

The “{2,3}” notation is standard Unix shell brace expansion. It expands to one word for each comma-separated value – here, you’d get rns202-N.cs.stolaf.edu and rns203-N.cs.stolaf.edu. This notation is so common in the CS community they use it in journal articles: if there are several authors from one institution, their email addresses will often be written like “{drake3,leeson2,olaf}@stolaf.edu”.

Overview

At a high level, you’ll be doing roughly the same thing as the PyTorch “Learn the Basics” tutorial. Read through that and use it as a starting point as you work through building your model. You should also peruse the other Learning PyTorch resources.

Looking at the starter code, there are several functions already implemented. Here is a brief description of each:

Looking at our data

When dealing with machine learning models, its a good idea to get acquainted with our data. Right now, the main function does the following: set the hyperparameters for training, build the datasets, get the first item out of the training set, and call some functions. Let’s look at this first item.

Run the program and put the output in your writeup. Investigate the size function for Torch tensors. Explain what each number in the output means. Why do they have that particular size? What do they store?

Building our model

Next, we need to build our model.

In the NeuralNetwork class, implement a neural network using PyTorch. It should consist of 3 layers. The constructor’s “dim” parameters indicate the number of nodes used in the various layers. It will have one input neuron for every pixel in the image. Its output is, effectively, a one-hot encoding for the digit.

The first layer has input_dim inputs and hidden_dim outputs; the second layer has hidden_dim inputs and outputs; and the final layer has hidden_dim inputs and out_dim outputs. It should use relu as its activation function.

Make a sequential network with appropriately-sized linear layers and ReLU activation functions. Store that in the linear_relu_stack field.

In PyTorch, we can run our model on data by using the following command:

model(input_data)

where model is our model and input_data is our data.

You can tell PyTorch to use a GPU to speed things up. You have to “move the model to the device”. After creating your model instance, do model.to(device).

The starter code falls back to the standard CPU device, so it should be safe to include that line on any computer.

If you get an error like

RuntimeError: Expected all tensors to be on the same device, but got mat1 is on cpu...

you need to be consistent about moving the model, features, or labels to the right device – use the .to() method.

The forward method is where each individual input gets fed forward through the network. In that method, apply the linear ReLU stack to the provided x input and return that from forward().

To test that, create a model instance. It should have an input neuron for each pixel in our image. The hidden dimension should be the hidden_layer_size variable declared at the top of main(). It should have an output neuron for each digit from zero to nine.

Now, let’s just run the model on an input: do model(features). You should get an error like:

RuntimeError: addmm: mat1 and mat2 shapes cannot be multiplied (448x28 and 784x128)

Why can’t it multiply?

In high school algebra you learned about linear functions with a single number input (\(x\)) and single number output (\(y\)): the classic \(y = mx + b\).

Linear functions that accept \(n\) inputs and have \(m\) outputs are, conceptually, “exactly the same”, and the notation we use is intended to reflect that:

\[ Y = MX + B \]

Our layers here are linear, and they operate through matrix operations. Our input (= the output from the previous layer, one input per neuron) is represented by the matrix \(X\): we have \(n\) inputs, so \(X\) is an \(n \times 1\) matrix (or vector, if you like).

The output of the current layer has \(m\) nodes, so the matrix \(M\) must have \(n\) columns and \(m\) rows. The product \(MX\) will be an \(m\)-dimensional vector, and to add in the bias, we’ll need \(B\) to have the same dimensions.

Above I’m using the convention of points in \(n\)-dimensional space being represented by column vectors; for those, applying the linear transformation represented by an \(m \times n\) matrix \(M\) is achieved by multiplying \(Mx\).

But other sources – including, very notably, PyTorch – use a row vector convention; if writing \(x\) as a row vector, the above would be written \(x M^T\); the T represents the transpose of the matrix. In the end, the computations are identical; it’s just a different convention for writing things.

If you haven’t taken linear algebra and/or the above is too mysterious:

PyTorch attempts to make data fit through the network. Right now, the features variable is a PyTorch tensor – a 4-dimensional array of dimension \(16 \times 1 \times 28 \times 28\).

PyTorch makes the data fit by “flattening” several dimensions: think about flattening a 3 by 4 grid of numbers – a matrix – into a column vector with 12 entries. Or a 3-dimensional array of size 2 by 3 by 5 into a 30-dimensional vector.

In your writeup, answer these questions: based on what you saw for the size of features and the meanings of its various dimensions, what dimensions is PyTorch flattening?

Which dimensions should get flattened?

We want each sample to have a single 784-dimensional feature.

Create a new variable called flat_features. Set it equal to

torch.flatten(features, start_dim=1)

Find the size of that new variable. What is it?

Now take those flattened features and feed them through the network to get predicted labels.

What’s the size of the output? Include that output in your write up. It’s a bit big, so you can elide some parts – include enough to make the overall structure and pattern clear.

Describe the structure of that output and what it represents.

What do the numbers in the output represent? They can’t possibly be probabilities. What are they? Refer to our calculations for logistic regression and the PyTorch tutorial to find the typical name for these numbers.

Take one of those output vectors and use softmax to convert it to a probability distribution. Include the output vector and corresponding distribution in your write up. All the probabilities are all roughly equal. Why?

Going forward, it will be more convenient to have the network handle its own flattening.

Add a flatten field to the NeuralNetwork class and initialize it in the constructor to nn.Flatten(). In forward, apply that flattening before feeding the input to our linear ReLU stack.

Now you can remove flat_features and directly do model(features).

Training Our Model

So we can put data through our model. But, wait, where did all those numbers in the above output come from?

Investigate the weights. Our sequential pipeline has 3 linear transformations: use print(model.linear_relu_stack). You’ll see three linear transformations and two ReLU transformations. You can index that with square brackets like any list.

Look at the first linear layer with model.linear_relu_stack[0].weighti. Find its size.

What does this represent, and where did the numbers come from? Use the PyTorch documentation.

Those are the weights for the first linear layer. They are the equivalent of the slope \(m\) in \(y = mx + b\).

What’s the size of the bias – the “intercept”, if you like – in the first linear layer?

What are the sizes of the weights and bias for the other two linear layers?

Millions, billions, and trillions: the frontier LLM models these days have over 1 trillion parameters, or weights. If you’ve heard the phrases “open weights” or “stealing the weights”, those numbers are what that refers to. “Open weight” models are those for which you can download those numbers. See the optional question at the end for links and info on downloading and using an LLM on your own computer.

How many parameters does your model have? Explain your calculation.

Now that we can pass data through our network, we can go ahead and train it! What you’re doing now is similar to this part of the tutorial.

Add a loss function and optimizer: make new variables loss_fn and optimizer. Use torch.nn.CrossEntropyLoss for the loss function and a stochastic gradient descent (SGD) optimizer from the imported optim module, initialized with the model parameters and learning rate.

Look up cross entropy loss. Why is it an appropriate loss function for our classification problem?

Next we need to implement our functions for training and validation on each epoch.

In the train_epoch() function, implement a training loop. It should iterate through the features-labels pairs in the dataset. For each batch in the dataloader:

You’ll also want to move the features and labels to the available accelerator device – that is, the GPU. Right at the top of the loop, do

features = features.to(device)
labels = labels.to(device)

Then collect some statistics. This function will return a pair of numbers: the total loss, and the accuracy proportion. (Accuracy is the proportion of samples correctly classified: the number of correct predictions divided by the total number of predictions.) You will need to sum up the loss from each batch.

For calculating accuracy: each prediction is a 10-dimensional vector representing (indirectly) probabilities. For each prediction vector, find the biggest value (the most likely digit) with torch.argmax, specifying that you want to reduce the first dimension to turn your 2-dimensional predictions output into a 1-dimensional vector representing a single-digit prediction for each sample in the batch.

You can then make an array of booleans for the predictions: if your argmax predictions are in, say, digit_predictions, just do digit_predictions == labels. You can use that directly with sum() – Python coerces False and True to 0 and 1 as you would expect.

Return the total loss and the accuracy proportion from train_epoch().

Your accuracy code should look something like this:

predictions = model(features) # run the model on the features
                              # this has dimensions [batch, num_digits]

digit_predictions = torch.argmax(predictions, dim=1) # get the index of the highest value,
                                                     # looking at dimension 1
                                                     # output dimension: [batch, 1]

does_match = preds == labels  # check where preds == labels, a 1-d tensor of booleans
num_correct = sum(does_match) # count Trues

# calculate accuracy:
num_correct / len(labels)

# or accumulate to return a total
total_num_correct += num_correct
total += len(labels)

We now can run training on a single epoch. Let’s actually train the model.

In main(), create a loop that calls train_epoch() once for each epoch. For each epoch, print out the loss and accuracy. Your output should look like this:

Epoch 0:
    training: loss=4581.649, accuracy=0.626
Epoch 1:
    training: loss=1584.772, accuracy=0.866
Epoch 2:
    training: loss=1147.298, accuracy=0.894
Epoch 3:
    training: loss=1000.3, accuracy=0.905
[ etc etc ]

The loss and accuracy are for the entire epoch, accumulated across all the batches.

So we can train the model. But we should validate it after each epoch.

In the eval_epoch() function, implement an evaluation loop. We want this to work exactly like the training loop in train_epoch() – except that we don’t change the weights and hence don’t need the optimizer. We still want to track loss, though.

This function will be identical to the training one except that it doesn’t do any backpropagation. It will track total loss and accuracy and return them just like the training function.

Update your epoch loop in main() to do a validation run each epoch, calling eval_epoch() on val, the validation dataset. Output the loss and accuracy. Your output will now look like this:

Epoch 0:
    training: loss=4456.271, accuracy=0.637
    evaluation: loss=515.065, accuracy=0.836
Epoch 1:
    training: loss=1531.308, accuracy=0.868
    evaluation: loss=317.374, accuracy=0.881
Epoch 2:
    training: loss=1139.809, accuracy=0.895
    evaluation: loss=268.164, accuracy=0.897

If you like, use the provided example matplotlib code to get scatter plots of your training and validation loss and accuracy over the epochs.

Once we have finished training, we should run our model on the test set. The test set and validation set serve very similar purposes. They are data specifically withheld from the training loop to evaluate the model. The difference is the validation set is used during training to see how the model is learning, while the test set is used at the end to see the overall performance of the model. Typically, we separate the two because the validation set is used indirectly to help training. Oftentimes, the validation set is used to determine when to stop training. When the loss stops improving for the validation set, it’s time to stop.

We need to evaluate the model on the test set. Implement the test_eval() function. Just like eval_epoch() does a bit less than train_epoch(), the test_eval() function in turn does less than eval_epoch(): it’s identical except that it doesn’t calculate any loss, just accuracy, and hence doesn’t need to a loss function.

Implement the test_eval() function. This will accumulate two lists: one of all the digit predictions, and one of all the corresponding labels, across the entire dataset.

Then find the confusion matrix and accuracy score using the functions from sklearn.metrics. Print them and include your output in your write up – something like this:

Confusion matrix:
[[ 960    0    3    1    0    4    8    1    2    1]
 [   0 1110    3    2    0    1    3    2   14    0]
 [   8    6  944   12   13    0   11   12   22    4]
 [   3    1   14  936    0   21    1   12   16    6]
 [   1    3    4    1  917    0   11    2    3   40]
 [   8    3    2   32    7  794   14    5   19    8]
 [  10    3    4    0   11    9  918    1    2    0]
 [   3    9   22    7    6    0    0  959    2   20]
 [   6    5    4   17   10   15   11   10  892    4]
 [  11    7    1    8   23    4    1   15    6  933]]
Accuracy: 0.9363

Let’s also investigate digit-wise performance. Let’s find the misclassification rate for each digit: out of all the true digit \(k\) images, what proportion were predicted incorrectly?

The confusion matrix is a list of rows, and index \(k\) in row \(k\) is the number of true \(k\)s classified correctly. Sum the rest of the entries in that row to get those classified incorrectly. Output your rates with something like:

Digit 0 misclassification rate: 20/980 = 0.0204
Digit 1 misclassification rate: 25/1135 = 0.022
Digit 2 misclassification rate: 88/1032 = 0.0853
Digit 3 misclassification rate: 74/1010 = 0.0733
Digit 4 misclassification rate: 65/982 = 0.0662
Digit 5 misclassification rate: 98/892 = 0.1099
Digit 6 misclassification rate: 40/958 = 0.0418
Digit 7 misclassification rate: 69/1028 = 0.0671
Digit 8 misclassification rate: 82/974 = 0.0842
Digit 9 misclassification rate: 76/1009 = 0.0753

Which digit(s) are the easiest – most often classified correctly? Which are the hardest? Why do you think that’s so?

Putting it all together

You now have one complete train-validate-test pipeline. You can see how accurate your model is. But maybe you can do better? It’s time to do hyperparameter tuning.

Train several models. For each model, use a different set of hyperparameters. You can use the flags given to manipulate them. In your write up, make a table with your hyperparameters and accuracy on the test set. Include something like this in your write up:

Learning rate | Accuracy
-------------   --------
0.001           0.9365
0.005           0.9781
0.9             0.9618
25              0.9999

Epochs | Accuracy
------   --------
10        .9433
15        .9781
99        .8888

(Those are, obviously, totally made-up numbers.)

Include in your experiments:

Discuss how the hyperparameters affected the model’s performance. What seemed to help? What seemed to hurt? How different were the model’s ultimate performance?

One last thing before committing and pushing your code to CSgit: make sure your code is testable.

Evaluation

I will run your submitted code with:

python hw7.py

Your code must run and perform one full train-validate-test run and output as above, including the loss and accuracy per epoch, the misclassification rates, the confusion matrix, and final test set accuracy.

Your write up must communicate your understanding of the various pieces of this neural network and how they work; the anti-goal here is that you just went through the tutorial and other online PyTorch examples and just copy-and-pasted code, without understanding what everything does and how it works – that is, it’s all just a black box to you.

Your write up, as always, must be well-written, using complete sentences, proper grammar, and be clear and easy to read.

(optional) On the subject of number of weights, just for fun: save your model to a file.