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:
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.
In [1]:
# Imports here
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.optim as optim
from torch import nn
from torch.utils.data.sampler import SubsetRandomSampler
from torch.utils.data.dataloader import DataLoader
import torchvision.transforms as transforms
import torchvision.datasets
import torchvision.models as models
from PIL import Image
Here you'll use torchvision
to load the data (documentation). You can download the data here. The dataset is split into two parts, training and validation. 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. If you use a pre-trained network, you'll also need to make sure the input data is resized to 224x224 pixels as required by the networks.
The validation set is 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 available from torchvision
were trained on the ImageNet dataset where each color channel was normalized separately. For both 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.
In [2]:
data_dir = './flower_data'
train_dir = data_dir + '/train'
valid_dir = data_dir + '/valid'
In [3]:
# TODO: Define your transforms for the training and validation sets
train_transforms = transforms.Compose([transforms.RandomHorizontalFlip(),
transforms.RandomRotation(degrees=45),
transforms.RandomResizedCrop(size=224),
transforms.ToTensor(),
transforms.Normalize(mean=(0.485, 0.456, 0.406),
std=(0.229, 0.224, 0.225))])
valid_transforms = transforms.Compose([transforms.Resize(size=256),
transforms.CenterCrop(size=224),
transforms.ToTensor(),
transforms.Normalize(mean=(0.485, 0.456, 0.406),
std=(0.229, 0.224, 0.225))])
# TODO: Load the datasets with ImageFolder
train_image_dataset = torchvision.datasets.ImageFolder(root=train_dir,
transform=train_transforms)
valid_image_dataset = torchvision.datasets.ImageFolder(root=valid_dir,
transform=valid_transforms)
# TODO: Using the image datasets and the trainforms, define the dataloaders
train_dataloader = DataLoader(dataset=train_image_dataset,
batch_size=32,
shuffle=True,
num_workers=0)
valid_dataloader = DataLoader(dataset=valid_image_dataset,
batch_size=32,
shuffle=True,
num_workers=0)
In [4]:
class_to_idx = train_image_dataset.class_to_idx
In [5]:
# Obtain one batch of training images
dataiter = iter(train_dataloader)
images, labels = dataiter.next()
images = images.numpy() # convert images to numpy for display
In [6]:
images.shape
Out[6]:
In [7]:
img = images[0, :, :, :]
In [8]:
plt.imshow(np.transpose(a=img, axes=(1, 2, 0)))
Out[8]:
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.
In [9]:
import json
with open('cat_to_name.json', 'r') as f:
cat_to_name = json.load(f)
In [10]:
cat_to_name
Out[10]:
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. If you want to talk through it with someone, chat with your fellow students! You can also ask questions on the forums or join the instructors in office hours.
Refer to the rubric for guidance on successfully completing this section. Things you'll need to do:
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.
In [11]:
# TODO: Build and train your network
def build_model(class_to_idx):
model = models.resnet18(pretrained=True)
# Freezing the features
for param in model.parameters():
param.requires_grad_(False)
from collections import OrderedDict
model.fc = nn.Sequential(OrderedDict([
('fc1', nn.Linear(512, 512)),
('relu', nn.ReLU()),
('fc2', nn.Linear(512, 102)),
('output', nn.LogSoftmax(dim=1))
]))
# Setting trainable parameters
for trainable_params in model.fc.parameters():
trainable_params.requires_grad_(True)
model.class_to_idx = class_to_idx
print('Model created!')
return model
In [12]:
model = build_model(class_to_idx=class_to_idx)
In [13]:
# Check if CUDA is available
train_on_gpu = torch.cuda.is_available()
if train_on_gpu:
model.cuda()
In [14]:
train_on_gpu
Out[14]:
In [15]:
# Specify loss function (categorical cross-entropy)
criterion = nn.NLLLoss()
# Specify optimizer
learning_rate = 0.0001
optimizer = optim.Adam(params=model.fc.parameters(),
lr=learning_rate)
In [16]:
from tqdm import tqdm_notebook as tqdm
In [17]:
best_weights_path = './models/lab_best_model_state_dict.pth'
In [18]:
# Number of epochs to train the model
n_epochs = 1000
valid_loss_min = np.Inf # track change in validation loss
for epoch in range(1, n_epochs + 1):
# Keep track of training and validation loss
train_loss = 0.0
valid_loss = 0.0
# train the model
model.train()
for data, target in tqdm(train_dataloader):
# Move tensors to GPU if CUDA is available
if train_on_gpu:
data, target = data.cuda(), target.cuda()
# Clear the gradients of all optimized variables
optimizer.zero_grad()
# Forward pass: compute predicted outputs by passing inputs to the model
output = model(data)
# Calculate the batch loss
loss = criterion(output, target)
# Backward pass: compute gradient of the loss with respect to model parameters
loss.backward()
# Perform a single optimization step (parameter update)
optimizer.step()
# Update training loss
train_loss += loss.item() * data.size(0)
# Validate the model
model.eval()
for data, target in valid_dataloader:
# Move tensors to GPU if CUDA is available
if train_on_gpu:
data, target = data.cuda(), target.cuda()
# Forward pass: compute predicted outputs by passing inputs to the model
output = model(data)
# Calculate the batch loss
loss = criterion(output, target)
# Update average validation loss
valid_loss += loss.item() * data.size(0)
# Calculate average losses
train_loss = train_loss / len(train_dataloader.dataset)
valid_loss = valid_loss / len(valid_dataloader.dataset)
# Print training / validation statistics
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
epoch, train_loss, valid_loss))
# Save model if validation loss has decreased
if valid_loss <= valid_loss_min:
print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format(
valid_loss_min,
valid_loss))
torch.save(model.state_dict(), best_weights_path)
valid_loss_min = valid_loss
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.
model.class_to_idx = image_datasets['train'].class_to_idx
Remember that you'll want to completely rebuild the model later so you can use it for inference. Make sure to include any information you need in the checkpoint. If you want to load the model and keep training, you'll want to save the number of epochs as well as the optimizer state, optimizer.state_dict
. You'll likely want to use this trained model in the next part of the project, so best to save it now.
In [19]:
# TODO: Save the checkpoint
# Load the best weights
full_model_path = './models/lab_best_model_full_model.pth'
state_dict = torch.load(best_weights_path)
full_model_dict = {'model_name': 'WojciechNetBasedOnResNet',
'lr': learning_rate,
'epochs': n_epochs,
'state_dict': model.state_dict(),
'optimizer' : optimizer.state_dict(),
'class_to_idx' : model.class_to_idx
}
torch.save(full_model_dict, full_model_path)
In [20]:
# TODO: Write a function that loads a checkpoint and rebuilds the model
full_model_dict_loaded = torch.load(full_model_path)
lr_loaded = full_model_dict_loaded['lr']
class_to_idx_loaded = full_model_dict_loaded['class_to_idx']
In [21]:
model = build_model(class_to_idx=class_to_idx_loaded)
model.load_state_dict(full_model_dict_loaded['state_dict'])
In [22]:
optimizer = optim.Adam(params=model.parameters(),
lr=lr_loaded)
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
probs, classes = predict(image_path, model)
print(probs)
print(classes)
> [ 0.01558163 0.01541934 0.01452626 0.01443549 0.01407339]
> ['70', '3', '45', '62', '55']
First you'll need to handle processing the input image such that it can be used in your network.
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.
In [23]:
def process_image(image):
''' Scales, crops, and normalizes a PIL image for a PyTorch model,
returns an Numpy array
'''
size = 224
# TODO: Process a PIL image for use in a PyTorch model
width, height = image.size
if height > width:
height = int(max(height * size / width, 1))
width = int(size)
else:
width = int(max(width * size / height, 1))
height = int(size)
resized_image = image.resize((width, height))
# Calculating points for cropping the image, left bottom and top right
x_left = (width - size) / 2
y_bottom = (height - size) / 2
x_right = x_left + size
y_top = y_bottom + size
# Cropping the image
cropped_image = image.crop((x_left,
y_bottom,
x_right,
y_top))
np_image = np.array(cropped_image) / 255.
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
np_image_array = (np_image - mean) / std
np_image_array = np_image.transpose((2, 0, 1))
return np_image_array
In [24]:
process_image(image = Image.open('./flower_data/valid/10/image_07094.jpg'))
Out[24]:
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).
In [25]:
def imshow(image, ax=None, title=None):
"""Imshow for Tensor."""
if ax is None:
fig, ax = plt.subplots()
# PyTorch tensors assume the color channel is the first dimension
# but matplotlib assumes is the third dimension
image = image.numpy().transpose((1, 2, 0))
# Undo preprocessing
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
image = std * image + mean
# Image needs to be clipped between 0 and 1 or it looks like noise when displayed
image = np.clip(image, 0, 1)
ax.imshow(image)
return ax
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.
probs, classes = predict(image_path, model)
print(probs)
print(classes)
> [ 0.01558163 0.01541934 0.01452626 0.01443549 0.01407339]
> ['70', '3', '45', '62', '55']
In [26]:
def predict(image_path, model, top_num=5):
# Process image
image = process_image(image=Image.open(image_path))
# Numpy -> Tensor
image_tensor = torch.from_numpy(image).type(torch.FloatTensor)
# Adding additional dimension to the it
model_input = image_tensor.unsqueeze(0)
# Calculating the probabilities
probabilities = torch.exp(model.forward(model_input))
# Top probabilities
top_probabilities, top_labels = probabilities.topk(top_num)
top_probabilities = top_probabilities.detach().numpy().tolist()[0]
top_labels = top_labels.detach().numpy().tolist()[0]
# Convert indices to classes
idx_to_class = {val: key for key, val in
model.class_to_idx.items()}
top_k_labels = [idx_to_class[lab] for lab in top_labels]
top_flowers = [cat_to_name[idx_to_class[lab]] for lab in top_labels]
return top_probabilities, top_k_labels, top_flowers
In [27]:
def predict(image_path, model, topk=5, use_gpu=True):
''' Predict the class (or classes) of an image using a trained deep learning model.
'''
model.eval()
train_on_gpu = torch.cuda.is_available()
model = model.cuda() if train_on_gpu else model.cpu()
image = Image.open(image_path)
np_array = process_image(image)
tensor = torch.from_numpy(np_array)
tensor_on_device = tensor.float().cuda() if train_on_gpu else tensor
with torch.no_grad():
var_inputs = torch.autograd.Variable(tensor_on_device)
var_inputs = var_inputs.unsqueeze(0)
output = model.forward(var_inputs)
predictions = torch.exp(output).data.topk(topk)
probabilities = predictions[0].cpu() if use_gpu else predictions[0]
classes = predictions[1].cpu() if use_gpu else predictions[1]
class_to_idx_inverted = {model.class_to_idx[k]: k for k in model.class_to_idx}
mapped_classes = []
for label in classes.numpy()[0]:
mapped_classes.append(class_to_idx_inverted[label])
return probabilities.numpy()[0], mapped_classes
image_path = './flower_data/valid/10/image_07094.jpg'
probabilities, classes = predict(image_path, model)
print(probabilities)
print(classes)
Now that you can use a trained model for predictions, check to make sure it makes sense. Even if the validation 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.
In [28]:
# TODO: Display an image along with the top 5 classes
image_path = './flower_data/valid/10/image_07094.jpg'
probabilities, classes = predict(image_path, model)
In [29]:
max_index = np.argmax(probabilities)
max_probability = probabilities[max_index]
label = classes[max_index]
fig = plt.figure(figsize=(10,10))
ax1 = plt.subplot2grid((15,9), (0,0),
colspan=9,
rowspan=9)
ax2 = plt.subplot2grid((15,9),
(9,2),
colspan=5,
rowspan=5)
image = Image.open(image_path)
ax1.axis('off')
ax1.set_title(cat_to_name[label])
ax1.imshow(image)
labels = []
for i_class in classes:
labels.append(cat_to_name[i_class])
y_pos = np.arange(5)
ax2.set_yticks(y_pos)
ax2.set_yticklabels(labels)
ax2.invert_yaxis()
ax2.set_xlabel('Probability')
ax2.barh(y_pos,
probabilities,
xerr=0,
align='center')
plt.show()