TD2: Deep learning

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 Sunday, December 1, 11:59 PM. Later commits will not be taken into account.

Install and test PyTorch from https://pytorch.org/get-started/locally.

To test run the following code

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.

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/deep_learning_60min_blitz.html

You can test if GPU is available on your machine and thus train on it to speed up the process

Next we load the CIFAR10 dataset

CNN definition (this one is an example)

Loss function and training using SGD (Stochastic Gradient Descent) optimizer

Does overfit occur? If so, do an early stopping.

Oui il y a de l'overfitting. A parir de l'epoche 11.

Now loading the model with the lowest validation loss value

Build a new network with the following structure.

Compare the results obtained with this new network to those obtained previously.

On crée la nouvelle architecture du réseau CNN de la même manière. On l'appellera model 2.

On entraine maintenant l'algorithme.

On affiche le train lost en fonction du nombre d'époches.

On calcule la precision du modèle sur une base de données test.

La précision est meilleure pour presque toutes les classes (la classe truck a une précision plus faible).

Au global, la précision avec cette nouvelle architecture est meilleure (71%) que la précedente (62%).

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.

La taille initial du modèle 1 est de 251.278 KB

On va compresser ce modèle :

Le modèle compressé a une taille de 76.522 KB. Il y a donc eu une réduction de 174.756 KB.

En terme de précision, elle est la même en pourcentage pour presque toutes les classes (en comparaison avec le modèle non compressé).

Elle différe de 1% pour la classe horse.

Au global, la précision est la même.

Le modèle compressé conserve la précision du modèle tout en réduisant sa taille.


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)

On va essayer le training aware quantization

On recrée un nouveau modèle à partir du modèle 1.

La taille du modèle compressé est de 76.522 KB. La précision globale est plus faible par rapport au modèle, elle est de 61%.

Les performances sont équivalentes à la quantization précédente.

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.

La prédiction d'une image se fait en plusieurs étapes :

-On resize l'image a la taille 224.

-On transforme en tenseur.

-On normalise

-On charge le modèle pre-entrainé.

-On fait la prédiction.

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.

On va tester ce modèle sur une autre image : un king crab.

Il faudra bien que l'image soit une image RGB.

Les classifications pour le Golden Retriever et le King Crab sont bonnes. Le modèle semble être bon.


Etudions la taille du modèle

Le modèle pré-entrainé a une taille de 102523.238 KB. Après compression sa taille est de 96379.996 KB.

Les prédictions sont toujours bonne avec le modèle compressé.

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 :

https://download.pytorch.org/tutorial/hymenoptera_data.zip

Execute the following code in order to display some images of the dataset.

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.

Experiments: Study the code and the results obtained.

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.


Dans cette partie, nous allons ajouter un dataset de test. On configure le data_transform pour qu'il prennent en compte les données test contenu dans le dossier test.

On va aussi configurer la sortie avec la nouvelle structure de neurones.

On a entraîné ce nouveau modèle. on définit maintenant la fonction eval_model(model), qui va évaluer les performances du modèle sur le data test.

On ajoute un test d'évaluation du modèle avec de nouvelles données

On obtient une précision de 1 sur l'échantillon test. (il faudrait ajouter plus de photos)


On va maintenant quantizer le modèle et comparer la taille des modèles.

La quantization permet de passer de 45304.25 à 44911.014 KB.

On étudie les performances du modèle.

Le modèle quantizé permet aussi d'atteindre une précision de 1.

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.

Author

Alberto BOSIO - Ph. D.