Making A CNN Using PyTorch Using TorchVision

Let start with importing libraries into our Jupyter notebook. We will be using Google Colaboratory for this. We will be using CIFAR 10 dataset for this purpose. CIFAR 10 has images in size 32 x 32 x 3 with ten classes. 

Importing libraries

Let’s add some variables to store the workers and batch size. The valid size state the x per cent of the train set to be in use as validation. 

While this is going on, we need to convert our data (images) to be store in Tensors for this, and we are going to use transform.Compose. We will also normalise our data to fine-tune our parameters.

Downloading our dataset

We are done with pre-processing is dealt with which we will download our CIFAR10 dataset. TorchVision.dataset has this dataset. You can also look into more datasets. Google Colab downloads the dataset in a matter of seconds,

 so you don’t need to worry about it.

Next step is making loaders of our data which are shuffled and random.

Now, as our data part is complete, we can move forward to making a model.

CNN architecture

Let us import neural network from PyTorch and make our first CNN model using it.

Let’s have three convolutional layers, followed by a max-pooling layer each. Since the images have a size 32 x 32 x 3, the input to first convolutional layer will be the same. The output is then fed to 2 fully connected layers and followed by dropout with p = 0.25

Let us see our model.

We will use  Cross entropy function loss and stoichiometric gradient descent as the optimiser. 

Remember to look at how the training and validation loss decreases over time; if the validation loss ever increases, it indicates possible overfitting. We save the model when validation loss drops to reduce overfitting.

Testing the model

Our model is trained and loaded. We can start with the test set.

We can see we got our test accuracy as 75% which is quite good considering we build our own CNN. but to increase this, we could have use transfer learning models like ResNet, AlexNet, etc.

written by: Mrunmay Shelar

Reviewed By: Savya Sachi

If you are Interested In Machine Learning You Can Check Machine Learning Internship Program
Also Check Other Technical And Non Technical Internship Programs

Leave a Comment

Your email address will not be published. Required fields are marked *