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.
File c:\Users\xxpod\AppData\Local\Programs\Python\Python312\Lib\site-packages\torch\nn\modules\module.py:1747, in Module._call_impl(self, *args, **kwargs)
1742 # If we don't have any hooks, we want to skip the rest of the logic in
1743 # this function, and just call forward.
1744 if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks or self._forward_pre_hooks
1745 or _global_backward_pre_hooks or _global_backward_hooks
1746 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1747 return forward_call(*args, **kwargs)
1749 result = None
1750 called_always_called_hooks = set()
File c:\Users\xxpod\AppData\Local\Programs\Python\Python312\Lib\site-packages\torch\nn\modules\pooling.py:213, in MaxPool2d.forward(self, input)
212 def forward(self, input: Tensor):
--> 213 return F.max_pool2d(
214 input,
215 self.kernel_size,
216 self.stride,
217 self.padding,
218 self.dilation,
219 ceil_mode=self.ceil_mode,
220 return_indices=self.return_indices,
221 )
File c:\Users\xxpod\AppData\Local\Programs\Python\Python312\Lib\site-packages\torch\_jit_internal.py:624, in boolean_dispatch.<locals>.fn(*args, **kwargs)
622 return if_true(*args, **kwargs)
623 else:
--> 624 return if_false(*args, **kwargs)
File c:\Users\xxpod\AppData\Local\Programs\Python\Python312\Lib\site-packages\torch\nn\functional.py:830, in _max_pool2d(input, kernel_size, stride, padding, dilation, ceil_mode, return_indices)
# forward pass: compute predicted outputs by passing inputs to the model
output=model(data)
# calculate the batch loss
loss=criterion(output,target)
# update test loss
test_loss+=loss.item()*data.size(0)
# convert output probabilities to predicted class
_,pred=torch.max(output,1)
# compare predictions to true label
correct_tensor=pred.eq(target.data.view_as(pred))
correct=(
np.squeeze(correct_tensor.numpy())
ifnottrain_on_gpu
elsenp.squeeze(correct_tensor.cpu().numpy())
)
# calculate test accuracy for each object class
foriinrange(batch_size):
label=target.data[i]
class_correct[label]+=correct[i].item()
class_total[label]+=1
# average test loss
test_loss=test_loss/len(test_loader)
print("Test Loss: {:.6f}\n".format(test_loss))
foriinrange(10):
ifclass_total[i]>0:
print(
"Test Accuracy of %5s: %2d%% (%2d/%2d)"
%(
classes[i],
100*class_correct[i]/class_total[i],
np.sum(class_correct[i]),
np.sum(class_total[i]),
)
)
else:
print("Test Accuracy of %5s: N/A (no training examples)"%(classes[i]))
print(
"\nTest Accuracy (Overall): %2d%% (%2d/%2d)"
%(
100.0*np.sum(class_correct)/np.sum(class_total),
np.sum(class_correct),
np.sum(class_total),
)
)
```
%% Output
C:\Users\xxpod\AppData\Local\Temp\ipykernel_18828\3291884398.py:1: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.
- 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.
- 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.
- The first fully connected layer will have an output size of 512.
- The second fully connected layer will have an output size of 64.
Compare the results obtained with this new network to those obtained previously.
ANSWER: The model is built above and named Net_Conv3_Lin3
Results for the previous model :
we osberve overfitting from about the 10nth Epoch - validation loss plateaued at 22 but training loss kept on decreasing to 10 , as can be seen from the training logs:
Epoch: 7 Training Loss: 23.183946 Validation Loss: 24.331222
Validation loss decreased (25.691083 --> 24.331222). Saving model ...
Epoch: 8 Training Loss: 22.215979 Validation Loss: 23.632853
Validation loss decreased (24.331222 --> 23.632853). Saving model ...
Epoch: 9 Training Loss: 21.408623 Validation Loss: 23.475442
Validation loss decreased (23.632853 --> 23.475442). Saving model ...
Epoch: 10 Training Loss: 20.637072 Validation Loss: 23.639358
Epoch: 11 Training Loss: 19.877338 Validation Loss: 22.408472
Validation loss decreased (23.475442 --> 22.408472). Saving model ...
Epoch: 12 Training Loss: 19.188079 Validation Loss: 23.296445
Epoch: 13 Training Loss: 18.647543 Validation Loss: 22.897815
Epoch: 14 Training Loss: 17.989626 Validation Loss: 22.755968
the performance is as follow: 
and the final accuries were:

SECOND MODEL:
for the second model, the validation loss goes lower, thougth in addition to the architectural changes, there are also just more weigth and it is longer to train.
we archieve a valisation loss of 16, and the model is still improving after a larger number of epoch ( 20 vs 10)
here are the final accuracies:
Test Loss: 16.123924
Test Accuracy of airplane: 81% (810/1000)
Test Accuracy of automobile: 85% (855/1000)
Test Accuracy of bird: 63% (633/1000)
Test Accuracy of cat: 52% (525/1000)
Test Accuracy of deer: 69% (695/1000)
Test Accuracy of dog: 71% (717/1000)
Test Accuracy of frog: 77% (772/1000)
Test Accuracy of horse: 77% (772/1000)
Test Accuracy of ship: 84% (843/1000)
Test Accuracy of truck: 76% (765/1000)
Test Accuracy (Overall): 73% (7387/10000)
%% Cell type:markdown id:bc381cf4 tags:
## 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
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.
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.
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:
## Exercise 3: working with pre-trained models.
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.
%% Cell type:code id:b4d13080 tags:
``` python
importjson
fromPILimportImage
# Choose an image to pass through the model
test_image="dog.png"
# Configure matplotlib for pretty inline plots
#%matplotlib inline
#%config InlineBackend.figure_format = 'retina'
# Prepare the labels
withopen("imagenet-simple-labels.json")asf:
labels=json.load(f)
# 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
model=models.resnet50(pretrained=True)
# Send the model to the GPU
# model.cuda()
# Set layers such as dropout and batchnorm in evaluation mode
model.eval()
# Get the 1000-dimensional model output
out=model(image)
# Find the predicted class
print("Predicted class is: {}".format(labels[out.argmax()]))
```
%% Cell type:markdown id:184cfceb tags:
Experiments:
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.
Experiment with other pre-trained CNN models.
%% Cell type:markdown id:5d57da4b tags:
## 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.
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.show()
# Get a batch of training data
inputs,classes=next(iter(dataloaders["train"]))
# Make a grid from batch
out=torchvision.utils.make_grid(inputs)
imshow(out,title=[class_names[x]forxinclasses])
```
%% 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.
%% Cell type:code id:572d824c tags:
``` python
importcopy
importos
importtime
importmatplotlib.pyplotasplt
importnumpyasnp
importtorch
importtorch.nnasnn
importtorch.optimasoptim
importtorchvision
fromtorch.optimimportlr_scheduler
fromtorchvisionimportdatasets,transforms
# Data augmentation and normalization for training
# Just normalization for validation
data_transforms={
"train":transforms.Compose(
[
transforms.RandomResizedCrop(
224
),# ImageNet models were trained on 224x224 images
transforms.RandomHorizontalFlip(),# flip horizontally 50% of the time - increases train set variability
transforms.ToTensor(),# convert it to a PyTorch tensor
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.
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.
%% Cell type:markdown id:04a263f0 tags:
## Optional
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/
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:
## Author
Alberto BOSIO - Ph. D.
...
...
%% Cell type:markdown id:7edf7168 tags:
# TD2: Deep learning
%% Cell type:markdown id:fbb8c8df tags:
In this TD, you must modify this notebook to answer the questions. To do this,
1. Fork this repository
2. Clone your forked repository on your local computer
3. Answer the questions
4. Commit and push regularly
The last commit is due on Wednesday, December 4, 11:59 PM. Later commits will not be taken into account.
%% Cell type:markdown id:3d167a29 tags:
Install and test PyTorch from https://pytorch.org/get-started/locally.
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.
File c:\Users\xxpod\AppData\Local\Programs\Python\Python312\Lib\site-packages\torch\nn\modules\module.py:1747, in Module._call_impl(self, *args, **kwargs)
1742 # If we don't have any hooks, we want to skip the rest of the logic in
1743 # this function, and just call forward.
1744 if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks or self._forward_pre_hooks
1745 or _global_backward_pre_hooks or _global_backward_hooks
1746 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1747 return forward_call(*args, **kwargs)
1749 result = None
1750 called_always_called_hooks = set()
File c:\Users\xxpod\AppData\Local\Programs\Python\Python312\Lib\site-packages\torch\nn\modules\pooling.py:213, in MaxPool2d.forward(self, input)
212 def forward(self, input: Tensor):
--> 213 return F.max_pool2d(
214 input,
215 self.kernel_size,
216 self.stride,
217 self.padding,
218 self.dilation,
219 ceil_mode=self.ceil_mode,
220 return_indices=self.return_indices,
221 )
File c:\Users\xxpod\AppData\Local\Programs\Python\Python312\Lib\site-packages\torch\_jit_internal.py:624, in boolean_dispatch.<locals>.fn(*args, **kwargs)
622 return if_true(*args, **kwargs)
623 else:
--> 624 return if_false(*args, **kwargs)
File c:\Users\xxpod\AppData\Local\Programs\Python\Python312\Lib\site-packages\torch\nn\functional.py:830, in _max_pool2d(input, kernel_size, stride, padding, dilation, ceil_mode, return_indices)
# forward pass: compute predicted outputs by passing inputs to the model
output=model(data)
# calculate the batch loss
loss=criterion(output,target)
# update test loss
test_loss+=loss.item()*data.size(0)
# convert output probabilities to predicted class
_,pred=torch.max(output,1)
# compare predictions to true label
correct_tensor=pred.eq(target.data.view_as(pred))
correct=(
np.squeeze(correct_tensor.numpy())
ifnottrain_on_gpu
elsenp.squeeze(correct_tensor.cpu().numpy())
)
# calculate test accuracy for each object class
foriinrange(batch_size):
label=target.data[i]
class_correct[label]+=correct[i].item()
class_total[label]+=1
# average test loss
test_loss=test_loss/len(test_loader)
print("Test Loss: {:.6f}\n".format(test_loss))
foriinrange(10):
ifclass_total[i]>0:
print(
"Test Accuracy of %5s: %2d%% (%2d/%2d)"
%(
classes[i],
100*class_correct[i]/class_total[i],
np.sum(class_correct[i]),
np.sum(class_total[i]),
)
)
else:
print("Test Accuracy of %5s: N/A (no training examples)"%(classes[i]))
print(
"\nTest Accuracy (Overall): %2d%% (%2d/%2d)"
%(
100.0*np.sum(class_correct)/np.sum(class_total),
np.sum(class_correct),
np.sum(class_total),
)
)
```
%% Output
C:\Users\xxpod\AppData\Local\Temp\ipykernel_18828\3291884398.py:1: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.
- 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.
- 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.
- The first fully connected layer will have an output size of 512.
- The second fully connected layer will have an output size of 64.
Compare the results obtained with this new network to those obtained previously.
ANSWER: The model is built above and named Net_Conv3_Lin3
Results for the previous model :
we osberve overfitting from about the 10nth Epoch - validation loss plateaued at 22 but training loss kept on decreasing to 10 , as can be seen from the training logs:
Epoch: 7 Training Loss: 23.183946 Validation Loss: 24.331222
Validation loss decreased (25.691083 --> 24.331222). Saving model ...
Epoch: 8 Training Loss: 22.215979 Validation Loss: 23.632853
Validation loss decreased (24.331222 --> 23.632853). Saving model ...
Epoch: 9 Training Loss: 21.408623 Validation Loss: 23.475442
Validation loss decreased (23.632853 --> 23.475442). Saving model ...
Epoch: 10 Training Loss: 20.637072 Validation Loss: 23.639358
Epoch: 11 Training Loss: 19.877338 Validation Loss: 22.408472
Validation loss decreased (23.475442 --> 22.408472). Saving model ...
Epoch: 12 Training Loss: 19.188079 Validation Loss: 23.296445
Epoch: 13 Training Loss: 18.647543 Validation Loss: 22.897815
Epoch: 14 Training Loss: 17.989626 Validation Loss: 22.755968
the performance is as follow: 
and the final accuries were:

