Image Classification using Logistic Regression in PyTorch built-ins
The Dataset which we will be using will be downloaded from [Link].
Let's get started then:-
- Firstly we will import all the required libraries:-
2. Let’s set the Hyperparameters and other constants
Ok so before we can proceed further we need to download our dataset.
For downloading the CIFAR10 dataset:
In the above line, we have used arguments. where
root='data/' : Is for saving our dataset inside the directory named
train=True : Here
trainis set to
True because certain dataset not only contains training dataset but, also contains
validation set too.
transform=transforms.ToTensor() : Now, this is a very important argument. Since PyTorch doesn’t know how to work with images we are converting the images to
3. We can see the number of images in the dataset and other details by-
4. But do we know what are the classes present in the dataset, So let’s have a look-
5. For building a good model we should have three sets of data in any dataset, Since we don’t have validation set in the CIFAR10 dataset, Let’s slice some portion from the train set itself. Also, the dataset contains additional 10,000 sets of images as a test set.
6. We will also need a data loader.
What are Data Loaders?
Data Loaders help us to load our dataset in batches and also it shuffles the batch each time it loads data in the model.
Let us have a look at one of the images from
What if we want to see a group of images, for that we’ll have to import a library:-
- Let’s have a look:
7. Now comes the main part, let us define our model:-
Also to evaluate our model, we will also need to define some functions like
evaluate etc. Let's do that -
We have also defined a fit function with which we will train our model by varying certain parameters like
epochs, lr, model, train_loader, val_loader .
Now without training, if we evaluate our model we get these results:
8. Let's train our model
For the first 60 epochs with lr=0.001, we are able to get val_acc: 0.3874
9. We can define functions to visualize our model.
10. Well, now its time to make predictions with our model. Let's Go
Our First prediction Fails, No worries lets check for 10 such predictions.
Well we can see that in some cases the
ship is predicted as
cat and what not 🤣 But though with Logistic regression we are able to get approx. 40% accuracy that's not that bad.
11. Can we Increase our accuracy to more 80% or more than that 🤔? Well, have you heard of the Feed-Forward Neural network? If not than soon I’ll be working on the same dataset but with a slightly different model and approach.
Since, you have made it till here then you can have a look at the entire notebook. Click