Lab 11 - Convolutional Neural Nets¶

This lab covers the integration of convolutional layers into a neural network using PyTorch.

Lab examples will continue using the Fashion MNIST data, and the lab will close using the cats vs. dogs data from the previous lab.

In [1]:
import torch
import torchvision
import numpy as np

### 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)

### 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)
train_X = torch.reshape(mnist_tensor, [900,1,28,28])

Part 1 - CNN Fundamentals¶

Convolutional Layers¶

Convolutional neural networks can be viewed as an extension of the basic network architectures discussed in our previous lab involving hidden layers that perform new types of operations. The most important of these are convolutional layers, which we will implement using the Conv2d building block in torch.

The example below demonstrates the four essential arguments of Conv2d on a randomly generated tensor whose dimensions can be taken to reflect a single 7x7 image with 3 color channels:

In [2]:
## Create random tensor to represent a 7x7 image with 3 channels
random_tensor = torch.rand(1,3,7,7)

## Use random_tensor as input into Conv2d
from torch import nn
trial_net = nn.Conv2d(in_channels=3, out_channels=4, kernel_size=3, stride=1)
trial_output = trial_net(random_tensor)

## Check output shape
print(trial_output.shape)

## Check weights shape
print(trial_net.weight.shape)

## Check bias shape
print(trial_net.bias.shape)
torch.Size([1, 4, 5, 5])
torch.Size([4, 3, 3, 3])
torch.Size([4])

This example applied a set of 3x3 convolution kernels using a stride length of 1 to our 1x3x7x7 input tensor. A few things to note:

  • in_channels must match the number of channels present in the input (generally this is the second dimension of the input tensor).
  • out_channels determines the number of feature maps (output channels) to be produced by the layer. Specifying more output channels will increase the number of hidden features learned in this layer of the network.
  • kernel_size determines the size of the filter, with kernel_size=3 indicating a 3x3 filter size. Note that you could provide a non-square filter by supplying a tuple, such as (2,3).

Summarizing this operation, the 1x3x7x7 input tensor was convolved into 1x4x5x5 output tensor (note that we did not use any padding).

Because the input had 3 channels and we requested 4 output channels, our model must estimate weights for 12 different 3x3 kernels, and 4 biases (1 per output channel). To better understand the role of these weights and biases, consider the following:

  • Our first set of three kernels, or the weights stored in the dimension [1,:,:] of trial_net.weight, act separately on the input channels to contribute, with the bias [1], to the first output channel.
  • The second set of three kernels, or the weights at [2,:,:], act separately on the input channels to contribute, with the bias [2], to the second output channel.

The mechanics of this layer are displayed visually in the .gif below:

In [3]:
## Sorry, this is the easiest way to display a gif in HTML generated by a Python notebook
from IPython.display import HTML
HTML('<img src="https://miro.medium.com/v2/resize:fit:1400/1*ubRrYAZJUlCcqg7WoKjLgQ.gif">')
Out[3]:
No description has been provided for this image

Printed below are the first set of weights:

In [4]:
trial_net.weight[1,:,:]
Out[4]:
tensor([[[-0.1609,  0.1105, -0.0272],
         [ 0.0510,  0.0207,  0.1864],
         [-0.0815,  0.1707, -0.0326]],

        [[ 0.1632,  0.1260, -0.1476],
         [-0.0911,  0.0227,  0.0422],
         [ 0.1720,  0.1171, -0.1813]],

        [[-0.0547, -0.0869,  0.1550],
         [ 0.0227,  0.1829, -0.1135],
         [-0.1053, -0.1391,  0.0338]]], grad_fn=<SelectBackward0>)

Question #1: Suppose a training example from the Fashion MNIST data (introduced in the previous lab) is given as the input to a convolutional layer created using Conv2d involving convolution kernels of size 4x4 and stride of 2.

  • Part A - If the number of output channels is specified as 5, how many parameters (weights and biases) are used in this layer? Briefly explain.
  • Part B - What are the dimensions of each feature map produced by this layer? Briefly explain.

Padding and Pooling¶

The previous convolution operation produced a 1x4x5x5 output tensor, or four features maps each having dimensions $5 \times 5$. Notice that the dimensions of these feature maps are less than the original data because the 3x3 kernels did not extend beyond the edges of the 7x7 image.

