Skip to content
Snippets Groups Projects
Commit db21682e authored by Dellandrea Emmanuel's avatar Dellandrea Emmanuel
Browse files

Update TD2 Deep Learning.ipynb

parent 29af4a2c
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id:7edf7168 tags: %% Cell type:markdown id:7edf7168 tags:
# TD2: Deep learning # TD2: Deep learning
%% Cell type:markdown id:fbb8c8df tags: %% Cell type:markdown id:fbb8c8df tags:
In this TD, you must modify this notebook to answer the questions. To do this, In this TD, you must modify this notebook to answer the questions. To do this,
1. Fork this repository 1. Fork this repository
2. Clone your forked repository on your local computer 2. Clone your forked repository on your local computer
3. Answer the questions 3. Answer the questions
4. Commit and push regularly 4. Commit and push regularly
The last commit is due on Sunday, November 27, 11:59 PM. Later commits will not be taken into account. The last commit is due on Sunday, December 1, 11:59 PM. Later commits will not be taken into account.
%% Cell type:markdown id:3d167a29 tags: %% Cell type:markdown id:3d167a29 tags:
Install and test PyTorch from https://pytorch.org/get-started/locally. Install and test PyTorch from https://pytorch.org/get-started/locally.
%% Cell type:code id:330a42f5 tags: %% Cell type:code id:330a42f5 tags:
``` python ``` python
%pip install torch torchvision %pip install torch torchvision
``` ```
%% Cell type:markdown id:0882a636 tags: %% Cell type:markdown id:0882a636 tags:
To test run the following code To test run the following code
%% Cell type:code id:b1950f0a tags: %% Cell type:code id:b1950f0a tags:
``` python ``` python
import torch import torch
N, D = 14, 10 N, D = 14, 10
x = torch.randn(N, D).type(torch.FloatTensor) x = torch.randn(N, D).type(torch.FloatTensor)
print(x) print(x)
from torchvision import models from torchvision import models
alexnet = models.alexnet() alexnet = models.alexnet()
print(alexnet) print(alexnet)
``` ```
%% Cell type:markdown id:23f266da tags: %% Cell type:markdown id:23f266da tags:
## Exercise 1: CNN on CIFAR10 ## Exercise 1: CNN on CIFAR10
The goal is to apply a Convolutional Neural Net (CNN) model on the CIFAR10 image dataset and test the accuracy of the model on the basis of image classification. Compare the Accuracy VS the neural network implemented during TD1. The goal is to apply a Convolutional Neural Net (CNN) model on the CIFAR10 image dataset and test the accuracy of the model on the basis of image classification. Compare the Accuracy VS the neural network implemented during TD1.
Have a look at the following documentation to be familiar with PyTorch. Have a look at the following documentation to be familiar with PyTorch.
https://pytorch.org/tutorials/beginner/pytorch_with_examples.html https://pytorch.org/tutorials/beginner/pytorch_with_examples.html
https://pytorch.org/tutorials/beginner/deep_learning_60min_blitz.html https://pytorch.org/tutorials/beginner/deep_learning_60min_blitz.html
%% Cell type:markdown id:4ba1c82d tags: %% Cell type:markdown id:4ba1c82d tags:
You can test if GPU is available on your machine and thus train on it to speed up the process You can test if GPU is available on your machine and thus train on it to speed up the process
%% Cell type:code id:6e18f2fd tags: %% Cell type:code id:6e18f2fd tags:
``` python ``` python
import torch import torch
# check if CUDA is available # check if CUDA is available
train_on_gpu = torch.cuda.is_available() train_on_gpu = torch.cuda.is_available()
if not train_on_gpu: if not train_on_gpu:
print("CUDA is not available. Training on CPU ...") print("CUDA is not available. Training on CPU ...")
else: else:
print("CUDA is available! Training on GPU ...") print("CUDA is available! Training on GPU ...")
``` ```
%% Cell type:markdown id:5cf214eb tags: %% Cell type:markdown id:5cf214eb tags:
Next we load the CIFAR10 dataset Next we load the CIFAR10 dataset
%% Cell type:code id:462666a2 tags: %% Cell type:code id:462666a2 tags:
``` python ``` python
import numpy as np import numpy as np
from torchvision import datasets, transforms from torchvision import datasets, transforms
from torch.utils.data.sampler import SubsetRandomSampler from torch.utils.data.sampler import SubsetRandomSampler
# number of subprocesses to use for data loading # number of subprocesses to use for data loading
num_workers = 0 num_workers = 0
# how many samples per batch to load # how many samples per batch to load
batch_size = 20 batch_size = 20
# percentage of training set to use as validation # percentage of training set to use as validation
valid_size = 0.2 valid_size = 0.2
# convert data to a normalized torch.FloatTensor # convert data to a normalized torch.FloatTensor
transform = transforms.Compose( transform = transforms.Compose(
[transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))] [transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]
) )
# choose the training and test datasets # choose the training and test datasets
train_data = datasets.CIFAR10("data", train=True, download=True, transform=transform) train_data = datasets.CIFAR10("data", train=True, download=True, transform=transform)
test_data = datasets.CIFAR10("data", train=False, download=True, transform=transform) test_data = datasets.CIFAR10("data", train=False, download=True, transform=transform)
# obtain training indices that will be used for validation # obtain training indices that will be used for validation
num_train = len(train_data) num_train = len(train_data)
indices = list(range(num_train)) indices = list(range(num_train))
np.random.shuffle(indices) np.random.shuffle(indices)
split = int(np.floor(valid_size * num_train)) split = int(np.floor(valid_size * num_train))
train_idx, valid_idx = indices[split:], indices[:split] train_idx, valid_idx = indices[split:], indices[:split]
# define samplers for obtaining training and validation batches # define samplers for obtaining training and validation batches
train_sampler = SubsetRandomSampler(train_idx) train_sampler = SubsetRandomSampler(train_idx)
valid_sampler = SubsetRandomSampler(valid_idx) valid_sampler = SubsetRandomSampler(valid_idx)
# prepare data loaders (combine dataset and sampler) # prepare data loaders (combine dataset and sampler)
train_loader = torch.utils.data.DataLoader( train_loader = torch.utils.data.DataLoader(
train_data, batch_size=batch_size, sampler=train_sampler, num_workers=num_workers train_data, batch_size=batch_size, sampler=train_sampler, num_workers=num_workers
) )
valid_loader = torch.utils.data.DataLoader( valid_loader = torch.utils.data.DataLoader(
train_data, batch_size=batch_size, sampler=valid_sampler, num_workers=num_workers train_data, batch_size=batch_size, sampler=valid_sampler, num_workers=num_workers
) )
test_loader = torch.utils.data.DataLoader( test_loader = torch.utils.data.DataLoader(
test_data, batch_size=batch_size, num_workers=num_workers test_data, batch_size=batch_size, num_workers=num_workers
) )
# specify the image classes # specify the image classes
classes = [ classes = [
"airplane", "airplane",
"automobile", "automobile",
"bird", "bird",
"cat", "cat",
"deer", "deer",
"dog", "dog",
"frog", "frog",
"horse", "horse",
"ship", "ship",
"truck", "truck",
] ]
``` ```
%% Cell type:markdown id:58ec3903 tags: %% Cell type:markdown id:58ec3903 tags:
CNN definition (this one is an example) CNN definition (this one is an example)
%% Cell type:code id:317bf070 tags: %% Cell type:code id:317bf070 tags:
``` python ``` python
import torch.nn as nn import torch.nn as nn
import torch.nn.functional as F import torch.nn.functional as F
# define the CNN architecture # define the CNN architecture
class Net(nn.Module): class Net(nn.Module):
def __init__(self): def __init__(self):
super(Net, self).__init__() super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5) self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2) self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5) self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120) self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84) self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10) self.fc3 = nn.Linear(84, 10)
def forward(self, x): def forward(self, x):
x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x))) x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5) x = x.view(-1, 16 * 5 * 5)
x = F.relu(self.fc1(x)) x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x)) x = F.relu(self.fc2(x))
x = self.fc3(x) x = self.fc3(x)
return x return x
# create a complete CNN # create a complete CNN
model = Net() model = Net()
print(model) print(model)
# move tensors to GPU if CUDA is available # move tensors to GPU if CUDA is available
if train_on_gpu: if train_on_gpu:
model.cuda() model.cuda()
``` ```
%% Cell type:markdown id:a2dc4974 tags: %% Cell type:markdown id:a2dc4974 tags:
Loss function and training using SGD (Stochastic Gradient Descent) optimizer Loss function and training using SGD (Stochastic Gradient Descent) optimizer
%% Cell type:code id:4b53f229 tags: %% Cell type:code id:4b53f229 tags:
``` python ``` python
import torch.optim as optim import torch.optim as optim
criterion = nn.CrossEntropyLoss() # specify loss function criterion = nn.CrossEntropyLoss() # specify loss function
optimizer = optim.SGD(model.parameters(), lr=0.01) # specify optimizer optimizer = optim.SGD(model.parameters(), lr=0.01) # specify optimizer
n_epochs = 30 # number of epochs to train the model n_epochs = 30 # number of epochs to train the model
train_loss_list = [] # list to store loss to visualize train_loss_list = [] # list to store loss to visualize
valid_loss_min = np.Inf # track change in validation loss valid_loss_min = np.Inf # track change in validation loss
for epoch in range(n_epochs): for epoch in range(n_epochs):
# Keep track of training and validation loss # Keep track of training and validation loss
train_loss = 0.0 train_loss = 0.0
valid_loss = 0.0 valid_loss = 0.0
# Train the model # Train the model
model.train() model.train()
for data, target in train_loader: for data, target in train_loader:
# Move tensors to GPU if CUDA is available # Move tensors to GPU if CUDA is available
if train_on_gpu: if train_on_gpu:
data, target = data.cuda(), target.cuda() data, target = data.cuda(), target.cuda()
# Clear the gradients of all optimized variables # Clear the gradients of all optimized variables
optimizer.zero_grad() optimizer.zero_grad()
# Forward pass: compute predicted outputs by passing inputs to the model # Forward pass: compute predicted outputs by passing inputs to the model
output = model(data) output = model(data)
# Calculate the batch loss # Calculate the batch loss
loss = criterion(output, target) loss = criterion(output, target)
# Backward pass: compute gradient of the loss with respect to model parameters # Backward pass: compute gradient of the loss with respect to model parameters
loss.backward() loss.backward()
# Perform a single optimization step (parameter update) # Perform a single optimization step (parameter update)
optimizer.step() optimizer.step()
# Update training loss # Update training loss
train_loss += loss.item() * data.size(0) train_loss += loss.item() * data.size(0)
# Validate the model # Validate the model
model.eval() model.eval()
for data, target in valid_loader: for data, target in valid_loader:
# Move tensors to GPU if CUDA is available # Move tensors to GPU if CUDA is available
if train_on_gpu: if train_on_gpu:
data, target = data.cuda(), target.cuda() data, target = data.cuda(), target.cuda()
# Forward pass: compute predicted outputs by passing inputs to the model # Forward pass: compute predicted outputs by passing inputs to the model
output = model(data) output = model(data)
# Calculate the batch loss # Calculate the batch loss
loss = criterion(output, target) loss = criterion(output, target)
# Update average validation loss # Update average validation loss
valid_loss += loss.item() * data.size(0) valid_loss += loss.item() * data.size(0)
# Calculate average losses # Calculate average losses
train_loss = train_loss / len(train_loader) train_loss = train_loss / len(train_loader)
valid_loss = valid_loss / len(valid_loader) valid_loss = valid_loss / len(valid_loader)
train_loss_list.append(train_loss) train_loss_list.append(train_loss)
# Print training/validation statistics # Print training/validation statistics
print( print(
"Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}".format( "Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}".format(
epoch, train_loss, valid_loss epoch, train_loss, valid_loss
) )
) )
# Save model if validation loss has decreased # Save model if validation loss has decreased
if valid_loss <= valid_loss_min: if valid_loss <= valid_loss_min:
print( print(
"Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...".format( "Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...".format(
valid_loss_min, valid_loss valid_loss_min, valid_loss
) )
) )
torch.save(model.state_dict(), "model_cifar.pt") torch.save(model.state_dict(), "model_cifar.pt")
valid_loss_min = valid_loss valid_loss_min = valid_loss
``` ```
%% Cell type:markdown id:13e1df74 tags: %% Cell type:markdown id:13e1df74 tags:
Does overfit occur? If so, do an early stopping. Does overfit occur? If so, do an early stopping.
%% Cell type:code id:d39df818 tags: %% Cell type:code id:d39df818 tags:
``` python ``` python
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
plt.plot(range(n_epochs), train_loss_list) plt.plot(range(n_epochs), train_loss_list)
plt.xlabel("Epoch") plt.xlabel("Epoch")
plt.ylabel("Loss") plt.ylabel("Loss")
plt.title("Performance of Model 1") plt.title("Performance of Model 1")
plt.show() plt.show()
``` ```
%% Cell type:markdown id:11df8fd4 tags: %% Cell type:markdown id:11df8fd4 tags:
Now loading the model with the lowest validation loss value Now loading the model with the lowest validation loss value
%% Cell type:code id:e93efdfc tags: %% Cell type:code id:e93efdfc tags:
``` python ``` python
model.load_state_dict(torch.load("./model_cifar.pt")) model.load_state_dict(torch.load("./model_cifar.pt"))
# track test loss # track test loss
test_loss = 0.0 test_loss = 0.0
class_correct = list(0.0 for i in range(10)) class_correct = list(0.0 for i in range(10))
class_total = list(0.0 for i in range(10)) class_total = list(0.0 for i in range(10))
model.eval() model.eval()
# iterate over test data # iterate over test data
for data, target in test_loader: for data, target in test_loader:
# move tensors to GPU if CUDA is available # move tensors to GPU if CUDA is available
if train_on_gpu: if train_on_gpu:
data, target = data.cuda(), target.cuda() data, target = data.cuda(), target.cuda()
# forward pass: compute predicted outputs by passing inputs to the model # forward pass: compute predicted outputs by passing inputs to the model
output = model(data) output = model(data)
# calculate the batch loss # calculate the batch loss
loss = criterion(output, target) loss = criterion(output, target)
# update test loss # update test loss
test_loss += loss.item() * data.size(0) test_loss += loss.item() * data.size(0)
# convert output probabilities to predicted class # convert output probabilities to predicted class
_, pred = torch.max(output, 1) _, pred = torch.max(output, 1)
# compare predictions to true label # compare predictions to true label
correct_tensor = pred.eq(target.data.view_as(pred)) correct_tensor = pred.eq(target.data.view_as(pred))
correct = ( correct = (
np.squeeze(correct_tensor.numpy()) np.squeeze(correct_tensor.numpy())
if not train_on_gpu if not train_on_gpu
else np.squeeze(correct_tensor.cpu().numpy()) else np.squeeze(correct_tensor.cpu().numpy())
) )
# calculate test accuracy for each object class # calculate test accuracy for each object class
for i in range(batch_size): for i in range(batch_size):
label = target.data[i] label = target.data[i]
class_correct[label] += correct[i].item() class_correct[label] += correct[i].item()
class_total[label] += 1 class_total[label] += 1
# average test loss # average test loss
test_loss = test_loss / len(test_loader) test_loss = test_loss / len(test_loader)
print("Test Loss: {:.6f}\n".format(test_loss)) print("Test Loss: {:.6f}\n".format(test_loss))
for i in range(10): for i in range(10):
if class_total[i] > 0: if class_total[i] > 0:
print( print(
"Test Accuracy of %5s: %2d%% (%2d/%2d)" "Test Accuracy of %5s: %2d%% (%2d/%2d)"
% ( % (
classes[i], classes[i],
100 * class_correct[i] / class_total[i], 100 * class_correct[i] / class_total[i],
np.sum(class_correct[i]), np.sum(class_correct[i]),
np.sum(class_total[i]), np.sum(class_total[i]),
) )
) )
else: else:
print("Test Accuracy of %5s: N/A (no training examples)" % (classes[i])) print("Test Accuracy of %5s: N/A (no training examples)" % (classes[i]))
print( print(
"\nTest Accuracy (Overall): %2d%% (%2d/%2d)" "\nTest Accuracy (Overall): %2d%% (%2d/%2d)"
% ( % (
100.0 * np.sum(class_correct) / np.sum(class_total), 100.0 * np.sum(class_correct) / np.sum(class_total),
np.sum(class_correct), np.sum(class_correct),
np.sum(class_total), np.sum(class_total),
) )
) )
``` ```
%% Cell type:markdown id:944991a2 tags: %% Cell type:markdown id:944991a2 tags:
Build a new network with the following structure. Build a new network with the following structure.
- It has 3 convolutional layers of kernel size 3 and padding of 1. - It has 3 convolutional layers of kernel size 3 and padding of 1.
- The first convolutional layer must output 16 channels, the second 32 and the third 64. - The first convolutional layer must output 16 channels, the second 32 and the third 64.
- At each convolutional layer output, we apply a ReLU activation then a MaxPool with kernel size of 2. - At each convolutional layer output, we apply a ReLU activation then a MaxPool with kernel size of 2.
- Then, three fully connected layers, the first two being followed by a ReLU activation and a dropout whose value you will suggest. - Then, three fully connected layers, the first two being followed by a ReLU activation and a dropout whose value you will suggest.
- The first fully connected layer will have an output size of 512. - The first fully connected layer will have an output size of 512.
- The second fully connected layer will have an output size of 64. - The second fully connected layer will have an output size of 64.
Compare the results obtained with this new network to those obtained previously. Compare the results obtained with this new network to those obtained previously.
%% Cell type:markdown id:bc381cf4 tags: %% Cell type:markdown id:bc381cf4 tags:
## Exercise 2: Quantization: try to compress the CNN to save space ## Exercise 2: Quantization: try to compress the CNN to save space
Quantization doc is available from https://pytorch.org/docs/stable/quantization.html#torch.quantization.quantize_dynamic Quantization doc is available from https://pytorch.org/docs/stable/quantization.html#torch.quantization.quantize_dynamic
The Exercise is to quantize post training the above CNN model. Compare the size reduction and the impact on the classification accuracy The Exercise is to quantize post training the above CNN model. Compare the size reduction and the impact on the classification accuracy
The size of the model is simply the size of the file. The size of the model is simply the size of the file.
%% Cell type:code id:ef623c26 tags: %% Cell type:code id:ef623c26 tags:
``` python ``` python
import os import os
def print_size_of_model(model, label=""): def print_size_of_model(model, label=""):
torch.save(model.state_dict(), "temp.p") torch.save(model.state_dict(), "temp.p")
size = os.path.getsize("temp.p") size = os.path.getsize("temp.p")
print("model: ", label, " \t", "Size (KB):", size / 1e3) print("model: ", label, " \t", "Size (KB):", size / 1e3)
os.remove("temp.p") os.remove("temp.p")
return size return size
print_size_of_model(model, "fp32") print_size_of_model(model, "fp32")
``` ```
%% Cell type:markdown id:05c4e9ad tags: %% Cell type:markdown id:05c4e9ad tags:
Post training quantization example Post training quantization example
%% Cell type:code id:c4c65d4b tags: %% Cell type:code id:c4c65d4b tags:
``` python ``` python
import torch.quantization import torch.quantization
quantized_model = torch.quantization.quantize_dynamic(model, dtype=torch.qint8) quantized_model = torch.quantization.quantize_dynamic(model, dtype=torch.qint8)
print_size_of_model(quantized_model, "int8") print_size_of_model(quantized_model, "int8")
``` ```
%% Cell type:markdown id:7b108e17 tags: %% Cell type:markdown id:7b108e17 tags:
For each class, compare the classification test accuracy of the initial model and the quantized model. Also give the overall test accuracy for both models. For each class, compare the classification test accuracy of the initial model and the quantized model. Also give the overall test accuracy for both models.
%% Cell type:markdown id:a0a34b90 tags: %% Cell type:markdown id:a0a34b90 tags:
Try training aware quantization to mitigate the impact on the accuracy (doc available here https://pytorch.org/docs/stable/quantization.html#torch.quantization.quantize_dynamic) Try training aware quantization to mitigate the impact on the accuracy (doc available here https://pytorch.org/docs/stable/quantization.html#torch.quantization.quantize_dynamic)
%% Cell type:markdown id:201470f9 tags: %% Cell type:markdown id:201470f9 tags:
## Exercise 3: working with pre-trained models. ## Exercise 3: working with pre-trained models.
PyTorch offers several pre-trained models https://pytorch.org/vision/0.8/models.html PyTorch offers several pre-trained models https://pytorch.org/vision/0.8/models.html
We will use ResNet50 trained on ImageNet dataset (https://www.image-net.org/index.php). Use the following code with the files `imagenet-simple-labels.json` that contains the imagenet labels and the image dog.png that we will use as test. We will use ResNet50 trained on ImageNet dataset (https://www.image-net.org/index.php). Use the following code with the files `imagenet-simple-labels.json` that contains the imagenet labels and the image dog.png that we will use as test.
%% Cell type:code id:b4d13080 tags: %% Cell type:code id:b4d13080 tags:
``` python ``` python
import json import json
from PIL import Image from PIL import Image
# Choose an image to pass through the model # Choose an image to pass through the model
test_image = "dog.png" test_image = "dog.png"
# Configure matplotlib for pretty inline plots # Configure matplotlib for pretty inline plots
#%matplotlib inline #%matplotlib inline
#%config InlineBackend.figure_format = 'retina' #%config InlineBackend.figure_format = 'retina'
# Prepare the labels # Prepare the labels
with open("imagenet-simple-labels.json") as f: with open("imagenet-simple-labels.json") as f:
labels = json.load(f) labels = json.load(f)
# First prepare the transformations: resize the image to what the model was trained on and convert it to a tensor # First prepare the transformations: resize the image to what the model was trained on and convert it to a tensor
data_transform = transforms.Compose( data_transform = transforms.Compose(
[ [
transforms.Resize((224, 224)), transforms.Resize((224, 224)),
transforms.ToTensor(), transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
] ]
) )
# Load the image # Load the image
image = Image.open(test_image) image = Image.open(test_image)
plt.imshow(image), plt.xticks([]), plt.yticks([]) plt.imshow(image), plt.xticks([]), plt.yticks([])
# Now apply the transformation, expand the batch dimension, and send the image to the GPU # Now apply the transformation, expand the batch dimension, and send the image to the GPU
# image = data_transform(image).unsqueeze(0).cuda() # image = data_transform(image).unsqueeze(0).cuda()
image = data_transform(image).unsqueeze(0) image = data_transform(image).unsqueeze(0)
# Download the model if it's not there already. It will take a bit on the first run, after that it's fast # Download the model if it's not there already. It will take a bit on the first run, after that it's fast
model = models.resnet50(pretrained=True) model = models.resnet50(pretrained=True)
# Send the model to the GPU # Send the model to the GPU
# model.cuda() # model.cuda()
# Set layers such as dropout and batchnorm in evaluation mode # Set layers such as dropout and batchnorm in evaluation mode
model.eval() model.eval()
# Get the 1000-dimensional model output # Get the 1000-dimensional model output
out = model(image) out = model(image)
# Find the predicted class # Find the predicted class
print("Predicted class is: {}".format(labels[out.argmax()])) print("Predicted class is: {}".format(labels[out.argmax()]))
``` ```
%% Cell type:markdown id:184cfceb tags: %% Cell type:markdown id:184cfceb tags:
Experiments: Experiments:
Study the code and the results obtained. Possibly add other images downloaded from the internet. Study the code and the results obtained. Possibly add other images downloaded from the internet.
What is the size of the model? Quantize it and then check if the model is still able to correctly classify the other images. What is the size of the model? Quantize it and then check if the model is still able to correctly classify the other images.
Experiment with other pre-trained CNN models. Experiment with other pre-trained CNN models.
%% Cell type:markdown id:5d57da4b tags: %% Cell type:markdown id:5d57da4b tags:
## Exercise 4: Transfer Learning ## Exercise 4: Transfer Learning
For this work, we will use a pre-trained model (ResNet18) as a descriptor extractor and will refine the classification by training only the last fully connected layer of the network. Thus, the output layer of the pre-trained network will be replaced by a layer adapted to the new classes to be recognized which will be in our case ants and bees. For this work, we will use a pre-trained model (ResNet18) as a descriptor extractor and will refine the classification by training only the last fully connected layer of the network. Thus, the output layer of the pre-trained network will be replaced by a layer adapted to the new classes to be recognized which will be in our case ants and bees.
Download and unzip in your working directory the dataset available at the address : Download and unzip in your working directory the dataset available at the address :
https://download.pytorch.org/tutorial/hymenoptera_data.zip https://download.pytorch.org/tutorial/hymenoptera_data.zip
Execute the following code in order to display some images of the dataset. Execute the following code in order to display some images of the dataset.
%% Cell type:code id:be2d31f5 tags: %% Cell type:code id:be2d31f5 tags:
``` python ``` python
import os import os
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import numpy as np import numpy as np
import torch import torch
import torchvision import torchvision
from torchvision import datasets, transforms from torchvision import datasets, transforms
# Data augmentation and normalization for training # Data augmentation and normalization for training
# Just normalization for validation # Just normalization for validation
data_transforms = { data_transforms = {
"train": transforms.Compose( "train": transforms.Compose(
[ [
transforms.RandomResizedCrop( transforms.RandomResizedCrop(
224 224
), # ImageNet models were trained on 224x224 images ), # ImageNet models were trained on 224x224 images
transforms.RandomHorizontalFlip(), # flip horizontally 50% of the time - increases train set variability transforms.RandomHorizontalFlip(), # flip horizontally 50% of the time - increases train set variability
transforms.ToTensor(), # convert it to a PyTorch tensor transforms.ToTensor(), # convert it to a PyTorch tensor
transforms.Normalize( transforms.Normalize(
[0.485, 0.456, 0.406], [0.229, 0.224, 0.225] [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]
), # ImageNet models expect this norm ), # ImageNet models expect this norm
] ]
), ),
"val": transforms.Compose( "val": transforms.Compose(
[ [
transforms.Resize(256), transforms.Resize(256),
transforms.CenterCrop(224), transforms.CenterCrop(224),
transforms.ToTensor(), transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
] ]
), ),
} }
data_dir = "hymenoptera_data" data_dir = "hymenoptera_data"
# Create train and validation datasets and loaders # Create train and validation datasets and loaders
image_datasets = { image_datasets = {
x: datasets.ImageFolder(os.path.join(data_dir, x), data_transforms[x]) x: datasets.ImageFolder(os.path.join(data_dir, x), data_transforms[x])
for x in ["train", "val"] for x in ["train", "val"]
} }
dataloaders = { dataloaders = {
x: torch.utils.data.DataLoader( x: torch.utils.data.DataLoader(
image_datasets[x], batch_size=4, shuffle=True, num_workers=0 image_datasets[x], batch_size=4, shuffle=True, num_workers=0
) )
for x in ["train", "val"] for x in ["train", "val"]
} }
dataset_sizes = {x: len(image_datasets[x]) for x in ["train", "val"]} dataset_sizes = {x: len(image_datasets[x]) for x in ["train", "val"]}
class_names = image_datasets["train"].classes class_names = image_datasets["train"].classes
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# Helper function for displaying images # Helper function for displaying images
def imshow(inp, title=None): def imshow(inp, title=None):
"""Imshow for Tensor.""" """Imshow for Tensor."""
inp = inp.numpy().transpose((1, 2, 0)) inp = inp.numpy().transpose((1, 2, 0))
mean = np.array([0.485, 0.456, 0.406]) mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225]) std = np.array([0.229, 0.224, 0.225])
# Un-normalize the images # Un-normalize the images
inp = std * inp + mean inp = std * inp + mean
# Clip just in case # Clip just in case
inp = np.clip(inp, 0, 1) inp = np.clip(inp, 0, 1)
plt.imshow(inp) plt.imshow(inp)
if title is not None: if title is not None:
plt.title(title) plt.title(title)
plt.pause(0.001) # pause a bit so that plots are updated plt.pause(0.001) # pause a bit so that plots are updated
plt.show() plt.show()
# Get a batch of training data # Get a batch of training data
inputs, classes = next(iter(dataloaders["train"])) inputs, classes = next(iter(dataloaders["train"]))
# Make a grid from batch # Make a grid from batch
out = torchvision.utils.make_grid(inputs) out = torchvision.utils.make_grid(inputs)
imshow(out, title=[class_names[x] for x in classes]) imshow(out, title=[class_names[x] for x in classes])
``` ```
%% Cell type:markdown id:bbd48800 tags: %% Cell type:markdown id:bbd48800 tags:
Now, execute the following code which uses a pre-trained model ResNet18 having replaced the output layer for the ants/bees classification and performs the model training by only changing the weights of this output layer. Now, execute the following code which uses a pre-trained model ResNet18 having replaced the output layer for the ants/bees classification and performs the model training by only changing the weights of this output layer.
%% Cell type:code id:572d824c tags: %% Cell type:code id:572d824c tags:
``` python ``` python
import copy import copy
import os import os
import time import time
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import numpy as np import numpy as np
import torch import torch
import torch.nn as nn import torch.nn as nn
import torch.optim as optim import torch.optim as optim
import torchvision import torchvision
from torch.optim import lr_scheduler from torch.optim import lr_scheduler
from torchvision import datasets, transforms from torchvision import datasets, transforms
# Data augmentation and normalization for training # Data augmentation and normalization for training
# Just normalization for validation # Just normalization for validation
data_transforms = { data_transforms = {
"train": transforms.Compose( "train": transforms.Compose(
[ [
transforms.RandomResizedCrop( transforms.RandomResizedCrop(
224 224
), # ImageNet models were trained on 224x224 images ), # ImageNet models were trained on 224x224 images
transforms.RandomHorizontalFlip(), # flip horizontally 50% of the time - increases train set variability transforms.RandomHorizontalFlip(), # flip horizontally 50% of the time - increases train set variability
transforms.ToTensor(), # convert it to a PyTorch tensor transforms.ToTensor(), # convert it to a PyTorch tensor
transforms.Normalize( transforms.Normalize(
[0.485, 0.456, 0.406], [0.229, 0.224, 0.225] [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]
), # ImageNet models expect this norm ), # ImageNet models expect this norm
] ]
), ),
"val": transforms.Compose( "val": transforms.Compose(
[ [
transforms.Resize(256), transforms.Resize(256),
transforms.CenterCrop(224), transforms.CenterCrop(224),
transforms.ToTensor(), transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
] ]
), ),
} }
data_dir = "hymenoptera_data" data_dir = "hymenoptera_data"
# Create train and validation datasets and loaders # Create train and validation datasets and loaders
image_datasets = { image_datasets = {
x: datasets.ImageFolder(os.path.join(data_dir, x), data_transforms[x]) x: datasets.ImageFolder(os.path.join(data_dir, x), data_transforms[x])
for x in ["train", "val"] for x in ["train", "val"]
} }
dataloaders = { dataloaders = {
x: torch.utils.data.DataLoader( x: torch.utils.data.DataLoader(
image_datasets[x], batch_size=4, shuffle=True, num_workers=4 image_datasets[x], batch_size=4, shuffle=True, num_workers=4
) )
for x in ["train", "val"] for x in ["train", "val"]
} }
dataset_sizes = {x: len(image_datasets[x]) for x in ["train", "val"]} dataset_sizes = {x: len(image_datasets[x]) for x in ["train", "val"]}
class_names = image_datasets["train"].classes class_names = image_datasets["train"].classes
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# Helper function for displaying images # Helper function for displaying images
def imshow(inp, title=None): def imshow(inp, title=None):
"""Imshow for Tensor.""" """Imshow for Tensor."""
inp = inp.numpy().transpose((1, 2, 0)) inp = inp.numpy().transpose((1, 2, 0))
mean = np.array([0.485, 0.456, 0.406]) mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225]) std = np.array([0.229, 0.224, 0.225])
# Un-normalize the images # Un-normalize the images
inp = std * inp + mean inp = std * inp + mean
# Clip just in case # Clip just in case
inp = np.clip(inp, 0, 1) inp = np.clip(inp, 0, 1)
plt.imshow(inp) plt.imshow(inp)
if title is not None: if title is not None:
plt.title(title) plt.title(title)
plt.pause(0.001) # pause a bit so that plots are updated plt.pause(0.001) # pause a bit so that plots are updated
plt.show() plt.show()
# Get a batch of training data # Get a batch of training data
# inputs, classes = next(iter(dataloaders['train'])) # inputs, classes = next(iter(dataloaders['train']))
# Make a grid from batch # Make a grid from batch
# out = torchvision.utils.make_grid(inputs) # out = torchvision.utils.make_grid(inputs)
# imshow(out, title=[class_names[x] for x in classes]) # imshow(out, title=[class_names[x] for x in classes])
# training # training
def train_model(model, criterion, optimizer, scheduler, num_epochs=25): def train_model(model, criterion, optimizer, scheduler, num_epochs=25):
since = time.time() since = time.time()
best_model_wts = copy.deepcopy(model.state_dict()) best_model_wts = copy.deepcopy(model.state_dict())
best_acc = 0.0 best_acc = 0.0
epoch_time = [] # we'll keep track of the time needed for each epoch epoch_time = [] # we'll keep track of the time needed for each epoch
for epoch in range(num_epochs): for epoch in range(num_epochs):
epoch_start = time.time() epoch_start = time.time()
print("Epoch {}/{}".format(epoch + 1, num_epochs)) print("Epoch {}/{}".format(epoch + 1, num_epochs))
print("-" * 10) print("-" * 10)
# Each epoch has a training and validation phase # Each epoch has a training and validation phase
for phase in ["train", "val"]: for phase in ["train", "val"]:
if phase == "train": if phase == "train":
scheduler.step() scheduler.step()
model.train() # Set model to training mode model.train() # Set model to training mode
else: else:
model.eval() # Set model to evaluate mode model.eval() # Set model to evaluate mode
running_loss = 0.0 running_loss = 0.0
running_corrects = 0 running_corrects = 0
# Iterate over data. # Iterate over data.
for inputs, labels in dataloaders[phase]: for inputs, labels in dataloaders[phase]:
inputs = inputs.to(device) inputs = inputs.to(device)
labels = labels.to(device) labels = labels.to(device)
# zero the parameter gradients # zero the parameter gradients
optimizer.zero_grad() optimizer.zero_grad()
# Forward # Forward
# Track history if only in training phase # Track history if only in training phase
with torch.set_grad_enabled(phase == "train"): with torch.set_grad_enabled(phase == "train"):
outputs = model(inputs) outputs = model(inputs)
_, preds = torch.max(outputs, 1) _, preds = torch.max(outputs, 1)
loss = criterion(outputs, labels) loss = criterion(outputs, labels)
# backward + optimize only if in training phase # backward + optimize only if in training phase
if phase == "train": if phase == "train":
loss.backward() loss.backward()
optimizer.step() optimizer.step()
# Statistics # Statistics
running_loss += loss.item() * inputs.size(0) running_loss += loss.item() * inputs.size(0)
running_corrects += torch.sum(preds == labels.data) running_corrects += torch.sum(preds == labels.data)
epoch_loss = running_loss / dataset_sizes[phase] epoch_loss = running_loss / dataset_sizes[phase]
epoch_acc = running_corrects.double() / dataset_sizes[phase] epoch_acc = running_corrects.double() / dataset_sizes[phase]
print("{} Loss: {:.4f} Acc: {:.4f}".format(phase, epoch_loss, epoch_acc)) print("{} Loss: {:.4f} Acc: {:.4f}".format(phase, epoch_loss, epoch_acc))
# Deep copy the model # Deep copy the model
if phase == "val" and epoch_acc > best_acc: if phase == "val" and epoch_acc > best_acc:
best_acc = epoch_acc best_acc = epoch_acc
best_model_wts = copy.deepcopy(model.state_dict()) best_model_wts = copy.deepcopy(model.state_dict())
# Add the epoch time # Add the epoch time
t_epoch = time.time() - epoch_start t_epoch = time.time() - epoch_start
epoch_time.append(t_epoch) epoch_time.append(t_epoch)
print() print()
time_elapsed = time.time() - since time_elapsed = time.time() - since
print( print(
"Training complete in {:.0f}m {:.0f}s".format( "Training complete in {:.0f}m {:.0f}s".format(
time_elapsed // 60, time_elapsed % 60 time_elapsed // 60, time_elapsed % 60
) )
) )
print("Best val Acc: {:4f}".format(best_acc)) print("Best val Acc: {:4f}".format(best_acc))
# Load best model weights # Load best model weights
model.load_state_dict(best_model_wts) model.load_state_dict(best_model_wts)
return model, epoch_time return model, epoch_time
# Download a pre-trained ResNet18 model and freeze its weights # Download a pre-trained ResNet18 model and freeze its weights
model = torchvision.models.resnet18(pretrained=True) model = torchvision.models.resnet18(pretrained=True)
for param in model.parameters(): for param in model.parameters():
param.requires_grad = False param.requires_grad = False
# Replace the final fully connected layer # Replace the final fully connected layer
# Parameters of newly constructed modules have requires_grad=True by default # Parameters of newly constructed modules have requires_grad=True by default
num_ftrs = model.fc.in_features num_ftrs = model.fc.in_features
model.fc = nn.Linear(num_ftrs, 2) model.fc = nn.Linear(num_ftrs, 2)
# Send the model to the GPU # Send the model to the GPU
model = model.to(device) model = model.to(device)
# Set the loss function # Set the loss function
criterion = nn.CrossEntropyLoss() criterion = nn.CrossEntropyLoss()
# Observe that only the parameters of the final layer are being optimized # Observe that only the parameters of the final layer are being optimized
optimizer_conv = optim.SGD(model.fc.parameters(), lr=0.001, momentum=0.9) optimizer_conv = optim.SGD(model.fc.parameters(), lr=0.001, momentum=0.9)
exp_lr_scheduler = lr_scheduler.StepLR(optimizer_conv, step_size=7, gamma=0.1) exp_lr_scheduler = lr_scheduler.StepLR(optimizer_conv, step_size=7, gamma=0.1)
model, epoch_time = train_model( model, epoch_time = train_model(
model, criterion, optimizer_conv, exp_lr_scheduler, num_epochs=10 model, criterion, optimizer_conv, exp_lr_scheduler, num_epochs=10
) )
``` ```
%% Cell type:markdown id:bbd48800 tags: %% Cell type:markdown id:bbd48800 tags:
Experiments: Experiments:
Study the code and the results obtained. Study the code and the results obtained.
Modify the code and add an "eval_model" function to allow Modify the code and add an "eval_model" function to allow
the evaluation of the model on a test set (different from the learning and validation sets used during the learning phase). Study the results obtained. the evaluation of the model on a test set (different from the learning and validation sets used during the learning phase). Study the results obtained.
Now modify the code to replace the current classification layer with a set of two layers using a "relu" activation function for the middle layer, and the "dropout" mechanism for both layers. Renew the experiments and study the results obtained. Now modify the code to replace the current classification layer with a set of two layers using a "relu" activation function for the middle layer, and the "dropout" mechanism for both layers. Renew the experiments and study the results obtained.
Apply ther quantization (post and quantization aware) and evaluate impact on model size and accuracy. Apply ther quantization (post and quantization aware) and evaluate impact on model size and accuracy.
%% Cell type:markdown id:04a263f0 tags: %% Cell type:markdown id:04a263f0 tags:
## Optional ## Optional
Try this at home!! Try this at home!!
Pytorch offers a framework to export a given CNN to your selfphone (either android or iOS). Have a look at the tutorial https://pytorch.org/mobile/home/ Pytorch offers a framework to export a given CNN to your selfphone (either android or iOS). Have a look at the tutorial https://pytorch.org/mobile/home/
The Exercise consists in deploying the CNN of Exercise 4 in your phone and then test it on live. The Exercise consists in deploying the CNN of Exercise 4 in your phone and then test it on live.
%% Cell type:markdown id:fe954ce4 tags: %% Cell type:markdown id:fe954ce4 tags:
## Author ## Author
Alberto BOSIO - Ph. D. Alberto BOSIO - Ph. D.
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment