Developing an AI application

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.

In [1]:
# Imports here
from collections import OrderedDict
import torch.nn.functional as F
import matplotlib.pyplot as plt
from torchvision import transforms, datasets, models
import torch
from torch import nn, optim

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.

In [2]:
data_dir = 'flowers'
train_dir = data_dir + '/train'
valid_dir = data_dir + '/valid'
test_dir = data_dir + '/test'
In [3]:
# View an image first (color channels not normalized) to make sure that we are loading the data correctly
transform = transforms.Compose([transforms.Resize(256),
                                transforms.CenterCrop(224),
                                transforms.ToTensor()])
img_dataset = datasets.ImageFolder(train_dir, transform)
dataloader = torch.utils.data.DataLoader(img_dataset, batch_size=32, shuffle=True)

images, labels = next(iter(dataloader))
plt.imshow(images[0].permute(1, 2, 0))
Out[3]:
<matplotlib.image.AxesImage at 0x7f25895a6390>
In [4]:
# TODO: Define your transforms for the training, validation, and testing sets
img_size = 224
means = [0.485, 0.456, 0.406]
stds = [0.229, 0.224, 0.225]

train_transforms = transforms.Compose([transforms.RandomRotation(45),
                                       transforms.RandomVerticalFlip(),
                                       transforms.RandomHorizontalFlip(),
                                       transforms.RandomResizedCrop(img_size),
                                       transforms.ToTensor(),
                                       transforms.Normalize(means, stds)])
                                       
validation_transforms = transforms.Compose([transforms.Resize(256),
                                            transforms.CenterCrop(img_size),
                                            transforms.ToTensor(),
                                            transforms.Normalize(means, stds)])
                                       
test_transforms = transforms.Compose([transforms.Resize(256),
                                      transforms.CenterCrop(img_size),
                                      transforms.ToTensor(),
                                      transforms.Normalize(means, stds)])

data_transforms = [train_transforms, validation_transforms, test_transforms]

# TODO: Load the datasets with ImageFolder
image_datasets = [ datasets.ImageFolder(folder, transform) \
                  for folder, transform in zip([train_dir, valid_dir, test_dir], data_transforms) ]

# TODO: Using the image datasets and the trainforms, define the dataloaders
dataloaders = [ torch.utils.data.DataLoader(dataset, batch_size=32, shuffle=True) for dataset in image_datasets ]

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.

In [5]:
import json

with open('cat_to_name.json', 'r') as f:
    cat_to_name = json.load(f)

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. 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:

  • 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.

In [ ]:
# Load a pre-trained network
# model = models.resnet152(pretrained=True)
model = models.vgg19(pretrained=True)
model
In [ ]:
# Freeze pretrained model parameters
for param in model.parameters():
    param.requires_grad = False
In [ ]:
# Define a new, untrained feed-forward network as a classifier, using ReLU activations and dropout
input_size = 25088
hidden_sizes = [4096, 1024, 512]
output_size = 102

classifier = [nn.Linear(input_size, hidden_sizes[0])]

for h1, h2 in zip(hidden_sizes[:-1], hidden_sizes[1:]):
    classifier.extend([nn.ReLU(), nn.Dropout(), nn.Linear(h1, h2)])
    
classifier.extend([nn.ReLU(), nn.Dropout(), nn.Linear(hidden_sizes[-1], output_size), nn.LogSoftmax(dim=1)])

model.classifier = nn.Sequential(*classifier)
In [64]:
# Define criterion and optimizer
criterion = nn.NLLLoss()
optimizer = optim.SGD(model.classifier.parameters(), lr=0.06)
In [62]:
# Define a validation function
def validation(model, criterion, validationloader):
    
    # Put model into eval mode and send to CUDA
    model.eval()
    model.to('cuda')
    
    # Initialize accuracy and loss variables
    accuracy = 0
    validation_loss = 0
    
    with torch.no_grad():
        for images, labels in validationloader:
            
            # Make predictions
            images, labels = images.to('cuda'), labels.to('cuda')
            outputs = model(images)
            predictions = torch.max(outputs, dim=1)[1]
            
            # Compute loss
            loss = criterion(outputs, labels)
            validation_loss += loss.item()
            
            # Compute accuracy
            accuracy += (predictions == labels).type(torch.FloatTensor).mean().item()
    
    validation_loss /= len(validationloader)
    accuracy /= len(validationloader)
    
    # Put model back into train mode
    model.train()
    
    return validation_loss, accuracy 
