Lab #10 - Introduction to PyTorch¶

PyTorch is an open-source machine learning framework developed by AI researchers at Meta. The torch library is not pre-installed in the Anaconda distribution, so you must add the torch and torchvision libraries yourself. You can install them via the Anaconda enironment user interface, or using the command: pip install torch torchvision

If you've installed the torch library correctly, the following code should print a 3x2 tensor of zeros:

In [1]:
import torch
import torchvision
x = torch.zeros(3, 2)
print(x)
tensor([[0., 0.],
        [0., 0.],
        [0., 0.]])

Part 1 - Tensors and Automatic Differentiation¶

Deep learning libraries, including torch, rely on a data structure known as a tensor, which is similar to a multi-dimensional numpy array. Below is an example of a $2 \times 3$ tensor, which is just a matrix:

In [2]:
x = torch.tensor([[1.,2.,3.], [4.,5.,6.]])
print(x.shape)
torch.Size([2, 3])

Tensors enable image, text, and time-series data to be stored in a way that preserves spatial and temporal relationships. The code below reads the reads the flattened form of 1000 examples from an image data set known as Fashion MNIST, which consists of 28x28 pixel grayscale images of 10 different types of fashion items:

In [3]:
### Read flattened, processed data
import pandas as pd
fash_mnist = pd.read_csv("https://remiller1450.github.io/data/fashion_mnist_train.csv")

## Train-test split
from sklearn.model_selection import train_test_split
train_fash, test_fash = train_test_split(fash_mnist, test_size=0.1, random_state=5)

### Separate the label column (outcome)
train_y = train_fash['y']
train_X = train_fash.drop(['y'], axis=1)
test_y = test_fash['y']
test_X = test_fash.drop(['y'], axis=1)

Since each training example is a $28 \times 28$ image, it is logical to store the data using a (900, 28, 28) tensor where the first dimension represents a training example, and the second and third correspond to the pixel length and width. This structure is preferred over the flattened form because it places adjacent pixels next to each other.

To provide additional context, one of these images (the 9th example) is displayed below. You can see how this example is stored in the tensor by printing the corresponding 28 x 28 tensor slice.

In [4]:
### Convert to numpy array then reshape to 900 by 28 by 28
mnist_unflattened = train_X.to_numpy()
mnist_unflattened = mnist_unflattened.reshape(900,28,28)

## Convert to tensor
mnist_tensor = torch.from_numpy(mnist_unflattened)

## Check shape and print the first image
print(mnist_tensor[0,:,:].shape)
import matplotlib.pyplot as plt
plt.imshow(mnist_unflattened[8,:,:], cmap="gray")
plt.axis("off")
plt.show()
# print(mnist_tensor[8,:,:]) ## Print if you'd like to see the tensor format
torch.Size([28, 28])
No description has been provided for this image

While tensors seem similar to numpy arrays, their defining feature is an ability to track how certain calculations are performed, specifically the computation of gradients.

Suppose we define $z = x^2$ and want to compute $\tfrac{\partial z}{\partial x}$, which we know should be $2x$. PyTorch can do this automatically:

In [5]:
## Value of x to differentiate at
x = torch.tensor(3.0, requires_grad=True)

## Function to differentiate
z = x**2

## Gradient
z.backward()
print(x.grad)
tensor(6.)

In this example we found the gradient of $z$ at the value $x=3.0$.

Automatic differentiation is extremely important when training a neural network because even a relatively simple model architecture might involve thousands (or even millions) of partial derivatives. PyTorch's automatic differentiation allows us to use gradient descent to optimize the model's weights without needing to calculate any gradients ourselves when we setup the model's architecture.

To show how automatic differentiation works with nested functions, let's modify our example by introducing a linear combination of weights followed by activation via the ReLU function:

In [6]:
## Nested functions of x
x = torch.tensor(3.0, requires_grad=True)
z = 2*x + 1
a = torch.relu(z)

## Gradient
a.backward()
print(x.grad)
tensor(2.)

Notice that that for $x=3.0$, we have $\tfrac{\partial a}{\partial z} = 1$ and $\tfrac{\partial z}{\partial x} = 2$, thus $\tfrac{\partial a}{\partial x} = 2$

PyTorch generalizes this idea by keeping track of sequential computations involving a tensor created with the argument requires_grad=True using computational graph. In our example the graph looks like: $$ x \rightarrow z = 3x + 1 \rightarrow a = ReLU(z)$$