SECOND MODEL:
for the second model, the validation loss goes lower, thougth in addition to the architectural changes, there are also just more weigth and it is longer to train.
we archieve a valisation loss of 16, and the model is still improving after a larger number of epoch ( 20 vs 10)
here are the final accuracies:
Test Loss: 16.123924
Test Accuracy of airplane: 81% (810/1000)
Test Accuracy of automobile: 85% (855/1000)
Test Accuracy of bird: 63% (633/1000)
Test Accuracy of cat: 52% (525/1000)
Test Accuracy of deer: 69% (695/1000)
Test Accuracy of dog: 71% (717/1000)
Test Accuracy of frog: 77% (772/1000)
Test Accuracy of horse: 77% (772/1000)
Test Accuracy of ship: 84% (843/1000)
Test Accuracy of truck: 76% (765/1000)
Test Accuracy (Overall): 73% (7387/10000)
%% Cell type:markdown id:bc381cf4 tags:
## 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
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.
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.
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:
## Exercise 3: working with pre-trained models.
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.
%% Cell type:code id:b4d13080 tags:
``` python
importjson
fromPILimportImage
# Choose an image to pass through the model
test_image="dog.png"
# Configure matplotlib for pretty inline plots
#%matplotlib inline
#%config InlineBackend.figure_format = 'retina'
# Prepare the labels
withopen("imagenet-simple-labels.json")asf:
labels=json.load(f)
# 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
model=models.resnet50(pretrained=True)
# Send the model to the GPU
# model.cuda()
# Set layers such as dropout and batchnorm in evaluation mode
model.eval()
# Get the 1000-dimensional model output
out=model(image)
# Find the predicted class
print("Predicted class is: {}".format(labels[out.argmax()]))
```
%% Cell type:markdown id:184cfceb tags:
Experiments:
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.
Experiment with other pre-trained CNN models.
%% Cell type:markdown id:5d57da4b tags:
## 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.
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.show()
# Get a batch of training data
inputs,classes=next(iter(dataloaders["train"]))
# Make a grid from batch
out=torchvision.utils.make_grid(inputs)
imshow(out,title=[class_names[x]forxinclasses])
```
%% 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.
%% Cell type:code id:572d824c tags:
``` python
importcopy
importos
importtime
importmatplotlib.pyplotasplt
importnumpyasnp
importtorch
importtorch.nnasnn
importtorch.optimasoptim
importtorchvision
fromtorch.optimimportlr_scheduler
fromtorchvisionimportdatasets,transforms
# Data augmentation and normalization for training
# Just normalization for validation
data_transforms={
"train":transforms.Compose(
[
transforms.RandomResizedCrop(
224
),# ImageNet models were trained on 224x224 images
transforms.RandomHorizontalFlip(),# flip horizontally 50% of the time - increases train set variability
transforms.ToTensor(),# convert it to a PyTorch tensor
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.
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.
%% Cell type:markdown id:04a263f0 tags:
## Optional
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/
The Exercise consists in deploying the CNN of Exercise 4 in your phone and then test it on live.