Padding adds additional zeros around the border of the input (image or feature map) before convolution. It can be applied using the padding argument in Conv2d:

In [5]:
## Same Conv2d args but with 1 level of padding
padded_net = nn.Conv2d(in_channels=3,out_channels=4,kernel_size=3,stride=1,padding=1)
padded_output = padded_net(random_tensor)

print(padded_output.shape)
torch.Size([1, 4, 7, 7])

Because we've added a one-pixel border to each input image we now have $7 \times 7$ feature maps, as each kernel has an extra position it can cover on each side of the image.

After convolution, a common next step is to apply pooling, which is intended to reduce the spatial dimensions of the feature maps while retaining the most important information.

Below is an example of $2 \times 2$ max pooling:

In [6]:
## Use previous output in a 2x2 max pooling layer
pool_layer = nn.MaxPool2d(kernel_size=2, stride=2)
pooled_output = pool_layer(trial_output)

print(pooled_output.shape)
torch.Size([1, 4, 2, 2])

Question #2: Suppose an image from the Fashion MNIST dataset is passed into the following layer: nn.Conv2d(in_channels=1,out_channels=8,kernel_size=5,stride=1,padding=2)

  • Part A: What are the dimensions of the output? Feel free to test an example.
  • Part B: Suppose the feature maps produced by this layer are given to a $2 \times 2$ max pooling layer. What will resulting dimensions be?

Part 2 - Building a CNN¶

Using the building blocks introduced in Part 1 (and a few things from our previous lab), we can create our own CNN architecture:

In [7]:
from torch import nn

class my_net(nn.Module):
    
    ## Constructor commands
    def __init__(self):
        super(my_net, self).__init__()
        
        ## Define architecture
        self.conv_stack = nn.Sequential(
            nn.Conv2d(1,10,4,1),
            nn.ReLU(),
            nn.MaxPool2d(2,2),
            nn.Conv2d(10,30,2,1),
            nn.ReLU(),
            nn.MaxPool2d(2,2),
            nn.Flatten(),
            nn.Linear(750, 250),
            nn.ReLU(),
            nn.Linear(250, 10)
        )
    
    ## Function to generate predictions
    def forward(self, x):
        scores = self.conv_stack(x)
        return scores

Notice how this architecture stacks a sequence of Conv2d, ReLU, MaxPool2d blocks before flattening and introducing linear layers that learn how to make predictions using the features learned by the convolutional layers.

We can calculate the total number of trainable parameters in the network using the following:

In [8]:
## Intialize the model
net = my_net()

## Sum the number of elements in the parameters that require gradients
sum(p.numel() for p in net.parameters() if p.requires_grad)
Out[8]:
191660

We can train this model using the process introduced in our previous lab. Below we set up training parameters:

In [9]:
## Hyperparms
epochs = 200
lrate = 0.025
bsize = 100

## For reproduction purposes 
torch.manual_seed(7)

## Cost Function
cost_fn = nn.CrossEntropyLoss()

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

## Make DataLoader for training batches
from torch.utils.data import DataLoader, TensorDataset
y_tensor = torch.Tensor(train_y)
train_loader = DataLoader(TensorDataset(train_X.type(torch.FloatTensor), y_tensor.type(torch.LongTensor)), 
                          batch_size=bsize, shuffle=True)

We've now set up everything we'll need to train the network. We'll do so using the same training loop from before:

In [10]:
## 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

Below we plot the learning curve:

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

Notice how the model has not learned anything new in several epochs. In a real application we'd want to monitoring performance on a held out validation set, but for these data we'll just go ahead and evaluate performance on the test set:

In [17]:
## 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),1,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)

## Repeat evaluation loop suing 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.79

For reference, the fully connected neural network from our previous lab achieved around 75% accuracy on the test set, so we did slightly better here.

Question #3: These questions pertain to the CNN architecture and training performed in this section of the lab.

  • Part A: For a single training example from the Fashion MNIST data, complete the dimensions table below as the image passes through this CNN:
Layer Output Dimensions
Conv2d(1,10,4,1)
ReLU()
MaxPool2d(2,2)
Conv2d(10,30,2,1)
ReLU()
MaxPool2d(2,2)
Flatten()
  • Part B: Where the does the value 750 in the first linear layer come from? Could this value be changed without also modifying any of the earlier layers?
  • Part C: Which portion of the network contains the most trainable parameters (weights and biases)?
  • Part D: The fully connected neural network in our previous lab had approximately 670,000 trainable parameters. Report the number of trainable parameters in this CNN as a fraction of 670,000. In your own words, briefly explain how the CNN was able to achieve better performance using far fewer parameters.

Part 3 - Data Augmentation¶

Convolutional neural networks are robust to the precise positions of hidden features within an image, so a common strategy used during network training is data augmentation, or the random alteration of training images in ways that preserve their meaning in order to provide the network with a larger and more diverse set of training examples.

For example, we might augment the Fashion MNIST data by randomly moving the location of an object via an affine transformation, and we might also think that adding a little "fuzz" or blurring to an image might provide additional variety without fundamental altering what each image means.

Below we define a set of data augmentation transformations that we can later use in our training loop:

In [18]:
## Compose the transformations
from torchvision import transforms
data_transforms = transforms.Compose([
        transforms.GaussianBlur(kernel_size=(5,5), sigma=(0.1, 5)),
        transforms.RandomAffine(degrees=10,translate=(0.05,0.05))
])

Note that the kernel argument defines the dimensions of the Gaussian kernel, and the two values used in the sigma argument represent the min and max of the range from which the standard deviation of the random noise will randomly be sampled from for each kernel. This link provides a more detailed (and relatively non-technical) explanation of Gaussian blurring.

Now let's utilize these data augmentation transformations on each batch of images during our training loop:

In [19]:
## Re-run the training loop, notice the new data_transforms() command
track_cost = np.zeros(epochs)
cur_cost = 0.0

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:
        
        ## Transform the input data using our data augmentation strategies
        inputs = data_transforms(inputs)
        
        ## Same as before
        optimizer.zero_grad()
        outputs = net(inputs)
        cost = cost_fn(nn.Softmax(dim=1)(outputs), labels)
        cost.backward()
        optimizer.step()
        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
    
plt.plot(np.linspace(0, epochs, epochs), track_cost)
plt.show()
No description has been provided for this image
In [20]:
## Repeat evaluation using the test data and model trained using data augmentation
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.81

Part 4 - Application¶

For this application you will revisit the cats vs. dogs image data stored in the zipped folder at this link. Recall that this folder includes 50 images of cats and 100 images of dogs (chihuahua breed). In our previous work with these data, it was immensely challenging to get a neural network to learn anything meaningful. This time, using the new methods introduced in this lab, we'll aim to build a neural network that at least learns something from the images.

Question #4:

  • Part A - Similar to work from our previous lab, create objects to store these images and class labels and perform a 75-25 train-test split using random_state=5. Next, reorganize the dimensions of the image tensor to follow the conventional format of (N images, C color channels, w pixels, h pixels).
  • Part B - Create a composition of data transformations that apply Gaussian blur, random horizontal flipping, and random rotation (between 0 and 180 degrees). You may consult the link at the end of the previous section for information on how to implement random rotation.
  • Part C - Define a network architecture containing the following layers (in the order provided below). You should pay careful attention to inputs of each layer to ensure they are appropriate for the tensors we're using to store our dog/cat images.
    • A convolutional layer of 3x3 kernels with a stride of 1 and 8 output channels
    • ReLU
    • Max pooling with 2x2 kernels
    • A convolutional layer of 2x2 kernels with a stride of 1 and 16 output channels
    • ReLU
    • Max pooling with 2x2 kernels
    • Flattening
    • A fully connected linear layer with 200 ouputs
    • ReLU
    • A linear layer that generates 2 outputs (corresponding to the class labels).
  • Part D - Train the network using stochastic gradient descent on batches of 28 images that are augmented using the transformations you defined in Part B. For your reference, using a learning rate of 0.001 and training for 300 epochs with weights initialized under torch.manual_seed(3) I was able to achieve around 73% classification accuracy on the training data (which is better than the 66% you'd expect from random guessing), as well as 81% classification accuracy on the test data.
  • Part E - Once you've found a network in Part D that learns something from the training data, evaluate its performance (classification accuracy) on the test data.

Note: Because this dataset is very small, classification accuracy will vary substantially across different random initializations and training runs, so you shouldn't expect to exactly match the numerical results mentioned in Question 4.