In [ ]:
# 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
epochs = 10
print_every = 40
step = 0
train_error = 0

model.to('cuda')
model.train()

for e in range(epochs):
    for images, labels in dataloaders[0]:
        step += 1
        
        # Zero out gradients
        optimizer.zero_grad()
        
        # Forward pass
        images, labels = images.to('cuda'), labels.to('cuda')
        outputs = model(images)
        
        # Compute loss
        loss = criterion(outputs, labels)
        train_error += loss.item()
        
        # Backward pass
        loss.backward()
        optimizer.step()
        
        if step % print_every == 0:
            with torch.no_grad():
                validation_loss, acc = validation(model, criterion, dataloaders[1])
                print("Epoch {}/{}:".format(e+1, epochs),
                      "Training error: {0:.4f}".format(train_error / print_every),
                      "Validation error: {0:.4f}".format(validation_loss),
                      "Validation accuracy: {0:.4f}".format(acc))
            
            train_error = 0     

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.

In [65]:
# TODO: Do validation on the test set
loss, acc = validation(model, criterion, dataloaders[2])
print("Loss: {0:.4f} Accuracy: {1:.2f}%".format(loss, acc * 100))
Loss: 0.9980 Accuracy: 71.19%

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.

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 [ ]:
# TODO: Save the checkpoint 
checkpoint = {
    'input_size': input_size,
    'hidden_sizes': hidden_sizes,
    'output_size': output_size,
    'state_dict': model.state_dict(),
    'num_epochs': epochs,
    'optimizer_state': optimizer.state_dict(),
    'mapping': image_datasets[0].class_to_idx}

torch.save(checkpoint, "checkpoint.pth")

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.

In [6]:
# TODO: Write a function that loads a checkpoint and rebuilds the model
def load_checkpoint(checkpoint):
    
    # Load model
    model = models.vgg19(pretrained=True)
    for param in model.parameters():
        param.requires_grad = False
        
    # Rebuild classifier
    input_size, hidden_sizes, output_size = checkpoint["input_size"], checkpoint["hidden_sizes"], checkpoint["output_size"]
    
    classifier = [nn.Linear(input_size, hidden_sizes[0])]
    for h1, h2 in zip(hidden_sizes[:-1], hidden_sizes[1:]):
        classifier.extend([nn.ReLU(), nn.Dropout(), nn.Linear(h1, h2)])    
    classifier.extend([nn.ReLU(), nn.Dropout(), nn.Linear(hidden_sizes[-1], output_size), nn.LogSoftmax(dim=1)])
    model.classifier = nn.Sequential(*classifier)
    
    # Load state_dict
    model.load_state_dict(checkpoint['state_dict'])
    
    # Attach mapping
    model.class_to_idx = checkpoint["mapping"]
    
    # Create optimizer
    optimizer = optim.SGD(model.classifier.parameters(), lr=0.06)
    
    # Load optimizer state
    optimizer.load_state_dict(checkpoint["optimizer_state"])
    
    return checkpoint["num_epochs"], model, optimizer
In [7]:
checkpoint = torch.load("./checkpoint.pth")
num_epochs, model, optimizer = load_checkpoint(checkpoint)
Downloading: "https://download.pytorch.org/models/vgg19-dcbb9e9d.pth" to /root/.torch/models/vgg19-dcbb9e9d.pth
100%|██████████| 574673361/574673361 [00:15<00:00, 37991394.86it/s]

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

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.

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.

