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 [87]:
# Imports here
import torch
import numpy as np
from torch import nn, optim
from torchvision import datasets, transforms, models
from workspace_utils import keep_awake, active_session
from PIL import Image

%matplotlib inline
%config InlineBackend.figure_format = 'retina'

import matplotlib.pyplot as plt

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 [88]:
data_dir = 'flowers'
train_dir = data_dir + '/train'
valid_dir = data_dir + '/valid'
test_dir = data_dir + '/test'
In [89]:
# TODO: Define your transforms for the training, validation, and testing sets
train_transforms = transforms.Compose([transforms.RandomResizedCrop(224),
                                       transforms.RandomRotation(40),
                                       transforms.RandomHorizontalFlip(),
                                       transforms.ToTensor(),
                                       transforms.Normalize([0.485, 0.456, 0.406],
                                                            [0.229, 0.224, 0.225])])

vt_transforms = transforms.Compose([transforms.Resize(255),
                                    transforms.CenterCrop(224),
                                    transforms.ToTensor(),
                                    transforms.Normalize([0.485, 0.456, 0.406],
                                                         [0.229, 0.224, 0.225])])

# TODO: Load the datasets with ImageFolder
train_dataset = datasets.ImageFolder(train_dir, transform = train_transforms)
valid_dataset = datasets.ImageFolder(valid_dir, transform = vt_transforms)
test_dataset = datasets.ImageFolder(test_dir, transform = vt_transforms)

# TODO: Using the image datasets and the trainforms, define the dataloaders
train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size = 64, shuffle = True)
valid_dataloader = torch.utils.data.DataLoader(valid_dataset, batch_size = 64)
test_dataloader = torch.utils.data.DataLoader(test_dataset, batch_size = 64)

print('done')
done

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 [90]:
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. 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.

In [91]:
# TODO: Build and train your network

