Image Classifier with Deep learning
Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you’d use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications.
In this project, you’ll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice you’d train this classifier, then export it for use in your application. We’ll be using this dataset of 102 flower categories, you can see a few examples below.
The project is broken down into multiple steps:
- Load and preprocess the image dataset
- Train the image classifier on your dataset
- Use the trained classifier to predict image content
We’ll lead you through each part which you’ll implement in Python.
When you’ve completed this project, you’ll have an application that can be trained on any set of labeled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. For example, imagine an app where you take a picture of a car, it tells you what the make and model is, then looks up information about it. Go build your own dataset and make something new.
First up is importing the packages you’ll need. It’s good practice to keep all the imports at the beginning of your code. As you work through this notebook and find you need to import a package, make sure to add the import up here.
1 | # Imports here |
Load the data
Here you’ll use torchvision
to load the data (documentation). The data should be included alongside this notebook, otherwise you can download it here. The dataset is split into three parts, training, validation, and testing. For the training, you’ll want to apply transformations such as random scaling, cropping, and flipping. This will help the network generalize leading to better performance. You’ll also need to make sure the input data is resized to 224x224 pixels as required by the pre-trained networks.
The validation and testing sets are used to measure the model’s performance on data it hasn’t seen yet. For this you don’t want any scaling or rotation transformations, but you’ll need to resize then crop the images to the appropriate size.
The pre-trained networks you’ll use were trained on the ImageNet dataset where each color channel was normalized separately. For all three sets you’ll need to normalize the means and standard deviations of the images to what the network expects. For the means, it’s [0.485, 0.456, 0.406]
and for the standard deviations [0.229, 0.224, 0.225]
, calculated from the ImageNet images. These values will shift each color channel to be centered at 0 and range from -1 to 1.
1 | data_dir = 'flowers' |
1 | # TODO: Define your transforms for the training, validation, and testing sets |
Label mapping
You’ll also need to load in a mapping from category label to category name. You can find this in the file cat_to_name.json
. It’s a JSON object which you can read in with the json
module. This will give you a dictionary mapping the integer encoded categories to the actual names of the flowers.
1 |
|
Building and training the classifier
Now that the data is ready, it’s time to build and train the classifier. As usual, you should use one of the pretrained models from torchvision.models
to get the image features. Build and train a new feed-forward classifier using those features.
We’re going to leave this part up to you. Refer to the rubric for guidance on successfully completing this section. Things you’ll need to do:
- Load a pre-trained network (If you need a starting point, the VGG networks work great and are straightforward to use)
- Define a new, untrained feed-forward network as a classifier, using ReLU activations and dropout
- Train the classifier layers using backpropagation using the pre-trained network to get the features
- Track the loss and accuracy on the validation set to determine the best hyperparameters
We’ve left a cell open for you below, but use as many as you need. Our advice is to break the problem up into smaller parts you can run separately. Check that each part is doing what you expect, then move on to the next. You’ll likely find that as you work through each part, you’ll need to go back and modify your previous code. This is totally normal!
When training make sure you’re updating only the weights of the feed-forward network. You should be able to get the validation accuracy above 70% if you build everything right. Make sure to try different hyperparameters (learning rate, units in the classifier, epochs, etc) to find the best model. Save those hyperparameters to use as default values in the next part of the project.
One last important tip if you’re using the workspace to run your code: To avoid having your workspace disconnect during the long-running tasks in this notebook, please read in the earlier page in this lesson called Intro to
GPU Workspaces about Keeping Your Session Active. You’ll want to include code from the workspace_utils.py module.
Note for Workspace users: If your network is over 1 GB when saved as a checkpoint, there might be issues with saving backups in your workspace. Typically this happens with wide dense layers after the convolutional layers. If your saved checkpoint is larger than 1 GB (you can open a terminal and check with ls -lh
), you should reduce the size of your hidden layers and train again.
1 | device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
VGG(
(features): Sequential(
(0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(1): ReLU(inplace=True)
(2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(3): ReLU(inplace=True)
(4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
(5): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(6): ReLU(inplace=True)
(7): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(8): ReLU(inplace=True)
(9): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
(10): Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(11): ReLU(inplace=True)
(12): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(13): ReLU(inplace=True)
(14): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(15): ReLU(inplace=True)
(16): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(17): ReLU(inplace=True)
(18): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
(19): Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(20): ReLU(inplace=True)
(21): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(22): ReLU(inplace=True)
(23): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(24): ReLU(inplace=True)
(25): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(26): ReLU(inplace=True)
(27): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
(28): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(29): ReLU(inplace=True)
(30): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(31): ReLU(inplace=True)
(32): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(33): ReLU(inplace=True)
(34): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(35): ReLU(inplace=True)
(36): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
)
(avgpool): AdaptiveAvgPool2d(output_size=(7, 7))
(classifier): Sequential(
(0): Linear(in_features=25088, out_features=2048, bias=True)
(1): ReLU()
(2): Dropout(p=0.25, inplace=False)
(3): Linear(in_features=2048, out_features=102, bias=True)
(4): LogSoftmax()
)
)
1 | model.to(device) |
1 | epochs = 8 |
Epoch: 1/8.. Train loss: 3.569.. Valid loss: 1.455.. Valid accuracy: 0.612
Epoch: 1/8.. Train loss: 1.689.. Valid loss: 0.859.. Valid accuracy: 0.768
Epoch: 2/8.. Train loss: 1.296.. Valid loss: 0.759.. Valid accuracy: 0.784
Epoch: 2/8.. Train loss: 1.181.. Valid loss: 0.720.. Valid accuracy: 0.800
Epoch: 3/8.. Train loss: 1.054.. Valid loss: 0.655.. Valid accuracy: 0.809
Epoch: 3/8.. Train loss: 1.020.. Valid loss: 0.517.. Valid accuracy: 0.839
Epoch: 4/8.. Train loss: 0.988.. Valid loss: 0.487.. Valid accuracy: 0.850
Epoch: 4/8.. Train loss: 0.932.. Valid loss: 0.596.. Valid accuracy: 0.832
Epoch: 5/8.. Train loss: 0.893.. Valid loss: 0.517.. Valid accuracy: 0.857
Epoch: 5/8.. Train loss: 0.854.. Valid loss: 0.493.. Valid accuracy: 0.870
Epoch: 6/8.. Train loss: 0.790.. Valid loss: 0.508.. Valid accuracy: 0.861
Epoch: 6/8.. Train loss: 0.806.. Valid loss: 0.491.. Valid accuracy: 0.873
Epoch: 7/8.. Train loss: 0.806.. Valid loss: 0.565.. Valid accuracy: 0.861
Epoch: 7/8.. Train loss: 0.825.. Valid loss: 0.449.. Valid accuracy: 0.887
Epoch: 8/8.. Train loss: 0.734.. Valid loss: 0.453.. Valid accuracy: 0.882
Epoch: 8/8.. Train loss: 0.773.. Valid loss: 0.539.. Valid accuracy: 0.860
Total time: 14m 39s
1 |
Testing your network
It’s good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model’s performance on completely new images. Run the test images through the network and measure the accuracy, the same way you did validation. You should be able to reach around 70% accuracy on the test set if the model has been trained well.
1 | # TODO: Do validation on the test set |
Valid accuracy: 0.854
Save the checkpoint
Now that your network is trained, save the model so you can load it later for making predictions. You probably want to save other things such as the mapping of classes to indices which you get from one of the image datasets: image_datasets['train'].class_to_idx
. You can attach this to the model as an attribute which makes inference easier later on.
1 |
|
Loading the checkpoint
At this point it’s good to write a function that can load a checkpoint and rebuild the model. That way you can come back to this project and keep working on it without having to retrain the network.
1 | # TODO: Write a function that loads a checkpoint and rebuilds the model |
1 | model = load_checkpoint('checkpoint.pth') |
VGG(
(features): Sequential(
(0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(1): ReLU(inplace=True)
(2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(3): ReLU(inplace=True)
(4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
(5): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(6): ReLU(inplace=True)
(7): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(8): ReLU(inplace=True)
(9): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
(10): Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(11): ReLU(inplace=True)
(12): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(13): ReLU(inplace=True)
(14): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(15): ReLU(inplace=True)
(16): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(17): ReLU(inplace=True)
(18): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
(19): Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(20): ReLU(inplace=True)
(21): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(22): ReLU(inplace=True)
(23): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(24): ReLU(inplace=True)
(25): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(26): ReLU(inplace=True)
(27): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
(28): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(29): ReLU(inplace=True)
(30): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(31): ReLU(inplace=True)
(32): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(33): ReLU(inplace=True)
(34): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(35): ReLU(inplace=True)
(36): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
)
(avgpool): AdaptiveAvgPool2d(output_size=(7, 7))
(classifier): Sequential(
(0): Linear(in_features=25088, out_features=2048, bias=True)
(1): ReLU()
(2): Dropout(p=0.25, inplace=False)
(3): Linear(in_features=2048, out_features=102, bias=True)
(4): LogSoftmax()
)
)
1 |
Inference for classification
Now you’ll write a function to use a trained network for inference. That is, you’ll pass an image into the network and predict the class of the flower in the image. Write a function called predict
that takes an image and a model, then returns the top $K$ most likely classes along with the probabilities. It should look like
1 | probs, classes = predict(image_path, model) |
First you’ll need to handle processing the input image such that it can be used in your network.
Image Preprocessing
You’ll want to use PIL
to load the image (documentation). It’s best to write a function that preprocesses the image so it can be used as input for the model. This function should process the images in the same manner used for training.
First, resize the images where the shortest side is 256 pixels, keeping the aspect ratio. This can be done with the thumbnail
or resize
methods. Then you’ll need to crop out the center 224x224 portion of the image.
Color channels of images are typically encoded as integers 0-255, but the model expected floats 0-1. You’ll need to convert the values. It’s easiest with a Numpy array, which you can get from a PIL image like so np_image = np.array(pil_image)
.
As before, the network expects the images to be normalized in a specific way. For the means, it’s [0.485, 0.456, 0.406]
and for the standard deviations [0.229, 0.224, 0.225]
. You’ll want to subtract the means from each color channel, then divide by the standard deviation.
And finally, PyTorch expects the color channel to be the first dimension but it’s the third dimension in the PIL image and Numpy array. You can reorder dimensions using ndarray.transpose
. The color channel needs to be first and retain the order of the other two dimensions.
1 | # TODO: Process a PIL image for use in a PyTorch model |
To check your work, the function below converts a PyTorch tensor and displays it in the notebook. If your process_image
function works, running the output through this function should return the original image (except for the cropped out portions).
1 | def imshow(image, ax=None, title=None): |
1 | # Show original pics |
1 | # Show processed pics |
<matplotlib.axes._subplots.AxesSubplot at 0x2ae83fbbf08>
Class Prediction
Once you can get images in the correct format, it’s time to write a function for making predictions with your model. A common practice is to predict the top 5 or so (usually called top-$K$) most probable classes. You’ll want to calculate the class probabilities then find the $K$ largest values.
To get the top $K$ largest values in a tensor use x.topk(k)
. This method returns both the highest k
probabilities and the indices of those probabilities corresponding to the classes. You need to convert from these indices to the actual class labels using class_to_idx
which hopefully you added to the model or from an ImageFolder
you used to load the data (see here). Make sure to invert the dictionary so you get a mapping from index to class as well.
Again, this method should take a path to an image and a model checkpoint, then return the probabilities and classes.
1 | probs, classes = predict(image_path, model) |
1 | def predict(image_path, model, topk=5): |
1 | img_path = test_dir + '/17/image_03911.jpg' |
(tensor([[9.8274e-01, 1.6505e-02, 3.9908e-04, 1.0707e-04, 9.1983e-05]],
grad_fn=<TopkBackward>), ['17', '100', '18', '34', '92'])
Sanity Checking
Now that you can use a trained model for predictions, check to make sure it makes sense. Even if the testing accuracy is high, it’s always good to check that there aren’t obvious bugs. Use matplotlib
to plot the probabilities for the top 5 classes as a bar graph, along with the input image. It should look like this:
You can convert from the class integer encoding to actual flower names with the cat_to_name.json
file (should have been loaded earlier in the notebook). To show a PyTorch tensor as an image, use the imshow
function defined above.
1 | # TODO: Display an image along with the top 5 classes |
1 | plt.figure(figsize = (8,8)) |
1 | # test a flower pic outside the dataset |