In general, a neural network looks like: $$ \mathbf{x} \rightarrow \mathbf{z}^{(1)} \rightarrow \mathbf{a}^{(1)} \rightarrow \mathbf{z}^{(2)} \rightarrow \mathbf{a}^{(2)} \rightarrow \ldots \rightarrow Cost$$

This graph becomes very large when the network is deep (uses many hidden layers), but the core idea does not change. By using cost.backward(), PyTorch will compute all of the partial derivatives so that they can be used in a gradient descent update.

In the previous example, our computational graph contained only a single input $x$, a single linear transformation $z$, and a single activation $a$. When classifying Fashion MNIST images, the same idea applies, but each image contains $28 \times 28 = 784$ pixel values rather than a single input. A neural network combines these pixel values through many linear transformations and activation functions before ultimately producing a classification score for each of the 10 clothing categories. During training, PyTorch uses backpropagation and automatic differentiation to compute the gradient of the cost function with respect to every weight and bias in this much larger computational graph.

Question #1:

  • Part A: Consider the computational graph associated with $z = 2x - 1$, $a = ReLU(z)$, and $y=a^3$. Use chain rule to compute $\tfrac{\partial y}{\partial x}$ for a scalar value of $x$.
  • Part B: Evaluate the gradient you calculated in Part A at $x=4$.
  • Part C: Use PyTorch and the .backward() method to verify your answer to Part B.

Part 2 - Network Architecture in PyTorch¶

At this point we're ready to translate the neural network concepts we've seen "on paper" into PyTorch. The following table summarizes the key quantities and operations, and introduces their associated PyTorch function:

Mathematical Notation Interpretation PyTorch Implementation
$\mathbf{x}$ Vector of inputs Tensor
$\mathbf{z}^{(k)}$ Pre-activation values from a linear combination nn.Linear()
$\mathbf{a}^{(k)}$ Activated outputs passed to the next layer nn.ReLU()
$\text{Cost}$ Cost function minimized during training nn.CrossEntropyLoss()
$\nabla \text{Cost}$ Gradient of the cost function cost.backward()
$\hat{\mathbf{w}}$ Model weight estimates net.parameters()
Gradient Descent Update the model parameters using gradients optimizer.step()

To set up our own neural network architecture, we'll create our own class named my_net as a subclass of nn.Module. This class contains two important components:

  1. A constructor that defines the pieces of the model's architecture using building blocks from nn.Module.
  2. A forward function that organizes the network architecture by defining how an input tensor is forward propagated through the network.

The simple neural network created below is intended to work on the Fashion MNIST data. It's important to recognize that this dataset contains 28 x 28 pixel images with no color channel, so the network's expected input is an $n$ by 28 by 28 tensor (hence the first layer begins with $28*28 = 784$ input features).

In [7]:
from torch import nn

class my_net(nn.Module):
    ## Constructor
    def __init__(self):
        super(my_net, self).__init__()
        
        ## define flattening layer
        self.flatten = nn.Flatten()
        
        ## define stack of linear-relu layers
        self.linear_relu_stack = nn.Sequential(
            nn.Linear(784, 512),
            nn.ReLU(),
            nn.Linear(512, 512),
            nn.ReLU(),
            nn.Linear(512, 10),
        )
    
    ## Function to generate predictions
    def forward(self, x):
        
        ## First flatten x (note the capitalization, this is flatten() as defined above)
        x = self.flatten(x)
        
        ## Then pass flattened x to "linear_relu_stack()" (defined above)
        scores = self.linear_relu_stack(x)
        
        return scores

Question #2: For this question you should reference the neural network architecture defined above.

  • Part A: When a single $28 \times 28$ image is passed into the network, how many neurons are used to represent it in the first hidden layer?
  • Part B: How many weights and biases are contained in the network? Show your calculation. You may opt to verify using the .parameters() method.
  • Part C: The last layer of the linear-relu stack produces a 10-dimensional vector as its output. Why is this important for the Fashion MNIST classification task?

Part 3 - Training the Network¶

To estimate the model's weights and biases using the training data, we need to begin by defining the following tuning parameters:

  • Epochs - how many times the optimization algorithm should iterate over the training dataset
  • Batch Size - how many observations should be used in each update iteration
  • Learning Rate - how aggressively should the model's weights/biases change at each iteration