In [8]:
from PIL import Image
import numpy as np
im = Image.open("flowers/train/1/image_06734.jpg")
In [9]:
def process_image(image):
    ''' Scales, crops, and normalizes a PIL image for a PyTorch model,
        returns an Numpy array
    '''
    
    # TODO: Process a PIL image for use in a PyTorch model
    width = image.width
    height = image.height
    aspect_ratio = width / height
    
    # Resize image so minimum dimension is 256, preserving aspect ratio
    if aspect_ratio > 1:
        width = 256 * aspect_ratio
        height = 256
    else:
        width = 256
        height = 256 / aspect_ratio
    
    # Center crop image to 224x224
    image.thumbnail((width, height))
    left, top = (width - 224) / 2, (height - 224) / 2,
    right, bot = width - left, height - top
    image = image.crop((left, top, right, bot))
    
    # Convert PIL image into array
    np_image = np.array(image) / 255
    
    # Normalize
    means = np.array([0.485, 0.456, 0.406])
    stds = np.array([0.229, 0.224, 0.225])
    np_image = (np_image - means[np.newaxis, np.newaxis, :]) / stds[np.newaxis, np.newaxis, :]
    
    return np.transpose(np_image, [2, 0, 1])

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 [10]:
def imshow(image, ax=None, title=None):
    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.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
In [12]:
# Test imshow
imshow(process_image(im))
Out[12]:
<matplotlib.axes._subplots.AxesSubplot at 0x7f25881b6780>

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.

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 [183]:
def predict(image_path, model, topk=5):
    ''' Predict the class (or classes) of an image using a trained deep learning model.
    '''
    
    # TODO: Implement the code to predict the class from an image file
    im = Image.open(image_path)
    image = process_image(im)
    
    # Make sure model is in eval mode
    model.eval()
    model.to('cuda')
    image = torch.from_numpy(image).type(torch.FloatTensor)
    image = image.to('cuda')
    image.unsqueeze_(0)
    with torch.no_grad():
        output = model(image)
    predictions = torch.exp(output)
    probs, indices = torch.topk(predictions, topk, dim=1)
    
    # Convert indices to class labels
    idx_to_class = { v : k for k, v in model.class_to_idx.items() }
    probs, indices = probs.cpu(), indices.cpu()
    classes = np.vectorize(lambda x: idx_to_class[x])(indices.numpy())

    return probs, classes

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.

In [ ]:
# Function that takes in flower names and uses cat_to_name to
# return flower names. Can take in single str or a list
# as a parameter and returns the same type.

def get_flower_names(indices):
    if isinstance(indices, list):
        return [ cat_to_name[k] for k in indices ]
    elif isinstance(indices, str):
        return cat_to_name[indices]
    else:
        print("`indices` should be a list or str")
        raise
In [191]:
# Function: plot_prediction()
# Plots a given image along with the true label if known
# and the top K predictions returned by the model
# @param image_path - path to input image
# @param model - model that takes as an input image and returns predictions
# @param topk - top K predictions to plot - 5 by default
# @param true_label - if known, provide in order to label reference image

def plot_prediction(image_path, model, topk=5, true_label=None):
    probs, classes = predict(image_path, model, topk)
    
    # Convert classes to names
    if true_label is None:
        flower_name = "Unknown"
    else:
        flower_name = get_flower_names(true_label)
    topk_names = get_flower_names(list(classes[0]))

    fig = plt.figure(figsize=(4, 8))
    ax1 = fig.add_subplot(211)
    imshow(process_image(Image.open(image_path)), ax1)
    ax1.get_xaxis().set_ticks([])
    ax1.get_yaxis().set_ticks([])
    ax1.set_title(flower_name)

    ax2 = fig.add_subplot(212)
    bar_probs = probs.numpy()[0]
    yticks = np.arange(len(bar_probs), 0, -1)
    ax2.barh(yticks, bar_probs)
    ax2.get_yaxis().set_ticks(yticks)
    ax2.get_yaxis().set_ticklabels(topk_names)
    
    return
In [192]:
# TODO: Display an image along with the top 5 classes
plot_prediction("flowers/test/10/image_07090.jpg", model, topk=6, true_label='10')