#Pre-trained torchvision model
model = models.vgg16(pretrained = True)
model
Out[91]:
VGG(
  (features): Sequential(
    (0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (1): ReLU(inplace)
    (2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (3): ReLU(inplace)
    (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)
    (7): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (8): ReLU(inplace)
    (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)
    (12): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (13): ReLU(inplace)
    (14): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (15): ReLU(inplace)
    (16): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (17): Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (18): ReLU(inplace)
    (19): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (20): ReLU(inplace)
    (21): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (22): ReLU(inplace)
    (23): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (24): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (25): ReLU(inplace)
    (26): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (27): ReLU(inplace)
    (28): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (29): ReLU(inplace)
    (30): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  )
  (classifier): Sequential(
    (0): Linear(in_features=25088, out_features=4096, bias=True)
    (1): ReLU(inplace)
    (2): Dropout(p=0.5)
    (3): Linear(in_features=4096, out_features=4096, bias=True)
    (4): ReLU(inplace)
    (5): Dropout(p=0.5)
    (6): Linear(in_features=4096, out_features=1000, bias=True)
  )
)
In [92]:
#Freeze parameters
for param in model.parameters():
    param.requires_grad = False
    
#Define Classifier (new feed-forward network using ReLU)
classifier = nn.Sequential(nn.Linear(25088, 4096),
                           nn.ReLU(),
                           nn.Dropout(0.5),
                           nn.Linear(4096, 102),
                           nn.LogSoftmax(dim=1))

#update classifier
model.classifier = classifier

#optimizer - use very small learning rate
optimizer = optim.Adam(model.classifier.parameters(), lr = 0.001)
In [93]:
#standard loss definition
criterion = nn.NLLLoss()

#device definition to enable training on GPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

model.to(device);
print('done')
done
In [94]:
#Training loop - similar to Lesson 4 Notebooks

epochs = 5
steps = 0
running_loss = 0
print_every = 10
for e in range(epochs):
    for images, labels in train_dataloader:
        steps += 1
        
        #Move input to GPU
        images, labels = images.to(device), labels.to(device)
        
        #zero gradients for each pass
        optimizer.zero_grad()
        
        #forward pass
        log_probabilities = model.forward(images)
        #loss
        loss = criterion(log_probabilities, labels)
        #backpropagation
        loss.backward()
        #update weights
        optimizer.step()
    
        running_loss += loss.item()
        
        #validation pass (similar to Notebook 8)
        if steps % print_every == 0:
            valid_loss = 0
            valid_accuracy = 0
            #set model to evaluation mode
            model.eval()
            
            #zero gradients
            with torch.no_grad():
                for images, labels in valid_dataloader:
                    images, labels = images.to(device), labels.to(device)
                    valid_log_probs = model.forward(images)
                    
                    batch_loss = criterion(valid_log_probs, labels)
                    
                    valid_loss += batch_loss.item()
                    
                    #calculate accuracy
                    probs = torch.exp(valid_log_probs)
                    top_prob, top_class = probs.topk(1, dim=1)
                    equals = top_class == labels.view(*top_class.shape)
                    valid_accuracy += torch.mean(equals.type(torch.FloatTensor)).item()
                    
            #print results
            print(f"Epoch {e+1}/{epochs}.. "
                  f"Validation loss: {valid_loss/len(valid_dataloader):.3f}.. "
                  f"Validation accuracy: {valid_accuracy/len(valid_dataloader):.3f}")
            
            running_loss = 0
            #back to train mode
            model.train()
print('done')
Epoch 1/5.. Validation loss: 7.142.. Validation accuracy: 0.053
Epoch 1/5.. Validation loss: 3.737.. Validation accuracy: 0.204
Epoch 1/5.. Validation loss: 3.080.. Validation accuracy: 0.321
Epoch 1/5.. Validation loss: 2.637.. Validation accuracy: 0.417
Epoch 1/5.. Validation loss: 2.099.. Validation accuracy: 0.494
Epoch 1/5.. Validation loss: 1.852.. Validation accuracy: 0.535
Epoch 1/5.. Validation loss: 1.690.. Validation accuracy: 0.554
Epoch 1/5.. Validation loss: 1.469.. Validation accuracy: 0.623
Epoch 1/5.. Validation loss: 1.351.. Validation accuracy: 0.638
Epoch 1/5.. Validation loss: 1.401.. Validation accuracy: 0.618
Epoch 2/5.. Validation loss: 1.287.. Validation accuracy: 0.648
Epoch 2/5.. Validation loss: 1.127.. Validation accuracy: 0.691
Epoch 2/5.. Validation loss: 1.154.. Validation accuracy: 0.691
Epoch 2/5.. Validation loss: 1.105.. Validation accuracy: 0.685
Epoch 2/5.. Validation loss: 1.108.. Validation accuracy: 0.690
Epoch 2/5.. Validation loss: 1.078.. Validation accuracy: 0.718
Epoch 2/5.. Validation loss: 0.918.. Validation accuracy: 0.758
Epoch 2/5.. Validation loss: 0.941.. Validation accuracy: 0.745
Epoch 2/5.. Validation loss: 0.989.. Validation accuracy: 0.734
Epoch 2/5.. Validation loss: 0.910.. Validation accuracy: 0.746
Epoch 3/5.. Validation loss: 0.879.. Validation accuracy: 0.759
Epoch 3/5.. Validation loss: 0.848.. Validation accuracy: 0.762
Epoch 3/5.. Validation loss: 0.893.. Validation accuracy: 0.760
Epoch 3/5.. Validation loss: 0.833.. Validation accuracy: 0.766
Epoch 3/5.. Validation loss: 0.889.. Validation accuracy: 0.765
Epoch 3/5.. Validation loss: 0.707.. Validation accuracy: 0.800
Epoch 3/5.. Validation loss: 0.787.. Validation accuracy: 0.787
Epoch 3/5.. Validation loss: 0.841.. Validation accuracy: 0.758
Epoch 3/5.. Validation loss: 0.753.. Validation accuracy: 0.795
Epoch 3/5.. Validation loss: 0.775.. Validation accuracy: 0.786
Epoch 4/5.. Validation loss: 0.767.. Validation accuracy: 0.800
Epoch 4/5.. Validation loss: 0.783.. Validation accuracy: 0.793
Epoch 4/5.. Validation loss: 0.776.. Validation accuracy: 0.783
Epoch 4/5.. Validation loss: 0.793.. Validation accuracy: 0.769
Epoch 4/5.. Validation loss: 0.752.. Validation accuracy: 0.789
Epoch 4/5.. Validation loss: 0.703.. Validation accuracy: 0.802
Epoch 4/5.. Validation loss: 0.669.. Validation accuracy: 0.810
Epoch 4/5.. Validation loss: 0.695.. Validation accuracy: 0.810
Epoch 4/5.. Validation loss: 0.867.. Validation accuracy: 0.794
Epoch 4/5.. Validation loss: 0.772.. Validation accuracy: 0.795
Epoch 4/5.. Validation loss: 0.719.. Validation accuracy: 0.801
Epoch 5/5.. Validation loss: 0.714.. Validation accuracy: 0.804
Epoch 5/5.. Validation loss: 0.649.. Validation accuracy: 0.831
Epoch 5/5.. Validation loss: 0.635.. Validation accuracy: 0.822
Epoch 5/5.. Validation loss: 0.706.. Validation accuracy: 0.821
Epoch 5/5.. Validation loss: 0.730.. Validation accuracy: 0.817
Epoch 5/5.. Validation loss: 0.685.. Validation accuracy: 0.806
Epoch 5/5.. Validation loss: 0.675.. Validation accuracy: 0.820
Epoch 5/5.. Validation loss: 0.673.. Validation accuracy: 0.825
Epoch 5/5.. Validation loss: 0.648.. Validation accuracy: 0.832
Epoch 5/5.. Validation loss: 0.671.. Validation accuracy: 0.826
done

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 [95]:
# TODO: Do validation on the test set
model.eval()
test_loss = 0
test_accuracy = 0

with torch.no_grad():
    for images, labels in test_dataloader:
        images, labels = images.to(device), labels.to(device)
        
        test_logps = model.forward(images)
        
        test_loss = criterion(test_logps, labels)
        
        test_probs = torch.exp(test_logps)
        test_top_p, test_top_class = test_probs.topk(1, dim=1)
        equals = test_top_class == labels.view(*test_top_class.shape)
        test_accuracy += torch.mean(equals.type(torch.FloatTensor)).item()
    
    print(f"Test accuracy: {test_accuracy/len(test_dataloader):.3f}")

    model.train()
Test accuracy: 0.767

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 [96]:
# TODO: Save the checkpoint 
model.class_to_idx = train_dataset.class_to_idx
checkpoint = {'classifier' : classifier,
              'state_dict' : model.state_dict(),
              'class_to_idx' : model.class_to_idx,
              'epochs' : 5,
              'optimizer' : optimizer.state_dict()}
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 [97]:
# TODO: Write a function that loads a checkpoint and rebuilds the model
def loadCheckpoint(filepath):
    checkpoint = torch.load(filepath)
    model = models.vgg16(pretrained = True)
    model.classifier = checkpoint['classifier']
    model.load_state_dict(checkpoint['state_dict'])
    model.class_to_idx = checkpoint['class_to_idx']
    model.optimizer = checkpoint['optimizer']
    model.epochs = checkpoint['epochs']
    
    return model

model = loadCheckpoint('checkpoint.pth')
print('done')
done

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 [98]:
def process_image(image):
    ''' Scales, crops, and normalizes a PIL image for a PyTorch model,
        returns an Numpy array
        Input: filepath to image
        
        Note: Adapted from examples shown in the Knowledge section of Udacity
    '''
    
    # TODO: Process a PIL image for use in a PyTorch model
    im = Image.open(image)
    #assuming input image was a square
    im = im.resize((256,256))
    
    #crop
    left = (256 - 224)/2
    top = (256 - 224)/2
    right = left + 224
    bottom = top + 224
    im = im.crop((left, top, right, bottom))
    
    #normalize color channels
    im = np.array(im)/255
    means = [0.485, 0.456, 0.406]
    stds = [0.229, 0.224, 0.225]
    im = (im - means) / stds
    
    #Transpose
    im = im.transpose([2,0,1])
        
    return im

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 [99]:
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.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 [100]:
#image processing test
test_image = test_dir + '/100/image_07899.jpg'
test_process = process_image(test_image)
test_result = imshow(test_process)

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 [101]:
def predict(image_path, model, topk=5):
    ''' Predict the class (or classes) of an image using a trained deep learning model.
    
        Again with assistance from the Knowledge Forum
    '''
    # TODO: Implement the code to predict the class from an image file
    
    model.eval()
    model.cpu()
    image = process_image(image_path)
    
    #convert back to tensor
    image_tensor = torch.from_numpy(image).float()
    
    #add batch dimension
    image_tensor = image_tensor.unsqueeze(0)
    
    with torch.no_grad():
                
        #probabilities
        predict_logps = model.forward(image_tensor)
        predict_probs = torch.exp(predict_logps)
        
        #get top K probabilities
        probs, indices = predict_probs.topk(topk)
        probs = probs.numpy()[0]
        
        #convert indices to class labels and map
        idx_to_class = {y : x for x,y in model.class_to_idx.items()}
        classes = []
        indices = indices.numpy()[0]
        for  i in indices:
            classes.append(idx_to_class[i])
    
    model.train()
    
    return probs, classes
In [102]:
probs, classes = predict(test_image, model)
print(probs)
print(classes)
[  9.97147501e-01   1.52138178e-03   6.53407769e-04   6.51161768e-04
   7.85466364e-06]
['100', '71', '54', '18', '83']

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 [103]:
# TODO: Display an image along with the top 5 classes
def sanity_check(image_path, model):
    '''
    Displays the image and a bar graph showing the probabilities 
    for the top 5 predicted classes of the image. 
    
    Made with reference to examples shown on knowledge.udacity.com, as well as 
    external sources helping me with matplotlib
    '''
    
    
    image = process_image(image_path)
    
    probs, classes = predict(image_path, model)
    
    flowers = []
    for i in classes:
        flowers.append(cat_to_name[i])
    
    image_out = imshow(image)
    
    image_out.axis('off')
    image_out.set_title(flowers[0])
    
    fig, ax = plt.subplots()
    ax.set_ylabel("Flowers")
    ax.set_xlabel("Probabilities")
    ax.invert_yaxis()
    ax.barh(flowers, probs, align='center')
    
In [104]:
sanity_check(test_image, model)
In [ ]:
 
In [ ]:
!jupyter nbconvert *.ipynb