We also must specify an appropriate cost function and an optimization algorithm (that is compatible with the chosen cost function).

In [8]:
## Training parameters
epochs = 200
lrate = 0.01
bsize = 100

## Cost Function (cross entropy loss since the outcome is categorical)
cost_fn = nn.CrossEntropyLoss()

## Initialize the model
net = my_net()

## Optimizer (Stochastic Gradient Descent)
optimizer = torch.optim.SGD(net.parameters(), lr=lrate)

To help facilitate the passing of training examples into the network during learning, we'll use the DataLoader utilities that are part of PyTorch:

In [9]:
from torch.utils.data import DataLoader, TensorDataset
y_tensor = torch.Tensor(train_y)
train_loader = DataLoader(TensorDataset(mnist_tensor.type(torch.FloatTensor), y_tensor.type(torch.LongTensor)), batch_size=bsize)

This code creates a TensorDataset object that contains a tensor of predictors (which was stored in mnist_tensor) and a tensor of outcomes (y_tensor). Then, this TensorDataset object is used to create a DataLoader object that can be used to pass batches of data into the network.

The code provided below will train our network, which we named net, on the data contained train_loader by using the iterable nature of DataLoader objects to streamline the process:

In [10]:
import numpy as np

## Initial values for cost tracking
track_cost = np.zeros(epochs)
cur_cost = 0.0

## Loop through the data
for epoch in range(epochs):
    
    cur_cost = 0.0
    correct = 0.0
    
    ## train_loader is iterable and knows the batch size
    for inputs, labels in train_loader:
        
        ## Clear the gradients accumulated from the previous batch 
        optimizer.zero_grad()
        
        ## Provide the input tensor into the network to get outputs
        outputs = net(inputs)
        
        ## Calculate the cost for the current batch
        ## nn.Softmax is used because net outputs prediction scores and our cost function expects probabilities and labels
        cost = cost_fn(nn.Softmax(dim=1)(outputs), labels)
        
        ## Calculate the gradient
        cost.backward()
        
        ## Update the model parameters using the gradient
        optimizer.step()
        
        ## Track the current cost (accumulating across batches)
        cur_cost += cost.item()
    
    ## Store the accumulated cost at each epoch
    track_cost[epoch] = cur_cost
    # print(f"Epoch: {epoch} Cost: {cur_cost}") ## Uncomment this if you want printed updates

We can graph the cost by epoch to see if the weight estimates in our network have converged. Because we are using batches of data (stochastic gradient descent), we're looking for the cost to flatten out (with some noise).

In [11]:
import matplotlib.pyplot as plt
plt.plot(np.linspace(0, epochs, epochs), track_cost)
plt.show()
No description has been provided for this image

Question #3: The following questions involve the example training code provided in this section.

  • Part A: Consider the training loop provided above. In your own words, briefly the purpose of optimizer.zero_grad(), cost.backward(), and optimizer.step(). Do these commands need to be executed in exactly this order? Explain your reasoning.
  • Part B: Based upon the cost curve shown above, do you believe the model is still learning from the training data? Briefly explain your reasoning.
  • Part C: In the lab's example the batch size was 100 and the learning rate was 0.01. How would you expect the cost curve to change if the batch size remained 100 but the learning rate was increased to 0.05? Try to reason your way to an answer before testing it empirically.
  • Part D: How would you expect the cost curve to change if the batch size was decreased to 10 but the learning rate remained 0.01? Try to reason your way to an answer before testing it empirically.
  • Part E: The training set contains 900 images. When 100 is used as the batch size, how many gradient descent updates occur during a single training epoch?

Part 4 - Assessing Performance¶

Next, we'll calculate the classification accuracy for the training set:

In [12]:
## Initialize objects for counting correct/total 
correct = 0
total = 0

# Specify no changes to the gradient in the subsequent steps (since we're not using these data for training)
with torch.no_grad():
    for data in train_loader:
        # Current batch of data
        images, labels = data
        
        # pass each batch into the network
        outputs = net(images)
        
        # the class with the maximum score is what we choose as prediction
        _, predicted = torch.max(outputs.data, 1)
        
        # add size of the current batch
        total += labels.size(0)
        
        # add the number of correct predictions in the current batch
        correct += (predicted == labels).sum().item()

## Calculate and print the proportion correct
print(correct/total)
0.8844444444444445

The model's accuracy score on the training data is reasonable and shows that the model has learned (since we'd expect only 10% accuracy by chance); however, it might reflect the network overfitting to the training data, so we're more interested in the network's performance on the test data.

The code below reformats our test data into a TensorDataset, then puts into its own DataLoader object:

In [13]:
## Make test outcomes into a tensor
test_y_tensor = torch.Tensor(test_y.to_numpy())

### Convert to numpy array then reshape
test_unflattened = test_X.to_numpy().reshape(len(test_y),28,28)

## Convert test images into a tensor
test_tensor = torch.from_numpy(test_unflattened)

## Combine X and y tensors into a TensorDataset and DataLoader
test_loader = DataLoader(TensorDataset(test_tensor.type(torch.FloatTensor), test_y_tensor.type(torch.LongTensor)), batch_size=bsize)

We can now use test_loader in the same evaluation loop we previously used:

In [14]:
## Repeat evaluation loop using the test data
correct = 0
total = 0
with torch.no_grad():
    for data in test_loader:
        images, labels = data
        outputs = net(images)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()
print(correct/total)
0.75

A few comments:

  1. In theory you could use cross-validation to obtain an unbiased estimate of your network's performance on new data, and cross-validation could also help you choose aspects of the model architecture. However, $k$-fold cross-validation is computationally demanding in this context since it requires $k$ neural networks be trained.
  2. In many applications, a single validation set is used, and performance on the held out data is assessed at each training epoch to determine when overfitting occurs. We will do this ourselves in a future lab.
  3. Because neural networks contain such a large number of parameters, training success can be sensitive to the initial weights, which are often determined by the random state that is used. It can sometimes be beneficial to change the initial weights by changing the random state if gradient descent doesn't seem to be making progress towards improving the cost.

Part 5 - Application¶

The zipped folder at this link contains 50 images of cats and 100 images of chihuahua breed dogs.

I have resized these images for you, so you won't need to worry about their dimensions. My resizing code was adapted from this StackOverflow answer if you happen to encounter a need to resize images on your project.

The code provided below will load all of these images into a numpy array, creating a vector of labels at the same time:

In [15]:
import os
import matplotlib.pyplot as plt
path = 'OneDrive - Grinnell College/Documents/cats_dogs/'
img_names = os.listdir(path)

images = np.empty(shape = (150, 64, 64, 3))
labels = np.empty(len(img_names), dtype=int)
for idx, name in enumerate(img_names):
    img_name = path + name
    image = plt.imread(img_name)
    images[idx] = image
    if "cat" in name.lower():
        labels[idx] = 1
    else:
        labels[idx] = 0

To confirm the data have been loaded correctly we can display one of the images:

In [16]:
import matplotlib.pyplot as plt
plt.imshow(images[10].astype('uint8'))
Out[16]:
<matplotlib.image.AxesImage at 0x172e3a2f9d0>
No description has been provided for this image

Note that we had to cast the pixel intensities to integers so that they are properly handled by imshow.

Question #4:

  • Part A: Perform a 75-25 training-testing split on the data described above that is stored in the objects images and labels. See the second example in the documentation if you've never used this function when the outcome/target variable has already been separated from the predictors.
  • Part B: Create a neural network model containing 3 hidden layers. You may choose the number of neurons contained in each layer, but you should be careful to specify a valid architecture. Your network should begin by flattening the input tensor before it is supplied to the hidden layers. Each layer, with the exception of the final output layer, should be followed by ReLU activation function.
  • Part C: Convert the training and testing data from Part A into properly formated tensors that are stored as DataLoader objects. Use a mini-batch size of your choice.
  • Part D: Train your network for 10 epochs, applying softmax to the network output and using the cross entropy cost function. You should try to manipulate the learning rate and network architecture to get the network to learn something from the training (ie: get the cost to improve), but you shouldn't be disappointed if you cannot get it to do so (since this is a miniscule amount of data for this type of application). If your code properly updates the network's weights and tracks the cost you will receive credit for this question.
  • Part E: Evaluate your network on the test data and print the classifcation accuracy.
  • Part F: Calculate the total number of trainable parameters in your network and compare this with the number of training images in each class. Based upon this comparison, do you think overfitting is a concern? Why else might an ordinary neural network struggle with these data?

Note: Fully connected neural networks tend to be poorly suited for unprocessed image data, so you should expect your network to perform around the level of random guessing (approximately 67% accuracy).