<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS_HTML"></script>
<!-- MathJax configuration -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {
inlineMath: [ ['$','$'], ["\\(","\\)"] ],
displayMath: [ ['$$','$$'], ["\\[","\\]"] ],
processEscapes: true,
processEnvironments: true
},
// Center justify equations in code and markdown cells. Elsewhere
// we use CSS to left justify single line equations in code cells.
displayAlign: 'center',
"HTML-CSS": {
styles: {'.MathJax_Display': {"margin": 0}},
linebreaks: { automatic: true }
}
});
</script>
<!-- End of mathjax configuration --></head>
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.
# Imports here import numpy as np import torch %matplotlib inline %config InlineBackend.figure_format = 'retina' import matplotlib.pyplot as plt from collections import OrderedDict from torchvision import datasets, transforms,models import torch.nn.functional as F from torch import nn,optim from PIL import Image import os
</div>
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.
data_dir = 'flowers' train_dir = data_dir + '/train' valid_dir = data_dir + '/valid' test_dir = data_dir + '/test'
</div>
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])train_transforms = transforms.Compose([transforms.RandomRotation(30), transforms.Resize(224), transforms.RandomResizedCrop(224), transforms.RandomVerticalFlip(), transforms.ToTensor(), normalize]) test_valid_transforms = transforms.Compose([transforms.Resize(224), transforms.CenterCrop(224), transforms.ToTensor(), normalize])
# TODO: Load the datasets with ImageFolder
train_data_datasets = datasets.ImageFolder(train_dir, transform=train_transforms) valid_data_datasets = datasets.ImageFolder(valid_dir , transform=test_valid_transforms) test_data_datasets = datasets.ImageFolder(test_dir , transform=test_valid_transforms) image_datasets = {'training_sets': train_data_datasets, 'validation_sets': valid_data_datasets , 'testing_sets': test_data_datasets }
# TODO: Using the image datasets and the trainforms, define the dataloaders trainloader = torch.utils.data.DataLoader(train_data_datasets, batch_size=64, shuffle=True) validloader = torch.utils.data.DataLoader(valid_data_datasets, batch_size=64) testloader = torch.utils.data.DataLoader(test_data_datasets, batch_size=64)
</div>
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.
import jsonwith open('cat_to_name.json', 'r') as f: cat_to_name = json.load(f)
</div>
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.
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") my_model = models.vgg16(pretrained=True) for param in my_model.parameters(): param.requires_grad = Falseclassifier = nn.Sequential(OrderedDict([ ('fc1', nn.Linear(25088, 512)), ('relu', nn.ReLU()), ('dropout', nn.Dropout(0.4)), ('fc2', nn.Linear(512, 102)), ('output', nn.LogSoftmax(dim=1)) ]))
my_model.classifier = classifier
criterion = nn.NLLLoss()
# Only train the classifier parameters, feature parameters are frozen optimizer = optim.Adam(my_model.classifier.parameters(), lr=0.001) my_model.to(device);
epochs = 3 steps = 0 running_loss = 0 print_every = 15 train_losses, valid_losses = [], []
</div>
<div class="prompt"></div>
Downloading: "https://download.pytorch.org/models/vgg16-397923af.pth" to /root/.torch/models/vgg16-397923af.pth 100%|██████████| 553433881/553433881 [00:05<00:00, 109937926.20it/s]
print("Starting the Training")for epoch in range(epochs): for inputs, labels in trainloader: steps += 1 # Move input and label tensors to the default device inputs, labels = inputs.to(device), labels.to(device)
<span class="n">optimizer</span><span class="o">.</span><span class="n">zero_grad</span><span class="p">()</span> <span class="n">logps</span> <span class="o">=</span> <span class="n">my_model</span><span class="o">.</span><span class="n">forward</span><span class="p">(</span><span class="n">inputs</span><span class="p">)</span> <span class="n">loss</span> <span class="o">=</span> <span class="n">criterion</span><span class="p">(</span><span class="n">logps</span><span class="p">,</span> <span class="n">labels</span><span class="p">)</span> <span class="n">loss</span><span class="o">.</span><span class="n">backward</span><span class="p">()</span> <span class="n">optimizer</span><span class="o">.</span><span class="n">step</span><span class="p">()</span> <span class="n">running_loss</span> <span class="o">+=</span> <span class="n">loss</span><span class="o">.</span><span class="n">item</span><span class="p">()</span> <span class="k">if</span> <span class="n">steps</span> <span class="o">%</span> <span class="n">print_every</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span> <span class="n">valid_loss</span> <span class="o">=</span> <span class="mi">0</span> <span class="n">accuracy</span> <span class="o">=</span> <span class="mi">0</span> <span class="n">my_model</span><span class="o">.</span><span class="n">eval</span><span class="p">()</span> <span class="k">with</span> <span class="n">torch</span><span class="o">.</span><span class="n">no_grad</span><span class="p">():</span> <span class="k">for</span> <span class="n">inputs</span><span class="p">,</span> <span class="n">labels</span> <span class="ow">in</span> <span class="n">validloader</span><span class="p">:</span> <span class="n">inputs</span><span class="p">,</span> <span class="n">labels</span> <span class="o">=</span> <span class="n">inputs</span><span class="o">.</span><span class="n">to</span><span class="p">(</span><span class="n">device</span><span class="p">),</span> <span class="n">labels</span><span class="o">.</span><span class="n">to</span><span class="p">(</span><span class="n">device</span><span class="p">)</span> <span class="n">logps</span> <span class="o">=</span> <span class="n">my_model</span><span class="o">.</span><span class="n">forward</span><span class="p">(</span><span class="n">inputs</span><span class="p">)</span> <span class="n">batch_loss</span> <span class="o">=</span> <span class="n">criterion</span><span class="p">(</span><span class="n">logps</span><span class="p">,</span> <span class="n">labels</span><span class="p">)</span> <span class="n">valid_loss</span> <span class="o">+=</span> <span class="n">batch_loss</span><span class="o">.</span><span class="n">item</span><span class="p">()</span> <span class="c1"># Calculate accuracy</span> <span class="n">ps</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">exp</span><span class="p">(</span><span class="n">logps</span><span class="p">)</span> <span class="n">top_p</span><span class="p">,</span> <span class="n">top_class</span> <span class="o">=</span> <span class="n">ps</span><span class="o">.</span><span class="n">topk</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="n">dim</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span> <span class="n">equals</span> <span class="o">=</span> <span class="n">top_class</span> <span class="o">==</span> <span class="n">labels</span><span class="o">.</span><span class="n">view</span><span class="p">(</span><span class="o">*</span><span class="n">top_class</span><span class="o">.</span><span class="n">shape</span><span class="p">)</span> <span class="n">accuracy</span> <span class="o">+=</span> <span class="n">torch</span><span class="o">.</span><span class="n">mean</span><span class="p">(</span><span class="n">equals</span><span class="o">.</span><span class="n">type</span><span class="p">(</span><span class="n">torch</span><span class="o">.</span><span class="n">FloatTensor</span><span class="p">))</span><span class="o">.</span><span class="n">item</span><span class="p">()</span> <span class="n">train_losses</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">running_loss</span><span class="o">/</span><span class="nb">len</span><span class="p">(</span><span class="n">trainloader</span><span class="p">))</span> <span class="n">valid_losses</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">valid_loss</span><span class="o">/</span><span class="nb">len</span><span class="p">(</span><span class="n">validloader</span><span class="p">))</span> <span class="nb">print</span><span class="p">(</span><span class="n">f</span><span class="s2">"Epoch {epoch+1}/</span><span class="si">{epochs}</span><span class="s2">.. "</span> <span class="n">f</span><span class="s2">"Train loss: {running_loss/print_every:.3f}.. "</span> <span class="n">f</span><span class="s2">"Validation loss: {valid_loss/len(validloader):.3f}.. "</span> <span class="n">f</span><span class="s2">"Validation accuracy: {100*accuracy/len(validloader):.3f}%"</span><span class="p">)</span> <span class="n">running_loss</span> <span class="o">=</span> <span class="mi">0</span> <span class="n">my_model</span><span class="o">.</span><span class="n">train</span><span class="p">()</span>
plt.plot(train_losses, label = 'Training loss') plt.plot(valid_losses, label = 'Validation loss') plt.legend(frameon = False)
</div>
<div class="prompt"></div>
Starting the Training Epoch 1/3.. Train loss: 4.451.. Validation loss: 3.275.. Validation accuracy: 30.591% Epoch 1/3.. Train loss: 3.418.. Validation loss: 2.357.. Validation accuracy: 45.558% Epoch 1/3.. Train loss: 2.953.. Validation loss: 1.901.. Validation accuracy: 52.250% Epoch 1/3.. Train loss: 2.571.. Validation loss: 1.445.. Validation accuracy: 63.370% Epoch 1/3.. Train loss: 2.227.. Validation loss: 1.276.. Validation accuracy: 68.077% Epoch 1/3.. Train loss: 2.165.. Validation loss: 1.117.. Validation accuracy: 70.462% Epoch 2/3.. Train loss: 1.952.. Validation loss: 1.041.. Validation accuracy: 73.519% Epoch 2/3.. Train loss: 1.715.. Validation loss: 0.966.. Validation accuracy: 73.909% Epoch 2/3.. Train loss: 1.712.. Validation loss: 0.919.. Validation accuracy: 74.082% Epoch 2/3.. Train loss: 1.594.. Validation loss: 0.806.. Validation accuracy: 76.692% Epoch 2/3.. Train loss: 1.787.. Validation loss: 0.825.. Validation accuracy: 76.264% Epoch 2/3.. Train loss: 1.667.. Validation loss: 0.764.. Validation accuracy: 79.144% Epoch 2/3.. Train loss: 1.498.. Validation loss: 0.745.. Validation accuracy: 80.087% Epoch 3/3.. Train loss: 1.474.. Validation loss: 0.802.. Validation accuracy: 77.962% Epoch 3/3.. Train loss: 1.434.. Validation loss: 0.707.. Validation accuracy: 80.038% Epoch 3/3.. Train loss: 1.325.. Validation loss: 0.639.. Validation accuracy: 82.149% Epoch 3/3.. Train loss: 1.338.. Validation loss: 0.697.. Validation accuracy: 80.880% Epoch 3/3.. Train loss: 1.392.. Validation loss: 0.634.. Validation accuracy: 83.005% Epoch 3/3.. Train loss: 1.403.. Validation loss: 0.655.. Validation accuracy: 82.784% Epoch 3/3.. Train loss: 1.379.. Validation loss: 0.641.. Validation accuracy: 83.538%
<div class="prompt output_prompt">Out[7]:</div>
<matplotlib.legend.Legend at 0x7f681cad55c0>
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.
# TODO: Do validation on the test set device = torch.device("cuda" if torch.cuda.is_available() else "cpu") my_model.to(device); my_model.eval() accuracy = 0 test_loss = 0 with torch.no_grad(): for inputs, labels in testloader: inputs, labels = inputs.to(device), labels.to(device) logps = my_model.forward(inputs) batch_loss = criterion(logps, labels)<span class="n">test_loss</span> <span class="o">+=</span> <span class="n">batch_loss</span><span class="o">.</span><span class="n">item</span><span class="p">()</span> <span class="c1"># Calculate accuracy</span> <span class="n">ps</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">exp</span><span class="p">(</span><span class="n">logps</span><span class="p">)</span> <span class="n">top_p</span><span class="p">,</span> <span class="n">top_class</span> <span class="o">=</span> <span class="n">ps</span><span class="o">.</span><span class="n">topk</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="n">dim</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span> <span class="n">equals</span> <span class="o">=</span> <span class="n">top_class</span> <span class="o">==</span> <span class="n">labels</span><span class="o">.</span><span class="n">view</span><span class="p">(</span><span class="o">*</span><span class="n">top_class</span><span class="o">.</span><span class="n">shape</span><span class="p">)</span> <span class="n">accuracy</span> <span class="o">+=</span> <span class="n">torch</span><span class="o">.</span><span class="n">mean</span><span class="p">(</span><span class="n">equals</span><span class="o">.</span><span class="n">type</span><span class="p">(</span><span class="n">torch</span><span class="o">.</span><span class="n">FloatTensor</span><span class="p">))</span><span class="o">.</span><span class="n">item</span><span class="p">()</span>
print(f"Test Loss: {test_loss/len(testloader):.3f}.. " f"Test accuracy: {100*accuracy/len(testloader):.3f} %")
</div>
<div class="prompt"></div>
Test Loss: 0.815.. Test accuracy: 78.957 %
</div>
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.
# TODO: Save the checkpoint checkpoint = {'state_dict': my_model.state_dict(), 'input_size': 25088, 'hidden_layer': 512 'output_size': 102, 'epochs': epochs, 'learning_rate': 0.001, 'class_to_idx': train_data_datasets.class_to_idx, 'classifier': my_model.classifier, 'optimizer': optimizer.state_dict()} #Save chesckpoint torch.save(checkpoint, 'cuba_my_checkpoint.pth')
</div>
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.
# TODO: Write a function that loads a checkpoint and rebuilds the model device = torch.device("cuda" if torch.cuda.is_available() else "cpu") def load_checkpoint(filepath): checkpoint = torch.load(filepath,map_location="cpu") my_model = models.vgg16(pretrained = True) my_model.to(device); for param in my_model.parameters(): param.requires_grad = False<span class="n">classifier</span> <span class="o">=</span> <span class="n">nn</span><span class="o">.</span><span class="n">Sequential</span><span class="p">(</span><span class="n">OrderedDict</span><span class="p">([</span> <span class="p">(</span><span class="s1">'fc1'</span><span class="p">,</span><span class="n">nn</span><span class="o">.</span><span class="n">Linear</span><span class="p">(</span><span class="n">checkpoint</span><span class="p">[</span><span class="s1">'input_size'</span><span class="p">],</span><span class="n">checkpoint</span><span class="p">[</span><span class="s1">'hidden_layer'</span><span class="p">])),</span> <span class="p">(</span><span class="s1">'relu'</span><span class="p">,</span><span class="n">nn</span><span class="o">.</span><span class="n">ReLU</span><span class="p">()),</span> <span class="p">(</span><span class="s1">'Dropout'</span><span class="p">,</span><span class="n">nn</span><span class="o">.</span><span class="n">Dropout</span><span class="p">(</span><span class="mf">0.4</span><span class="p">)),</span> <span class="p">(</span><span class="s1">'fc2'</span><span class="p">,</span><span class="n">nn</span><span class="o">.</span><span class="n">Linear</span><span class="p">(</span><span class="n">checkpoint</span><span class="p">[</span><span class="s1">'hidden_layer'</span><span class="p">],</span><span class="n">checkpoint</span><span class="p">[</span><span class="s1">'output_size'</span><span class="p">])),</span> <span class="p">(</span><span class="s1">'output'</span><span class="p">,</span><span class="n">nn</span><span class="o">.</span><span class="n">LogSoftmax</span><span class="p">(</span><span class="n">dim</span><span class="o">=</span><span class="mi">1</span><span class="p">))]))</span> <span class="n">my_model</span><span class="o">.</span><span class="n">classifier</span> <span class="o">=</span> <span class="n">classifier</span> <span class="n">my_model</span><span class="o">.</span><span class="n">optimizer</span> <span class="o">=</span> <span class="n">checkpoint</span><span class="p">[</span><span class="s1">'optimizer'</span><span class="p">]</span> <span class="n">my_model</span><span class="o">.</span><span class="n">load_state_dict</span><span class="p">(</span><span class="n">checkpoint</span><span class="p">[</span><span class="s1">'state_dict'</span><span class="p">])</span> <span class="n">my_model</span><span class="o">.</span><span class="n">class_to_index</span> <span class="o">=</span> <span class="n">checkpoint</span><span class="p">[</span><span class="s1">'class_to_idx'</span><span class="p">]</span> <span class="nb">print</span><span class="p">(</span><span class="n">f</span><span class="s2">"Load Model Hyper paramter Values: </span><span class="se">\n</span><span class="s2">"</span> <span class="c1"># f"optimizer: {checkpoint['optimizer']} \n"</span> <span class="c1">#f"classifier: {checkpoint['classifier'] }\n"</span> <span class="n">f</span><span class="s2">"input_size: {checkpoint['input_size'] }</span><span class="se">\n</span><span class="s2">"</span> <span class="n">f</span><span class="s2">"output_size: </span><span class="si">{checkpoint['output_size']}</span><span class="se">\n</span><span class="s2">"</span> <span class="n">f</span><span class="s2">"epochs: {checkpoint['epochs'] }"</span><span class="p">)</span> <span class="k">return</span> <span class="n">my_model</span>
loaded_model = None loaded_model = load_checkpoint('cuba_my_checkpoint.pth')
</div>
<div class="prompt"></div>
Downloading: "https://download.pytorch.org/models/vgg16-397923af.pth" to /root/.torch/models/vgg16-397923af.pth 100%|██████████| 553433881/553433881 [00:07<00:00, 69744391.47it/s]
<div class="prompt"></div>
Load Model Hyper paramter Values: input_size: 25088 output_size: 102 epochs: 3
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
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.
def process_image(image): im = Image.open(image) ##normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], # std=[0.229, 0.224, 0.225]) #test_valid_transforms = transforms.Compose([transforms.Resize(224), # transforms.CenterCrop(224), # transforms.ToTensor(), # normalize]) #image_tensor = test_valid_transforms(im).float() #image_tensor = image_tensor.unsqueeze_(0) #input = Variable(image_tensor) #input = input.to(device)<span class="c1">#return image_tensor</span> <span class="sd">''' Scales, crops, and normalizes a PIL image for a PyTorch model,</span>
returns an Numpy array ''' # print(f" Image : {image}") im = Image.open(image) width, height = im.size size_r = float(width/height) n_width = 256 if size_r <= 1 else 256size_r n_height = 256 if size_r >= 1 else 256size_r im=im.resize((int(n_width),int(n_height))) #crop_size = (256 - 224)/2. #im=im.crop((crop_size, crop_size, crop_size, crop_size)) im=im.crop(((256 - 224) / 2., (256 - 224) / 2., (256 + 224) / 2., (256 + 224) / 2.)) im = np.array(im)/255 mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] im = (im - mean) / std im = im.transpose((2, 0, 1)) tns_im = torch.from_numpy(im) return tns_im
<span class="c1"># TODO: Process a PIL image for use in a PyTorch model</span>
d = np.random.randint(103,size=1)[0] image_dir = test_dir+"/"+str(d) i_file = image_dir + "/" + np.random.choice(os.listdir(image_dir)) tns_image=process_image(i_file) print(i_file) imshow(tns_image)
</div>
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).
def imshow(image, ax=None, title=None): """Imshow for Tensor.""" if ax is None: fig, ax = plt.subplots()<span class="c1"># PyTorch tensors assume the color channel is the first dimension</span> <span class="c1"># but matplotlib assumes is the third dimension</span> <span class="n">image</span> <span class="o">=</span> <span class="n">image</span><span class="o">.</span><span class="n">numpy</span><span class="p">()</span><span class="o">.</span><span class="n">transpose</span><span class="p">((</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">0</span><span class="p">))</span> <span class="c1"># Undo preprocessing</span> <span class="n">mean</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span><span class="mf">0.485</span><span class="p">,</span> <span class="mf">0.456</span><span class="p">,</span> <span class="mf">0.406</span><span class="p">])</span> <span class="n">std</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span><span class="mf">0.229</span><span class="p">,</span> <span class="mf">0.224</span><span class="p">,</span> <span class="mf">0.225</span><span class="p">])</span> <span class="n">image</span> <span class="o">=</span> <span class="n">std</span> <span class="o">*</span> <span class="n">image</span> <span class="o">+</span> <span class="n">mean</span> <span class="c1"># Image needs to be clipped between 0 and 1 or it looks like noise when displayed</span> <span class="n">image</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">clip</span><span class="p">(</span><span class="n">image</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span> <span class="n">ax</span><span class="o">.</span><span class="n">imshow</span><span class="p">(</span><span class="n">image</span><span class="p">)</span> <span class="k">return</span> <span class="n">ax</span>
d = np.random.randint(103,size=1)[0] image_dir = test_dir+"/"+str(d) i_file = image_dir + "/" + np.random.choice(os.listdir(image_dir)) tns_image=process_image(i_file) imshow(tns_image);
</div>
<div class="prompt"></div>