This post is in continuation of my series of building classical and most popular convolutional neural networks from scratch in PyTorch. You can see the previous post here, where we built LeNet5. In this post, we will build AlexNet, one of the most popular and earliest breakthrough algorithms in Computer Vision.
We will start by investigating and understanding the architecture of AlexNet. We will then dive straight into code by loading our dataset, CIFAR10, before jumping in by applying some pre-processing to the data. Then, we will build our AlexNet from scratch using
PyTorch and train it on our pre-processed data. The trained model will be tested on unseen (test) data for evaluation purposes at the end
AlexNet is a deep convolutional neural network, which was initially developed by Alex Krizhevsky and his colleagues back in 2012. It was designed to classify images for the ImageNet LSVRC-2010 competition where it achieved state of the art results. You can read in detail about the model in the original research paper here.
Here, I'll summarize the key takeaways about the AlexNet network. Firstly, it operated with 3-channel images that were (224x224x3) in size. It used max pooling along with ReLU activations when subsampling. The kernels used for convolutions were either 11x11, 5x5, or 3x3 while kernels used for max pooling were 3x3 in size. It classified images into 1000 classes. It also utilized multiple GPUs.
Let's start by loading and then pre-processing the data. For our purposes, we will be using the CIFAR10 dataset. The dataset consists of 60000 32x32 colour images in 10 classes, with 6000 images per class. There are 50000 training images and 10000 test images.
Here are the classes in the dataset, as well as 10 random sample images from each:
The classes are completely mutually exclusive. There is no overlap between automobiles and trucks. "Automobile" includes sedans, SUVs, and things of that sort. "Truck" includes only big trucks. Neither includes pickup trucks.
Importing the Libraries
Let's start by importing the required libraries along with defining a variable
device, so that the Notebook knows to use a GPU to train the model if it's available.
Loading the Dataset
torchvision (a helper library for computer vision tasks), we will load our dataset. This method has some helper functions that makes pre-processing pretty easy and straight-forward. Let's define the functions
get_test_loader, and then call them to load in and process our CIFAR-10 data:
Let's break down the code into bits:
- We define two functions
get_test_loaderto load train/validation and test sets respectively
- We start by defining the variable
normalizewith the mean and standard deviations of each of the channel (red, green, and blue) in the dataset. These can be calculated manually, but are also available online since CIFAR-10 is quite popular
- For our training dataset, we add the option to augment the dataset as well for more robust training and increasing the number of images as well. Note: augmentation is only applied to the training subset and not the validation and testing subsets as they are only used for evaluation purposes
- We split the training dataset into train and validation sets (90:10 ratio), and randomly subset it from the whole training set
- We specify the batch size and shuffle the dataset when loading, so that every batch has some variance in the types of labels it has. This will increase the efficacy of our eventual model
- Finally, we make use of data loaders. This might not affect the performance in the case of a small dataset like CIFAR10, but it can really impede the performance in case of large datasets and is generally considered a good practice. Data loaders allow us to iterate through the data in batches, and the data is loaded while iterating and not all at once in start into your RAM
Bring this project to life
AlexNet from Scratch
Let's start with the code first:
Let's dive into how the above code works:
- The first step to defining any neural network (whether a CNN or not) in PyTorch is to define a class that inherits
nn.Moduleas it contains many of the methods that we will need to utilize
- There are two main steps after that. First is initializing the layers that we are going to use in our CNN inside
__init__, and the other is to define the sequence in which those layers will process the image. This is defined inside the
- For the architecture itself, we first define the convolutional layers using the
nn.Conv2Dfunction with the appropriate kernel size and the input/output channels. We also apply max pooling using
nn.MaxPool2Dfunction. The nice thing about PyTorch is that we can combine the convolutional layer, activation function, and max pooling into one single layer (they will be separately applied, but it helps with organization) using the
- Then we define the fully connected layers using linear (
nn.Linear) and dropout (
nn.Dropout) along with ReLu activation function (
nn.ReLU) and combining these with the
- Finally, our last layer outputs 10 neurons which are our final predictions for the 10 classes of objects
Before training, we need to set some hyperparameters, such as the loss function and the optimizer to be used along with batch size, learning rate, and number of epochs.
We start by defining simple hyperparameters (epochs, batch size, and learning rate) and initializing our model using the number of classes as an argument, which in this case is 10 along with transferring the model to the appropriate device (CPU or GPU). Then we define our cost function as cross entropy loss and optimizer as Adam. There are a lot of choices for these, but these tend to give good results with the model and the given data. Finally, we define
total_step to keep better track of steps when training
We are ready to train our model at this point:
Let's see what the code does:
- We start by iterating through the number of epochs, and then the batches in our training data
- We convert the images and the labels according to the device we are using, i.e., GPU or CPU
- In the forward pass, we make predictions using our model and calculate loss based on those predictions and our actual labels
- Next, we do the backward pass where we actually update our weights to improve our model
- We then set the gradients to zero before every update using
- Then, we calculate the new gradients using the
- And finally, we update the weights with the
- Also, at the end of every epoch we use our validation set to calculate the accuracy of the model as well. In this case, we don't need gradients so we use
with torch.no_grad()for faster evaluation
We can see the output as follows:
As we can see, the loss is decreasing with every epoch which shows that our model is indeed learning. Note that this loss is on the training set, and if the loss is way too small it can indicate overfitting. This is why we are using the validation set as well. The accuracy seems to be increasing on validation set which indicates that there is an unlikely chance of any overfitting. Let's now test our model to see how it performs.
Now, we see how our model performs on unseen data:
Note that the code is exactly the same as for our validation purposes.
Using the model, and training for only 6 epochs, we seem to get around 78.8% accuracy on the validation set which seems good enough
Let's now conclude what we did in this article:
- We started by understanding the architecture and different kinds of layers in the AlexNet model
- Next, we loaded and pre-processed the CIFAR10 dataset using
- Then, we used
PyTorchto build our AlexNet model from scratch
- Finally, we trained and tested our model on the CIFAR10 dataset, and the model seemed to perform well on the test dataset with minimal training (6 epochs)
Using this article, you get a good introduction and hand-on learning but you'll learn much more if you extend this and see what you can do else:
- You can try using different datasets. One such dataset is CIFAR100 which is an extension of the CIFAR10 dataset with 100 classes
- You can experiment with different hyperparameters and see the best combination of them for the model
- Finally, you can try adding or removing layers from the dataset to see their impact on the capability of the model
To run this on Gradient Notebooks, simply put this URL in the advanced options boxed marked "Workspace URL." This is the GitHub repo for this article.