"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: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
%pipinstalltorchtorchvision
%pipinstalltorchtorchvision
```
```
%% 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
importtorch
importtorch
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)
fromtorchvisionimportmodels
fromtorchvisionimportmodels
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.
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
importjson
importjson
fromPILimportImage
fromPILimportImage
# 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
withopen("imagenet-simple-labels.json")asf:
withopen("imagenet-simple-labels.json")asf:
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
# 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 :
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]forxinclasses])
imshow(out,title=[class_names[x]forxinclasses])
```
```
%% 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
importcopy
importcopy
importos
importos
importtime
importtime
importmatplotlib.pyplotasplt
importmatplotlib.pyplotasplt
importnumpyasnp
importnumpyasnp
importtorch
importtorch
importtorch.nnasnn
importtorch.nnasnn
importtorch.optimasoptim
importtorch.optimasoptim
importtorchvision
importtorchvision
fromtorch.optimimportlr_scheduler
fromtorch.optimimportlr_scheduler
fromtorchvisionimportdatasets,transforms
fromtorchvisionimportdatasets,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
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.