Skip to content
Snippets Groups Projects
Commit 9f1e5731 authored by Paganelli Emilien's avatar Paganelli Emilien
Browse files

update the name of file

parent 37fce13b
Branches main
No related tags found
No related merge requests found
{"cells":[{"cell_type":"markdown","id":"7edf7168","metadata":{"id":"7edf7168"},"source":["# TD2: Deep learning"]},{"cell_type":"markdown","id":"fbb8c8df","metadata":{"id":"fbb8c8df"},"source":["In this TD, you must modify this notebook to answer the questions. To do this,\n","\n","1. Fork this repository\n","2. Clone your forked repository on your local computer\n","3. Answer the questions\n","4. Commit and push regularly\n","\n","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","metadata":{"id":"3d167a29"},"source":["Install and test PyTorch from https://pytorch.org/get-started/locally."]},{"cell_type":"markdown","source":[],"metadata":{"id":"QCeGtWXR9J0y"},"id":"QCeGtWXR9J0y"},{"cell_type":"code","execution_count":27,"id":"330a42f5","metadata":{"colab":{"base_uri":"https://localhost:8080/","height":348},"id":"330a42f5","executionInfo":{"status":"ok","timestamp":1701426305624,"user_tz":-60,"elapsed":7349,"user":{"displayName":"Emilien Paganelli","userId":"14204960141695635735"}},"outputId":"2919d0d6-6505-4f44-c820-d714835dbf32"},"outputs":[{"output_type":"stream","name":"stdout","text":["Requirement already satisfied: torch in /usr/local/lib/python3.10/dist-packages (2.1.0+cu118)\n","Requirement already satisfied: torchvision in /usr/local/lib/python3.10/dist-packages (0.16.0+cu118)\n","Requirement already satisfied: filelock in /usr/local/lib/python3.10/dist-packages (from torch) (3.13.1)\n","Requirement already satisfied: typing-extensions in /usr/local/lib/python3.10/dist-packages (from torch) (4.5.0)\n","Requirement already satisfied: sympy in /usr/local/lib/python3.10/dist-packages (from torch) (1.12)\n","Requirement already satisfied: networkx in /usr/local/lib/python3.10/dist-packages (from torch) (3.2.1)\n","Requirement already satisfied: jinja2 in /usr/local/lib/python3.10/dist-packages (from torch) (3.1.2)\n","Requirement already satisfied: fsspec in /usr/local/lib/python3.10/dist-packages (from torch) (2023.6.0)\n","Requirement already satisfied: triton==2.1.0 in /usr/local/lib/python3.10/dist-packages (from torch) (2.1.0)\n","Requirement already satisfied: numpy in /usr/local/lib/python3.10/dist-packages (from torchvision) (1.23.5)\n","Requirement already satisfied: requests in /usr/local/lib/python3.10/dist-packages (from torchvision) (2.31.0)\n","Requirement already satisfied: pillow!=8.3.*,>=5.3.0 in /usr/local/lib/python3.10/dist-packages (from torchvision) (9.4.0)\n","Requirement already satisfied: MarkupSafe>=2.0 in /usr/local/lib/python3.10/dist-packages (from jinja2->torch) (2.1.3)\n","Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.10/dist-packages (from requests->torchvision) (3.3.2)\n","Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.10/dist-packages (from requests->torchvision) (3.4)\n","Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.10/dist-packages (from requests->torchvision) (2.0.7)\n","Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.10/dist-packages (from requests->torchvision) (2023.7.22)\n","Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.10/dist-packages (from sympy->torch) (1.3.0)\n"]},{"output_type":"execute_result","data":{"text/plain":["'/content'"],"application/vnd.google.colaboratory.intrinsic+json":{"type":"string"}},"metadata":{},"execution_count":27}],"source":["%pip install torch torchvision\n","%pwd"]},{"cell_type":"markdown","id":"0882a636","metadata":{"id":"0882a636"},"source":["\n","To test run the following code"]},{"cell_type":"code","execution_count":28,"id":"b1950f0a","metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"b1950f0a","executionInfo":{"status":"ok","timestamp":1701426306511,"user_tz":-60,"elapsed":894,"user":{"displayName":"Emilien Paganelli","userId":"14204960141695635735"}},"outputId":"ad7c03d1-2f59-4fc4-fc8a-95cd79d1dbc0"},"outputs":[{"output_type":"stream","name":"stdout","text":["tensor([[ 3.5464e-01, -2.5162e-01, -3.4084e-01, -4.0203e-01, 3.5056e-01,\n"," -6.9368e-01, 3.9031e-01, 3.7319e-01, -1.4964e+00, -4.2178e-01],\n"," [-4.0251e-01, 1.5534e+00, -1.0358e+00, -5.9098e-01, -6.0426e-02,\n"," -9.6500e-01, -7.1777e-01, -3.0196e-01, -2.0247e-01, 2.8037e-01],\n"," [-4.0223e-01, -7.3649e-01, -8.6344e-01, -7.9131e-01, -6.1953e-02,\n"," -1.8424e+00, 9.4855e-01, -1.0007e-01, -1.4111e+00, -6.5363e-01],\n"," [ 1.3629e-01, -3.6519e-01, 1.7978e-01, -4.4087e-01, -4.5886e-01,\n"," 4.6493e-01, -1.0318e+00, 1.2653e-01, -3.5993e-01, 7.4553e-01],\n"," [-2.5067e-01, 9.4126e-01, -6.1452e-01, 7.3656e-01, -2.8452e-01,\n"," 9.6051e-01, 1.0045e+00, 4.4673e-04, 1.2508e+00, -9.4441e-01],\n"," [-1.3628e+00, -8.0748e-01, 8.7495e-01, -6.0305e-01, -3.0637e+00,\n"," -4.7690e-01, 7.7525e-01, -8.4844e-02, -8.0040e-01, -1.6611e+00],\n"," [-6.5572e-01, 2.8375e-01, -8.9761e-01, 6.8970e-01, -2.1472e+00,\n"," -5.3845e-01, -1.3347e-01, -4.6737e-01, 5.3647e-01, -9.9889e-02],\n"," [-6.5048e-01, 1.7173e-01, -2.7836e-01, 6.2470e-02, 2.4870e+00,\n"," 1.0898e+00, 7.3483e-01, -9.4346e-01, 1.0283e+00, 1.3574e-01],\n"," [ 5.7310e-01, -1.9131e-01, 6.2758e-01, 1.4844e-01, -7.4922e-01,\n"," -8.9184e-01, 8.0467e-01, -7.2978e-01, -7.0883e-01, -1.4534e-01],\n"," [ 1.1513e+00, -8.5424e-01, 1.3269e+00, -4.4614e-01, -4.5424e-01,\n"," -1.0125e+00, -7.7922e-01, -9.7093e-01, 2.2431e+00, -1.8060e+00],\n"," [ 1.0384e+00, -1.8293e+00, -4.7758e-01, -1.7817e+00, -3.3394e-01,\n"," 1.7667e+00, 1.1108e+00, -1.9820e-01, -5.5519e-01, -5.8780e-01],\n"," [-1.3990e+00, -1.7740e+00, -1.2106e+00, 3.2282e-03, -1.7323e+00,\n"," -2.3775e-01, 5.3892e-01, 9.7521e-01, -3.2019e-01, -1.3805e+00],\n"," [-5.7714e-02, 1.2586e-01, -1.7178e+00, 2.8869e+00, -8.5589e-01,\n"," -4.0656e-01, 1.0384e+00, 8.4800e-01, 4.2282e-01, 7.2093e-01],\n"," [-1.9805e-02, -2.7115e-01, 3.3575e-01, -1.1353e-01, -4.9451e-01,\n"," 2.2995e-01, 1.0682e+00, 1.1319e+00, -4.9516e-01, -1.2863e+00]])\n","AlexNet(\n"," (features): Sequential(\n"," (0): Conv2d(3, 64, kernel_size=(11, 11), stride=(4, 4), padding=(2, 2))\n"," (1): ReLU(inplace=True)\n"," (2): MaxPool2d(kernel_size=3, stride=2, padding=0, dilation=1, ceil_mode=False)\n"," (3): Conv2d(64, 192, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))\n"," (4): ReLU(inplace=True)\n"," (5): MaxPool2d(kernel_size=3, stride=2, padding=0, dilation=1, ceil_mode=False)\n"," (6): Conv2d(192, 384, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n"," (7): ReLU(inplace=True)\n"," (8): Conv2d(384, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n"," (9): ReLU(inplace=True)\n"," (10): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n"," (11): ReLU(inplace=True)\n"," (12): MaxPool2d(kernel_size=3, stride=2, padding=0, dilation=1, ceil_mode=False)\n"," )\n"," (avgpool): AdaptiveAvgPool2d(output_size=(6, 6))\n"," (classifier): Sequential(\n"," (0): Dropout(p=0.5, inplace=False)\n"," (1): Linear(in_features=9216, out_features=4096, bias=True)\n"," (2): ReLU(inplace=True)\n"," (3): Dropout(p=0.5, inplace=False)\n"," (4): Linear(in_features=4096, out_features=4096, bias=True)\n"," (5): ReLU(inplace=True)\n"," (6): Linear(in_features=4096, out_features=1000, bias=True)\n"," )\n",")\n"]}],"source":["import torch\n","\n","N, D = 14, 10\n","x = torch.randn(N, D).type(torch.FloatTensor)\n","print(x)\n","\n","from torchvision import models\n","\n","alexnet = models.alexnet()\n","print(alexnet)"]},{"cell_type":"markdown","id":"23f266da","metadata":{"id":"23f266da"},"source":["## Exercise 1: CNN on CIFAR10\n","\n","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.\n","\n","Have a look at the following documentation to be familiar with PyTorch.\n","\n","https://pytorch.org/tutorials/beginner/pytorch_with_examples.html\n","\n","https://pytorch.org/tutorials/beginner/deep_learning_60min_blitz.html"]},{"cell_type":"markdown","id":"4ba1c82d","metadata":{"id":"4ba1c82d"},"source":["You can test if GPU is available on your machine and thus train on it to speed up the process"]},{"cell_type":"code","execution_count":29,"id":"6e18f2fd","metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"6e18f2fd","executionInfo":{"status":"ok","timestamp":1701426306511,"user_tz":-60,"elapsed":3,"user":{"displayName":"Emilien Paganelli","userId":"14204960141695635735"}},"outputId":"02f0f21b-1da2-46f2-d67e-a27d41d7ff93"},"outputs":[{"output_type":"stream","name":"stdout","text":["CUDA is available! Training on GPU ...\n"]}],"source":["import torch\n","\n","# check if CUDA is available\n","train_on_gpu = torch.cuda.is_available()\n","\n","if not train_on_gpu:\n"," print(\"CUDA is not available. Training on CPU ...\")\n","else:\n"," print(\"CUDA is available! Training on GPU ...\")"]},{"cell_type":"markdown","id":"5cf214eb","metadata":{"id":"5cf214eb"},"source":["Next we load the CIFAR10 dataset"]},{"cell_type":"code","execution_count":30,"id":"462666a2","metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"462666a2","executionInfo":{"status":"ok","timestamp":1701426308369,"user_tz":-60,"elapsed":1860,"user":{"displayName":"Emilien Paganelli","userId":"14204960141695635735"}},"outputId":"a0158530-9554-4462-d7de-7b69df58e40b"},"outputs":[{"output_type":"stream","name":"stdout","text":["Files already downloaded and verified\n","Files already downloaded and verified\n"]}],"source":["import numpy as np\n","from torchvision import datasets, transforms\n","from torch.utils.data.sampler import SubsetRandomSampler\n","\n","# number of subprocesses to use for data loading\n","num_workers = 0\n","# how many samples per batch to load\n","batch_size = 20\n","# percentage of training set to use as validation\n","valid_size = 0.2\n","\n","# convert data to a normalized torch.FloatTensor\n","transform = transforms.Compose(\n"," [transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]\n",")\n","\n","# choose the training and test datasets\n","train_data = datasets.CIFAR10(\"data\", train=True, download=True, transform=transform)\n","test_data = datasets.CIFAR10(\"data\", train=False, download=True, transform=transform)\n","\n","# obtain training indices that will be used for validation\n","num_train = len(train_data)\n","indices = list(range(num_train))\n","np.random.shuffle(indices)\n","split = int(np.floor(valid_size * num_train))\n","train_idx, valid_idx = indices[split:], indices[:split]\n","\n","# define samplers for obtaining training and validation batches\n","train_sampler = SubsetRandomSampler(train_idx)\n","valid_sampler = SubsetRandomSampler(valid_idx)\n","\n","# prepare data loaders (combine dataset and sampler)\n","train_loader = torch.utils.data.DataLoader(\n"," train_data, batch_size=batch_size, sampler=train_sampler, num_workers=num_workers\n",")\n","valid_loader = torch.utils.data.DataLoader(\n"," train_data, batch_size=batch_size, sampler=valid_sampler, num_workers=num_workers\n",")\n","test_loader = torch.utils.data.DataLoader(\n"," test_data, batch_size=batch_size, num_workers=num_workers\n",")\n","\n","# specify the image classes\n","classes = [\n"," \"airplane\",\n"," \"automobile\",\n"," \"bird\",\n"," \"cat\",\n"," \"deer\",\n"," \"dog\",\n"," \"frog\",\n"," \"horse\",\n"," \"ship\",\n"," \"truck\",\n","]"]},{"cell_type":"markdown","id":"58ec3903","metadata":{"id":"58ec3903"},"source":["CNN definition (this one is an example)"]},{"cell_type":"code","execution_count":31,"id":"317bf070","metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"317bf070","executionInfo":{"status":"ok","timestamp":1701426308369,"user_tz":-60,"elapsed":4,"user":{"displayName":"Emilien Paganelli","userId":"14204960141695635735"}},"outputId":"39844deb-a37a-4d6b-dc9d-a5824620d7ad"},"outputs":[{"output_type":"stream","name":"stdout","text":["Net(\n"," (conv1): Conv2d(3, 6, kernel_size=(5, 5), stride=(1, 1))\n"," (pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n"," (conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))\n"," (fc1): Linear(in_features=400, out_features=120, bias=True)\n"," (fc2): Linear(in_features=120, out_features=84, bias=True)\n"," (fc3): Linear(in_features=84, out_features=10, bias=True)\n",")\n"]}],"source":["import torch.nn as nn\n","import torch.nn.functional as F\n","\n","# define the CNN architecture\n","\n","\n","class Net(nn.Module):\n"," def __init__(self):\n"," super(Net, self).__init__()\n"," self.conv1 = nn.Conv2d(3, 6, 5)\n"," self.pool = nn.MaxPool2d(2, 2)\n"," self.conv2 = nn.Conv2d(6, 16, 5)\n"," self.fc1 = nn.Linear(16 * 5 * 5, 120)\n"," self.fc2 = nn.Linear(120, 84)\n"," self.fc3 = nn.Linear(84, 10)\n","\n"," def forward(self, x):\n"," x = self.pool(F.relu(self.conv1(x)))\n"," x = self.pool(F.relu(self.conv2(x)))\n"," x = x.view(-1, 16 * 5 * 5)\n"," x = F.relu(self.fc1(x))\n"," x = F.relu(self.fc2(x))\n"," x = self.fc3(x)\n"," return x\n","\n","\n","# create a complete CNN\n","model = Net()\n","print(model)\n","# move tensors to GPU if CUDA is available\n","if train_on_gpu:\n"," model.cuda()"]},{"cell_type":"markdown","id":"a2dc4974","metadata":{"id":"a2dc4974"},"source":["Loss function and training using SGD (Stochastic Gradient Descent) optimizer"]},{"cell_type":"code","execution_count":null,"id":"4b53f229","metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"4b53f229","outputId":"ffb784e2-4c61-46f8-dee6-8b81f12e9662"},"outputs":[{"output_type":"stream","name":"stdout","text":["Epoch: 0 \tTraining Loss: 43.538748 \tValidation Loss: 39.015653\n","Validation loss decreased (inf --> 39.015653). Saving model ...\n"]}],"source":["import torch.optim as optim\n","\n","criterion = nn.CrossEntropyLoss() # specify loss function\n","optimizer = optim.SGD(model.parameters(), lr=0.01) # specify optimizer\n","\n","n_epochs = 30 # number of epochs to train the model\n","train_loss_list = [] # list to store loss to visualize\n","valid_loss_min = np.Inf # track change in validation loss\n","\n","for epoch in range(n_epochs):\n"," # Keep track of training and validation loss\n"," train_loss = 0.0\n"," valid_loss = 0.0\n","\n"," # Train the model\n"," model.train()\n"," for data, target in train_loader:\n"," # Move tensors to GPU if CUDA is available\n"," if train_on_gpu:\n"," data, target = data.cuda(), target.cuda()\n"," # Clear the gradients of all optimized variables\n"," optimizer.zero_grad()\n"," # Forward pass: compute predicted outputs by passing inputs to the model\n"," output = model(data)\n"," # Calculate the batch loss\n"," loss = criterion(output, target)\n"," # Backward pass: compute gradient of the loss with respect to model parameters\n"," loss.backward()\n"," # Perform a single optimization step (parameter update)\n"," optimizer.step()\n"," # Update training loss\n"," train_loss += loss.item() * data.size(0)\n","\n"," # Validate the model\n"," model.eval()\n"," for data, target in valid_loader:\n"," # Move tensors to GPU if CUDA is available\n"," if train_on_gpu:\n"," data, target = data.cuda(), target.cuda()\n"," # Forward pass: compute predicted outputs by passing inputs to the model\n"," output = model(data)\n"," # Calculate the batch loss\n"," loss = criterion(output, target)\n"," # Update average validation loss\n"," valid_loss += loss.item() * data.size(0)\n","\n"," # Calculate average losses\n"," train_loss = train_loss / len(train_loader)\n"," valid_loss = valid_loss / len(valid_loader)\n"," train_loss_list.append(train_loss)\n","\n"," # Print training/validation statistics\n"," print(\n"," \"Epoch: {} \\tTraining Loss: {:.6f} \\tValidation Loss: {:.6f}\".format(\n"," epoch, train_loss, valid_loss\n"," )\n"," )\n","\n"," # Save model if validation loss has decreased\n"," if valid_loss <= valid_loss_min:\n"," print(\n"," \"Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...\".format(\n"," valid_loss_min, valid_loss\n"," )\n"," )\n"," torch.save(model.state_dict(), \"model_cifar.pt\")\n"," valid_loss_min = valid_loss"]},{"cell_type":"markdown","id":"13e1df74","metadata":{"id":"13e1df74"},"source":["Does overfit occur? If so, do an early stopping."]},{"cell_type":"code","execution_count":null,"id":"d39df818","metadata":{"id":"d39df818"},"outputs":[],"source":["import matplotlib.pyplot as plt\n","\n","plt.plot(range(n_epochs), train_loss_list)\n","plt.xlabel(\"Epoch\")\n","plt.ylabel(\"Loss\")\n","plt.title(\"Performance of Model 1\")\n","plt.show()"]},{"cell_type":"markdown","id":"11df8fd4","metadata":{"id":"11df8fd4"},"source":["Now loading the model with the lowest validation loss value\n"]},{"cell_type":"code","execution_count":null,"id":"e93efdfc","metadata":{"id":"e93efdfc"},"outputs":[],"source":["model.load_state_dict(torch.load(\"./model_cifar.pt\"))\n","\n","# track test loss\n","test_loss = 0.0\n","class_correct = list(0.0 for i in range(10))\n","class_total = list(0.0 for i in range(10))\n","\n","model.eval()\n","# iterate over test data\n","for data, target in test_loader:\n"," # move tensors to GPU if CUDA is available\n"," if train_on_gpu:\n"," data, target = data.cuda(), target.cuda()\n"," # forward pass: compute predicted outputs by passing inputs to the model\n"," output = model(data)\n"," # calculate the batch loss\n"," loss = criterion(output, target)\n"," # update test loss\n"," test_loss += loss.item() * data.size(0)\n"," # convert output probabilities to predicted class\n"," _, pred = torch.max(output, 1)\n"," # compare predictions to true label\n"," correct_tensor = pred.eq(target.data.view_as(pred))\n"," correct = (\n"," np.squeeze(correct_tensor.numpy())\n"," if not train_on_gpu\n"," else np.squeeze(correct_tensor.cpu().numpy())\n"," )\n"," # calculate test accuracy for each object class\n"," for i in range(batch_size):\n"," label = target.data[i]\n"," class_correct[label] += correct[i].item()\n"," class_total[label] += 1\n","\n","# average test loss\n","test_loss = test_loss / len(test_loader)\n","print(\"Test Loss: {:.6f}\\n\".format(test_loss))\n","\n","for i in range(10):\n"," if class_total[i] > 0:\n"," print(\n"," \"Test Accuracy of %5s: %2d%% (%2d/%2d)\"\n"," % (\n"," classes[i],\n"," 100 * class_correct[i] / class_total[i],\n"," np.sum(class_correct[i]),\n"," np.sum(class_total[i]),\n"," )\n"," )\n"," else:\n"," print(\"Test Accuracy of %5s: N/A (no training examples)\" % (classes[i]))\n","\n","print(\n"," \"\\nTest Accuracy (Overall): %2d%% (%2d/%2d)\"\n"," % (\n"," 100.0 * np.sum(class_correct) / np.sum(class_total),\n"," np.sum(class_correct),\n"," np.sum(class_total),\n"," )\n",")"]},{"cell_type":"markdown","id":"944991a2","metadata":{"id":"944991a2"},"source":["Build a new network with the following structure.\n","\n","- It has 3 convolutional layers of kernel size 3 and padding of 1.\n","- The first convolutional layer must output 16 channels, the second 32 and the third 64.\n","- At each convolutional layer output, we apply a ReLU activation then a MaxPool with kernel size of 2.\n","- Then, three fully connected layers, the first two being followed by a ReLU activation and a dropout whose value you will suggest.\n","- The first fully connected layer will have an output size of 512.\n","- The second fully connected layer will have an output size of 64.\n","\n","Compare the results obtained with this new network to those obtained previously."]},{"cell_type":"markdown","source":["Net(\n"," (conv1): Conv2d(3, 6, kernel_size=(5, 5), stride=(1, 1))\n"," (pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n"," (conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))\n"," (fc1): Linear(in_features=400, out_features=120, bias=True)\n"," (fc2): Linear(in_features=120, out_features=84, bias=True)\n"," (fc3): Linear(in_features=84, out_features=10, bias=True)\n",")"],"metadata":{"id":"fgfXjKBy3mwR"},"id":"fgfXjKBy3mwR"},{"cell_type":"code","source":["import torch.nn as nn\n","import torch.nn.functional as F\n","\n","# define the CNN architecture\n","\n","\n","class Net(nn.Module):\n"," def __init__(self):\n"," super(Net, self).__init__()\n"," self.conv1 = nn.Conv2d(3, 16, 3, padding=1)\n"," self.conv2 = nn.Conv2d(16, 32 , 3, padding=1)\n"," self.conv3 = nn.Conv2d(32, 64 , 3, padding=1)\n"," self.pool = nn.MaxPool2d(2, 2)\n"," self.fc1 = nn.Linear(64 * 4 * 4, 512)\n"," self.fc2 = nn.Linear(512, 64)\n"," self.fc3 = nn.Linear(64, 10)\n"," self.dropout = nn.Dropout()\n","\n"," def forward(self, x):\n"," x = self.pool(F.relu(self.conv1(x)))\n"," x = self.pool(F.relu(self.conv2(x)))\n"," x = self.pool(F.relu(self.conv3(x)))\n"," x = x.view(-1, 64 * 4 * 4)\n"," x = F.relu(x)\n"," x = self.dropout(self.fc1(x))\n"," x = F.relu(x)\n"," x = self.dropout(self.fc2(x))\n"," x = self.fc3(x)\n"," return x\n","\n","\n","# create a complete CNN\n","model = Net()\n","print(model)\n","# move tensors to GPU if CUDA is available\n","if train_on_gpu:\n"," model.cuda()"],"metadata":{"id":"BNqCMzKT3SfJ"},"id":"BNqCMzKT3SfJ","execution_count":null,"outputs":[]},{"cell_type":"code","source":["import torch.optim as optim\n","\n","criterion = nn.CrossEntropyLoss() # specify loss function\n","optimizer = optim.SGD(model.parameters(), lr=0.01) # specify optimizer\n","\n","n_epochs = 30 # number of epochs to train the model\n","train_loss_list = [] # list to store loss to visualize\n","valid_loss_min = np.Inf # track change in validation loss\n","\n","for epoch in range(n_epochs):\n"," # Keep track of training and validation loss\n"," train_loss = 0.0\n"," valid_loss = 0.0\n","\n"," # Train the model\n"," model.train()\n"," for data, target in train_loader:\n"," # Move tensors to GPU if CUDA is available\n"," if train_on_gpu:\n"," data, target = data.cuda(), target.cuda()\n"," # Clear the gradients of all optimized variables\n"," optimizer.zero_grad()\n"," # Forward pass: compute predicted outputs by passing inputs to the model\n"," output = model(data)\n"," # Calculate the batch loss\n"," loss = criterion(output, target)\n"," # Backward pass: compute gradient of the loss with respect to model parameters\n"," loss.backward()\n"," # Perform a single optimization step (parameter update)\n"," optimizer.step()\n"," # Update training loss\n"," train_loss += loss.item() * data.size(0)\n","\n"," # Validate the model\n"," model.eval()\n"," for data, target in valid_loader:\n"," # Move tensors to GPU if CUDA is available\n"," if train_on_gpu:\n"," data, target = data.cuda(), target.cuda()\n"," # Forward pass: compute predicted outputs by passing inputs to the model\n"," output = model(data)\n"," # Calculate the batch loss\n"," loss = criterion(output, target)\n"," # Update average validation loss\n"," valid_loss += loss.item() * data.size(0)\n","\n"," # Calculate average losses\n"," train_loss = train_loss / len(train_loader)\n"," valid_loss = valid_loss / len(valid_loader)\n"," train_loss_list.append(train_loss)\n","\n"," # Print training/validation statistics\n"," print(\n"," \"Epoch: {} \\tTraining Loss: {:.6f} \\tValidation Loss: {:.6f}\".format(\n"," epoch, train_loss, valid_loss\n"," )\n"," )\n","\n"," # Save model if validation loss has decreased\n"," if valid_loss <= valid_loss_min:\n"," print(\n"," \"Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...\".format(\n"," valid_loss_min, valid_loss\n"," )\n"," )\n"," torch.save(model.state_dict(), \"model_cifar_3D.pt\")\n"," valid_loss_min = valid_loss"],"metadata":{"id":"heaTYMsTZIEu"},"id":"heaTYMsTZIEu","execution_count":null,"outputs":[]},{"cell_type":"code","source":["import matplotlib.pyplot as plt\n","\n","plt.plot(range(n_epochs), train_loss_list)\n","plt.xlabel(\"Epoch\")\n","plt.ylabel(\"Loss\")\n","plt.title(\"Performance of Model 2\")\n","plt.show()"],"metadata":{"id":"K5lIwyTZZNTt"},"id":"K5lIwyTZZNTt","execution_count":null,"outputs":[]},{"cell_type":"code","source":["model.load_state_dict(torch.load(\"./model_cifar_3D.pt\"))\n","\n","# track test loss\n","test_loss = 0.0\n","class_correct = list(0.0 for i in range(10))\n","class_total = list(0.0 for i in range(10))\n","\n","model.eval()\n","# iterate over test data\n","for data, target in test_loader:\n"," # move tensors to GPU if CUDA is available\n"," if train_on_gpu:\n"," data, target = data.cuda(), target.cuda()\n"," # forward pass: compute predicted outputs by passing inputs to the model\n"," output = model(data)\n"," # calculate the batch loss\n"," loss = criterion(output, target)\n"," # update test loss\n"," test_loss += loss.item() * data.size(0)\n"," # convert output probabilities to predicted class\n"," _, pred = torch.max(output, 1)\n"," # compare predictions to true label\n"," correct_tensor = pred.eq(target.data.view_as(pred))\n"," correct = (\n"," np.squeeze(correct_tensor.numpy())\n"," if not train_on_gpu\n"," else np.squeeze(correct_tensor.cpu().numpy())\n"," )\n"," # calculate test accuracy for each object class\n"," for i in range(batch_size):\n"," label = target.data[i]\n"," class_correct[label] += correct[i].item()\n"," class_total[label] += 1\n","\n","# average test loss\n","test_loss = test_loss / len(test_loader)\n","print(\"Test Loss: {:.6f}\\n\".format(test_loss))\n","\n","for i in range(10):\n"," if class_total[i] > 0:\n"," print(\n"," \"Test Accuracy of %5s: %2d%% (%2d/%2d)\"\n"," % (\n"," classes[i],\n"," 100 * class_correct[i] / class_total[i],\n"," np.sum(class_correct[i]),\n"," np.sum(class_total[i]),\n"," )\n"," )\n"," else:\n"," print(\"Test Accuracy of %5s: N/A (no training examples)\" % (classes[i]))\n","\n","print(\n"," \"\\nTest Accuracy (Overall): %2d%% (%2d/%2d)\"\n"," % (\n"," 100.0 * np.sum(class_correct) / np.sum(class_total),\n"," np.sum(class_correct),\n"," np.sum(class_total),\n"," )\n",")"],"metadata":{"id":"oAeC05EmZN8P"},"id":"oAeC05EmZN8P","execution_count":null,"outputs":[]},{"cell_type":"markdown","id":"bc381cf4","metadata":{"id":"bc381cf4"},"source":["## Exercise 2: Quantization: try to compress the CNN to save space\n","\n","Quantization doc is available from https://pytorch.org/docs/stable/quantization.html#torch.quantization.quantize_dynamic\n"," \n","The Exercise is to quantize post training the above CNN model. Compare the size reduction and the impact on the classification accuracy\n","\n","\n","The size of the model is simply the size of the file."]},{"cell_type":"code","execution_count":null,"id":"ef623c26","metadata":{"id":"ef623c26"},"outputs":[],"source":["import os\n","\n","def print_size_of_model(model, label=\"\"):\n"," torch.save(model.state_dict(), \"temp.p\")\n"," size = os.path.getsize(\"temp.p\")\n"," print(\"model: \", label, \" \\t\", \"Size (KB):\", size / 1e3)\n"," os.remove(\"temp.p\")\n"," return size\n","\n","\n","size_model=print_size_of_model(model, \"fp32\")"]},{"cell_type":"markdown","id":"05c4e9ad","metadata":{"id":"05c4e9ad"},"source":["Post training quantization example"]},{"cell_type":"code","execution_count":null,"id":"c4c65d4b","metadata":{"id":"c4c65d4b"},"outputs":[],"source":["import torch.quantization\n","\n","\n","quantized_model = torch.quantization.quantize_dynamic(model, {torch.nn.Linear}, dtype=torch.qint8)\n","torch.save(quantized_model.state_dict(), \"quantized_model_cifar.pt\")\n","\n","size_quantized = print_size_of_model(quantized_model, \"int8\")\n","\n","print(\"The size of the original model has been divided by %.2f compared to the Quantized model\" % (size_model / size_quantized))"]},{"cell_type":"markdown","id":"7b108e17","metadata":{"id":"7b108e17"},"source":["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","metadata":{"id":"a0a34b90"},"source":["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":"code","source":["quantized_model.load_state_dict(torch.load(\"./quantized_model_cifar.pt\", map_location=torch.device('cpu')))\n","\n","# track test loss\n","test_loss_quantized = 0.0\n","class_correct_quantized = list(0.0 for i in range(10))\n","class_total_quantized = list(0.0 for i in range(10))\n","\n","quantized_model.eval()\n","quantized_model.cpu()\n","# iterate over test data\n","for data, target in test_loader:\n"," # forward pass: compute predicted outputs by passing inputs to the model\n"," output = quantized_model(data)\n"," # calculate the batch loss\n"," loss = criterion(output, target)\n"," # update test loss\n"," test_loss_quantized += loss.item() * data.size(0)\n"," # convert output probabilities to predicted class\n"," _, pred = torch.max(output, 1)\n"," # compare predictions to true label\n"," correct_tensor = pred.eq(target.data.view_as(pred))\n"," correct = np.squeeze(correct_tensor.numpy()) #np.squeeze(correct_tensor.cpu().numpy()\n"," # calculate test accuracy for each object class\n"," for i in range(batch_size):\n"," label = target.data[i]\n"," class_correct_quantized[label] += correct[i].item()\n"," class_total_quantized[label] += 1\n","\n","# average test loss\n","test_loss_quantized = test_loss_quantized / len(test_loader)\n","loss_delta = test_loss_quantized - test_loss\n","print(\"Original Test Loss: {:.6f}\\n\".format(test_loss))\n","print(\"Quantized Test Loss: {:.6f}\\n\".format(test_loss_quantized))\n","print(\"Loss Delta: {:.6f}\\n\".format(loss_delta))\n","\n","for i in range(10):\n"," if class_total[i] > 0:\n"," print(\n"," \"Quantized Test Accuracy of %5s: %2d%% (%2d/%2d)\"\n"," % (\n"," classes[i],\n"," 100 * class_correct_quantized[i] / class_total_quantized[i],\n"," np.sum(class_correct_quantized[i]),\n"," np.sum(class_total_quantized[i]),\n"," ))\n"," print(\n"," \"Original Test Accuracy of %5s: %2d%% (%2d/%2d)\"\n"," % (\n"," classes[i],\n"," 100 * class_correct[i] / class_total[i],\n"," np.sum(class_correct[i]),\n"," np.sum(class_total[i]),\n"," ))\n"," print(\n"," \"Difference in Instances Correctly classified of %5s: %2d \\n\"\n"," % (\n"," classes[i],\n"," class_correct[i]-class_correct_quantized[i],\n","\n"," )\n"," )\n"," else:\n"," print(\"Test Accuracy of %5s: N/A (no training examples)\" % (classes[i]))\n","\n","print(\n"," \"\\nQuantized Test Accuracy (Overall): %2d%% (%2d/%2d)\"\n"," % (\n"," 100.0 * np.sum(class_correct_quantized) / np.sum(class_total_quantized),\n"," np.sum(class_correct_quantized),\n"," np.sum(class_total_quantized),\n"," )\n",")\n","print(\n"," \"\\nOriginal Test Accuracy (Overall): %2d%% (%2d/%2d)\"\n"," % (\n"," 100.0 * np.sum(class_correct) / np.sum(class_total),\n"," np.sum(class_correct),\n"," np.sum(class_total),\n"," )\n",")\n","print(\n"," \"\\nDifference in Instances Correctly classified overall: %2d \\n\"\n"," % (\n"," np.sum(class_correct)-np.sum(class_correct_quantized),\n"," )\n"," )"],"metadata":{"id":"-1DG65AMAHFd"},"id":"-1DG65AMAHFd","execution_count":null,"outputs":[]},{"cell_type":"markdown","id":"201470f9","metadata":{"id":"201470f9"},"source":["## Exercise 3: working with pre-trained models.\n","\n","PyTorch offers several pre-trained models https://pytorch.org/vision/0.8/models.html \n","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.\n"]},{"cell_type":"code","execution_count":null,"id":"b4d13080","metadata":{"id":"b4d13080"},"outputs":[],"source":["import json\n","from PIL import Image\n","\n","# Choose an image to pass through the model\n","test_image = \"dog.png\"\n","\n","# Configure matplotlib for pretty inline plots\n","#%matplotlib inline\n","#%config InlineBackend.figure_format = 'retina'\n","\n","# Prepare the labels\n","with open(\"imagenet-simple-labels.json\") as f:\n"," labels = json.load(f)\n","\n","# First prepare the transformations: resize the image to what the model was trained on and convert it to a tensor\n","data_transform = transforms.Compose(\n"," [\n"," transforms.Resize((224, 224)),\n"," transforms.ToTensor(),\n"," transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n"," ]\n",")\n","# Load the image\n","\n","image = Image.open(test_image)\n","plt.imshow(image), plt.xticks([]), plt.yticks([])\n","\n","# Now apply the transformation, expand the batch dimension, and send the image to the GPU\n","# image = data_transform(image).unsqueeze(0).cuda()\n","image = data_transform(image).unsqueeze(0)\n","\n","# Download the model if it's not there already. It will take a bit on the first run, after that it's fast\n","model = models.resnet50(pretrained=True)\n","# Send the model to the GPU\n","# model.cuda()\n","# Set layers such as dropout and batchnorm in evaluation mode\n","model.eval()\n","\n","# Get the 1000-dimensional model output\n","out = model(image)\n","# Find the predicted class\n","print(\"Predicted class is: {}\".format(labels[out.argmax()]))"]},{"cell_type":"markdown","id":"184cfceb","metadata":{"id":"184cfceb"},"source":["Experiments:\n","\n","Study the code and the results obtained. Possibly add other images downloaded from the internet.\n","\n","What is the size of the model? Quantize it and then check if the model is still able to correctly classify the other images.\n","\n","Experiment with other pre-trained CNN models.\n","\n"," \n"]},{"cell_type":"code","source":["import json\n","from PIL import Image\n","\n","# Choose an image to pass through the model\n","test_image1 = \"koala.jpg\"\n","test_image2 = \"raton.jpg\"\n","\n","# Configure matplotlib for pretty inline plots\n","#%matplotlib inline\n","#%config InlineBackend.figure_format = 'retina'\n","\n","# Prepare the labels\n","with open(\"imagenet-simple-labels.json\") as f:\n"," labels = json.load(f)\n","\n","# First prepare the transformations: resize the image to what the model was trained on and convert it to a tensor\n","data_transform = transforms.Compose(\n"," [\n"," transforms.Resize((224, 224)),\n"," transforms.ToTensor(),\n"," transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n"," ]\n",")\n","# Load the image\n","image1 = Image.open(test_image1)\n","image2 = Image.open(test_image2)\n","\n","plt.figure()\n","\n","\n","f, axarr = plt.subplots(2,1)\n","\n","axarr[0].imshow(image1)\n","axarr[1].imshow(image2)\n","\n","#plt.imshow(image), plt.xticks([]), plt.yticks([])\n","\n","# Now apply the transformation, expand the batch dimension, and send the image to the GPU\n","# image = data_transform(image).unsqueeze(0).cuda()\n","image1 = data_transform(image1).unsqueeze(0)\n","image2 = data_transform(image2).unsqueeze(0)\n","\n","# Download the model if it's not there already. It will take a bit on the first run, after that it's fast\n","\n","resnet50_model=models.resnet50(pretrained=True)\n","resnet50_model_quantized=torch.quantization.quantize_dynamic(resnet50_model, dtype=torch.qint8)\n","\n","googlenet_model = models.googlenet(pretrained=True)\n","googlenet_model_quantized = torch.quantization.quantize_dynamic(googlenet_model, dtype=torch.qint8)\n","\n","\n","# Send the model to the GPU\n","# model.cuda()\n","# Set layers such as dropout and batchnorm in evaluation mode\n","resnet50_model.eval()\n","resnet50_model_quantized.eval()\n","\n","googlenet_model.eval()\n","googlenet_model_quantized.eval()\n","\n","out1=resnet50_model(image1)\n","out1q=resnet50_model_quantized(image1)\n","out2=googlenet_model(image1)\n","out2q=googlenet_model_quantized(image1)\n","\n","out3=resnet50_model(image2)\n","out3q=resnet50_model_quantized(image2)\n","out4=googlenet_model(image2)\n","out4q=googlenet_model_quantized(image2)\n","\n","\n","# Get the 1000-dimensional model output\n","\n","# Find the predicted class\n","print(\"Predicted class for Resnet50 is Koala: {}\".format(labels[out1.argmax()]))\n","print(\"Predicted class for GoogleNet is Koala: {}\".format(labels[out2.argmax()]))\n","print(\"Predicted class for Quantized_Resnet is Koala: {}\".format(labels[out1q.argmax()]))\n","print(\"Predicted class for Quantized_GoogleNet is Koala: {}\".format(labels[out2q.argmax()]))\n","print(\"Predicted class for Resnet50 is Racoon: {}\".format(labels[out3.argmax()]))\n","print(\"Predicted class for GoogleNet is Racoon: {}\".format(labels[out4.argmax()]))\n","print(\"Predicted class for Quantized_Resnet is Racoon: {}\".format(labels[out3q.argmax()]))\n","print(\"Predicted class for Quantized_GoogleNet is Racoon: {}\".format(labels[out4q.argmax()]))"],"metadata":{"id":"wfgNGDlsnYBg"},"id":"wfgNGDlsnYBg","execution_count":null,"outputs":[]},{"cell_type":"code","source":["size_resnet50=print_size_of_model(resnet50_model, \"int8\")\n","size_resnet50_quantized = print_size_of_model(resnet50_model_quantized, \"int8\")\n","\n","print(\"The size of the original ResNet50 model has been divided by %.2f compared to the Quantized ResNet50 model\" % (size_resnet50 /size_resnet50_quantized))\n","\n","size_googlenet=print_size_of_model(googlenet_model, \"int8\")\n","size_googlenet_quantized = print_size_of_model(googlenet_model_quantized, \"int8\")\n","\n","print(\"The size of the original GoogleNet model has been divided by %.2f compared to the Quantized GoogleNet model\" % (size_resnet50 /size_resnet50_quantized))"],"metadata":{"id":"ehW_YwAp5CiO"},"id":"ehW_YwAp5CiO","execution_count":null,"outputs":[]},{"cell_type":"markdown","id":"5d57da4b","metadata":{"id":"5d57da4b"},"source":["## Exercise 4: Transfer Learning\n"," \n"," \n","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.\n","Download and unzip in your working directory the dataset available at the address :\n"," \n","https://download.pytorch.org/tutorial/hymenoptera_data.zip\n"," \n","Execute the following code in order to display some images of the dataset."]},{"cell_type":"code","source":["!wget https://download.pytorch.org/tutorial/hymenoptera_data.zip\n","!unzip hymenoptera_data.zip"],"metadata":{"id":"-GhBj4ORpEr3"},"id":"-GhBj4ORpEr3","execution_count":null,"outputs":[]},{"cell_type":"code","execution_count":null,"id":"be2d31f5","metadata":{"id":"be2d31f5"},"outputs":[],"source":["import os\n","\n","import matplotlib.pyplot as plt\n","import numpy as np\n","import torch\n","import torchvision\n","from torchvision import datasets, transforms\n","\n","# Data augmentation and normalization for training\n","# Just normalization for validation\n","data_transforms = {\n"," \"train\": transforms.Compose(\n"," [\n"," transforms.RandomResizedCrop(\n"," 224\n"," ), # ImageNet models were trained on 224x224 images\n"," transforms.RandomHorizontalFlip(), # flip horizontally 50% of the time - increases train set variability\n"," transforms.ToTensor(), # convert it to a PyTorch tensor\n"," transforms.Normalize(\n"," [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]\n"," ), # ImageNet models expect this norm\n"," ]\n"," ),\n"," \"val\": transforms.Compose(\n"," [\n"," transforms.Resize(256),\n"," transforms.CenterCrop(224),\n"," transforms.ToTensor(),\n"," transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n"," ]\n"," ),\n","}\n","\n","data_dir = \"hymenoptera_data\"\n","# Create train and validation datasets and loaders\n","image_datasets = {\n"," x: datasets.ImageFolder(os.path.join(data_dir, x), data_transforms[x])\n"," for x in [\"train\", \"val\"]\n","}\n","dataloaders = {\n"," x: torch.utils.data.DataLoader(\n"," image_datasets[x], batch_size=4, shuffle=True, num_workers=0\n"," )\n"," for x in [\"train\", \"val\"]\n","}\n","dataset_sizes = {x: len(image_datasets[x]) for x in [\"train\", \"val\"]}\n","class_names = image_datasets[\"train\"].classes\n","device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n","\n","# Helper function for displaying images\n","def imshow(inp, title=None):\n"," \"\"\"Imshow for Tensor.\"\"\"\n"," inp = inp.numpy().transpose((1, 2, 0))\n"," mean = np.array([0.485, 0.456, 0.406])\n"," std = np.array([0.229, 0.224, 0.225])\n","\n"," # Un-normalize the images\n"," inp = std * inp + mean\n"," # Clip just in case\n"," inp = np.clip(inp, 0, 1)\n"," plt.imshow(inp)\n"," if title is not None:\n"," plt.title(title)\n"," plt.pause(0.001) # pause a bit so that plots are updated\n"," plt.show()\n","\n","\n","# Get a batch of training data\n","inputs, classes = next(iter(dataloaders[\"train\"]))\n","\n","# Make a grid from batch\n","out = torchvision.utils.make_grid(inputs)\n","\n","imshow(out, title=[class_names[x] for x in classes])\n","\n"]},{"cell_type":"markdown","id":"bbd48800","metadata":{"id":"bbd48800"},"source":["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","execution_count":null,"id":"572d824c","metadata":{"id":"572d824c"},"outputs":[],"source":["import copy\n","import os\n","import time\n","\n","import matplotlib.pyplot as plt\n","import numpy as np\n","import torch\n","import torch.nn as nn\n","import torch.optim as optim\n","import torchvision\n","from torch.optim import lr_scheduler\n","from torchvision import datasets, transforms\n","\n","# Data augmentation and normalization for training\n","# Just normalization for validation\n","data_transforms = {\n"," \"train\": transforms.Compose(\n"," [\n"," transforms.RandomResizedCrop(\n"," 224\n"," ), # ImageNet models were trained on 224x224 images\n"," transforms.RandomHorizontalFlip(), # flip horizontally 50% of the time - increases train set variability\n"," transforms.ToTensor(), # convert it to a PyTorch tensor\n"," transforms.Normalize(\n"," [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]\n"," ), # ImageNet models expect this norm\n"," ]\n"," ),\n"," \"val\": transforms.Compose(\n"," [\n"," transforms.Resize(256),\n"," transforms.CenterCrop(224),\n"," transforms.ToTensor(),\n"," transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n"," ]\n"," ),\n","}\n","\n","data_dir = \"hymenoptera_data\"\n","# Create train and validation datasets and loaders\n","image_datasets = {\n"," x: datasets.ImageFolder(os.path.join(data_dir, x), data_transforms[x])\n"," for x in [\"train\", \"val\"]\n","}\n","dataloaders = {\n"," x: torch.utils.data.DataLoader(\n"," image_datasets[x], batch_size=4, shuffle=True, num_workers=4\n"," )\n"," for x in [\"train\", \"val\"]\n","}\n","dataset_sizes = {x: len(image_datasets[x]) for x in [\"train\", \"val\"]}\n","class_names = image_datasets[\"train\"].classes\n","device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n","\n","# Helper function for displaying images\n","def imshow(inp, title=None):\n"," \"\"\"Imshow for Tensor.\"\"\"\n"," inp = inp.numpy().transpose((1, 2, 0))\n"," mean = np.array([0.485, 0.456, 0.406])\n"," std = np.array([0.229, 0.224, 0.225])\n","\n"," # Un-normalize the images\n"," inp = std * inp + mean\n"," # Clip just in case\n"," inp = np.clip(inp, 0, 1)\n"," plt.imshow(inp)\n"," if title is not None:\n"," plt.title(title)\n"," plt.pause(0.001) # pause a bit so that plots are updated\n"," plt.show()\n","\n","\n","# Get a batch of training data\n","# inputs, classes = next(iter(dataloaders['train']))\n","\n","# Make a grid from batch\n","# out = torchvision.utils.make_grid(inputs)\n","\n","# imshow(out, title=[class_names[x] for x in classes])\n","# training\n","\n","\n","def train_model(model, criterion, optimizer, scheduler, num_epochs=25):\n"," since = time.time()\n","\n"," best_model_wts = copy.deepcopy(model.state_dict())\n"," best_acc = 0.0\n","\n"," epoch_time = [] # we'll keep track of the time needed for each epoch\n","\n"," for epoch in range(num_epochs):\n"," epoch_start = time.time()\n"," print(\"Epoch {}/{}\".format(epoch + 1, num_epochs))\n"," print(\"-\" * 10)\n","\n"," # Each epoch has a training and validation phase\n"," for phase in [\"train\", \"val\"]:\n"," if phase == \"train\":\n"," scheduler.step()\n"," model.train() # Set model to training mode\n"," else:\n"," model.eval() # Set model to evaluate mode\n","\n"," running_loss = 0.0\n"," running_corrects = 0\n","\n"," # Iterate over data.\n"," for inputs, labels in dataloaders[phase]:\n"," inputs = inputs.to(device)\n"," labels = labels.to(device)\n","\n"," # zero the parameter gradients\n"," optimizer.zero_grad()\n","\n"," # Forward\n"," # Track history if only in training phase\n"," with torch.set_grad_enabled(phase == \"train\"):\n"," outputs = model(inputs)\n"," _, preds = torch.max(outputs, 1)\n"," loss = criterion(outputs, labels)\n","\n"," # backward + optimize only if in training phase\n"," if phase == \"train\":\n"," loss.backward()\n"," optimizer.step()\n","\n"," # Statistics\n"," running_loss += loss.item() * inputs.size(0)\n"," running_corrects += torch.sum(preds == labels.data)\n","\n"," epoch_loss = running_loss / dataset_sizes[phase]\n"," epoch_acc = running_corrects.double() / dataset_sizes[phase]\n","\n"," print(\"{} Loss: {:.4f} Acc: {:.4f}\".format(phase, epoch_loss, epoch_acc))\n","\n"," # Deep copy the model\n"," if phase == \"val\" and epoch_acc > best_acc:\n"," best_acc = epoch_acc\n"," best_model_wts = copy.deepcopy(model.state_dict())\n","\n"," # Add the epoch time\n"," t_epoch = time.time() - epoch_start\n"," epoch_time.append(t_epoch)\n"," print()\n","\n"," time_elapsed = time.time() - since\n"," print(\n"," \"Training complete in {:.0f}m {:.0f}s\".format(\n"," time_elapsed // 60, time_elapsed % 60\n"," )\n"," )\n"," print(\"Best val Acc: {:4f}\".format(best_acc))\n","\n"," # Load best model weights\n"," model.load_state_dict(best_model_wts)\n"," return model, epoch_time\n","\n","\n"]},{"cell_type":"code","source":["# Download a pre-trained ResNet18 model and freeze its weights\n","resNet18 = torchvision.models.resnet18(pretrained=True)\n","for param in resNet18.parameters():\n"," param.requires_grad = False\n","\n","# Replace the final fully connected layer\n","# Parameters of newly constructed modules have requires_grad=True by default\n","num_ftrs = resNet18.fc.in_features\n","resNet18.fc = nn.Linear(num_ftrs, 2)\n","# Send the model to the GPU\n","resNet18 = resNet18.to(device)\n","# Set the loss function\n","criterion = nn.CrossEntropyLoss()\n","\n","# Observe that only the parameters of the final layer are being optimized\n","optimizer_conv = optim.SGD(resNet18.fc.parameters(), lr=0.001, momentum=0.9)\n","exp_lr_scheduler = lr_scheduler.StepLR(optimizer_conv, step_size=7, gamma=0.1)\n","resNet18, epoch_time = train_model(\n"," resNet18, criterion, optimizer_conv, exp_lr_scheduler, num_epochs=10\n",")\n"],"metadata":{"id":"aRrvPNdgSPJd"},"id":"aRrvPNdgSPJd","execution_count":null,"outputs":[]},{"cell_type":"code","source":["def eval_model(model, test_loader, criterion):\n"," model.eval()\n","\n"," test_loss = 0.0\n"," class_correct = list(0.0 for i in range(2))\n"," class_total = list(0.0 for i in range(2))\n","\n"," with torch.no_grad():\n"," for data, target in test_loader:\n"," data, target = data.to(device), target.to(device)\n","\n"," # Forward pass\n"," output = model(data)\n"," loss = criterion(output, target)\n","\n"," # Update statistics\n"," test_loss += loss.item() * data.size(0)\n"," _, pred = torch.max(output, 1)\n"," correct = pred.eq(target.data.view_as(pred))\n","\n"," for i in range(len(target)):\n"," label = target.data[i]\n"," class_correct[label] += correct[i].item()\n"," class_total[label] += 1\n","\n"," # Calculate average test loss\n"," test_loss = test_loss / len(test_loader.dataset)\n"," print(f\"Test Loss: {test_loss:.6f}\\n\")\n","\n"," # Print accuracy for each class\n"," for i in range(2):\n"," if class_total[i] > 0:\n"," print(\n"," f\"Test Accuracy of {class_names[i]}: {100 * class_correct[i] / class_total[i]:.2f}% \"\n"," f\"({int(np.sum(class_correct[i]))}/{int(np.sum(class_total[i]))})\"\n"," )\n"," else:\n"," print(f\"Test Accuracy of {class_names[i]}: N/A (no training examples)\")\n","\n"," # Print overall accuracy\n"," overall_accuracy = 100.0 * np.sum(class_correct) / np.sum(class_total)\n"," print(f\"\\nTest Accuracy (Overall): {overall_accuracy:.2f}% \"\n"," f\"({int(np.sum(class_correct))}/{int(np.sum(class_total))})\")\n","\n","\n","\n","\n"],"metadata":{"id":"06D2WVv_Wwu4"},"id":"06D2WVv_Wwu4","execution_count":null,"outputs":[]},{"cell_type":"markdown","metadata":{"id":"CiWFsGydy1TB"},"source":["Experiments:\n","Study the code and the results obtained.\n","\n","Modify the code and add an \"eval_model\" function to allow\n","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.\n","\n","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.\n","\n","Apply ther quantization (post and quantization aware) and evaluate impact on model size and accuracy."],"id":"CiWFsGydy1TB"},{"cell_type":"code","source":["import copy\n","import os\n","import time\n","import matplotlib.pyplot as plt\n","import numpy as np\n","import torch\n","import torch.nn as nn\n","import torch.nn.functional as F\n","import torch.optim as optim\n","from torch.optim import lr_scheduler\n","from torchvision import datasets, transforms\n","\n","# Function to train the model\n","def train_model(model, criterion, optimizer, scheduler, num_epochs=25):\n"," since = time.time()\n","\n"," best_model_wts = copy.deepcopy(model.state_dict())\n"," best_acc = 0.0\n","\n"," epoch_time = [] # we'll keep track of the time needed for each epoch\n","\n"," for epoch in range(num_epochs):\n"," epoch_start = time.time()\n"," print(\"Epoch {}/{}\".format(epoch + 1, num_epochs))\n"," print(\"-\" * 10)\n","\n"," # Each epoch has a training and validation phase\n"," for phase in [\"train\", \"val\"]:\n"," if phase == \"train\":\n"," scheduler.step()\n"," model.train() # Set model to training mode\n"," else:\n"," model.eval() # Set model to evaluate mode\n","\n"," running_loss = 0.0\n"," running_corrects = 0\n","\n"," # Iterate over data.\n"," for inputs, labels in dataloaders[phase]:\n"," inputs = inputs.to(device)\n"," labels = labels.to(device)\n","\n"," optimizer.zero_grad()\n","\n"," with torch.set_grad_enabled(phase == \"train\"):\n"," outputs = model(inputs)\n"," _, preds = torch.max(outputs, 1)\n"," loss = criterion(outputs, labels)\n","\n"," if phase == \"train\":\n"," loss.backward()\n"," optimizer.step()\n","\n"," running_loss += loss.item() * inputs.size(0)\n"," running_corrects += torch.sum(preds == labels.data)\n","\n"," epoch_loss = running_loss / dataset_sizes[phase]\n"," epoch_acc = running_corrects.double() / dataset_sizes[phase]\n","\n"," print(\"{} Loss: {:.4f} Acc: {:.4f}\".format(phase, epoch_loss, epoch_acc))\n","\n"," if phase == \"val\" and epoch_acc > best_acc:\n"," best_acc = epoch_acc\n"," best_model_wts = copy.deepcopy(model.state_dict())\n","\n"," t_epoch = time.time() - epoch_start\n"," epoch_time.append(t_epoch)\n"," print()\n","\n"," time_elapsed = time.time() - since\n"," print(\n"," \"Training complete in {:.0f}m {:.0f}s\".format(\n"," time_elapsed // 60, time_elapsed % 60\n"," )\n"," )\n"," print(\"Best val Acc: {:4f}\".format(best_acc))\n","\n"," model.load_state_dict(best_model_wts)\n"," return model, epoch_time\n","\n","# Define the modified ResNet18 model\n","class ModifiedResNet18(nn.Module):\n"," def __init__(self, num_classes=2):\n"," super(ModifiedResNet18, self).__init__()\n"," resnet18 = torchvision.models.resnet18(pretrained=True)\n"," for param in resnet18.parameters():\n"," param.requires_grad = False\n","\n"," # Remove the original fully connected layer\n"," self.features = nn.Sequential(*list(resnet18.children())[:-1])\n","\n"," # Add two new fully connected layers\n"," self.fc = nn.Linear(resnet18.fc.in_features, 16)\n"," self.fc2 = nn.Linear(16, num_classes)\n","\n"," def forward(self, x):\n"," x = self.features(x)\n"," x = x.view(x.size(0), -1)\n"," x = F.relu(self.fc(x))\n"," x = self.fc2(x)\n"," return x\n","\n","# Data transformations\n","data_transforms = {\n"," \"train\": transforms.Compose(\n"," [\n"," transforms.RandomResizedCrop(224),\n"," transforms.RandomHorizontalFlip(),\n"," transforms.ToTensor(),\n"," transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n"," ]\n"," ),\n"," \"val\": transforms.Compose(\n"," [\n"," transforms.Resize(256),\n"," transforms.CenterCrop(224),\n"," transforms.ToTensor(),\n"," transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n"," ]\n"," ),\n","}\n","\n","# Load the data\n","data_dir = \"hymenoptera_data\"\n","image_datasets = {\n"," x: datasets.ImageFolder(os.path.join(data_dir, x), data_transforms[x])\n"," for x in [\"train\", \"val\"]\n","}\n","dataloaders = {\n"," x: torch.utils.data.DataLoader(\n"," image_datasets[x], batch_size=4, shuffle=True, num_workers=0\n"," )\n"," for x in [\"train\", \"val\"]\n","}\n","dataset_sizes = {x: len(image_datasets[x]) for x in [\"train\", \"val\"]}\n","class_names = image_datasets[\"train\"].classes\n","device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n","\n","# Initialize the modified model\n","new_resNet18 = ModifiedResNet18(num_classes=2)\n","new_resNet18 = new_resNet18.to(device)\n","\n","# Set the loss function\n","criterion = nn.CrossEntropyLoss()\n","\n","# Observe that only the parameters of the final layer are being optimized\n","optimizer_conv = optim.SGD(new_resNet18.parameters(), lr=0.001, momentum=0.9)\n","exp_lr_scheduler = lr_scheduler.StepLR(optimizer_conv, step_size=7, gamma=0.1)\n","\n","# Train the modified model\n","new_resNet18, epoch_time = train_model(new_resNet18, criterion, optimizer_conv, exp_lr_scheduler, num_epochs=10)\n"],"metadata":{"id":"XSy45U7fM72l"},"id":"XSy45U7fM72l","execution_count":null,"outputs":[]},{"cell_type":"code","source":["\n","print(\"Original Model: \\n\")\n","eval_model(resNet18.to(device), dataloaders[\"val\"], criterion)\n","print(\"\\n\"+\"New Model: \\n\")\n","eval_model(new_resNet18.to(device), dataloaders[\"val\"], criterion)\n"],"metadata":{"id":"mNfk6kNI3AsQ"},"id":"mNfk6kNI3AsQ","execution_count":null,"outputs":[]},{"cell_type":"code","source":["import torchvision.models as models\n","new_resNet18_quantized = torch.quantization.quantize_dynamic(new_resNet18, dtype=torch.qint8)\n","\n","size_resNet18 = print_size_of_model(new_resNet18, \"fp32\")\n","size_resNet18_quantized = print_size_of_model(new_resNet18_quantized, \"fp32_quant\")\n","\n","print(\n"," \"\\nThe size of the resNet18 model is %.2fMB, which is %.0f times bigger than the resNet18_quantized model\"\n"," % (\n"," size_resNet18 / 1000000,\n"," size_resNet18 / size_resNet18_quantized\n"," )\n",")"],"metadata":{"id":"AGeIeacy2Xgd"},"id":"AGeIeacy2Xgd","execution_count":null,"outputs":[]},{"cell_type":"markdown","id":"04a263f0","metadata":{"id":"04a263f0"},"source":["## Optional\n"," \n","Try this at home!!\n","\n","\n","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/\n","\n","The Exercise consists in deploying the CNN of Exercise 4 in your phone and then test it on live.\n","\n"]},{"cell_type":"markdown","id":"fe954ce4","metadata":{"id":"fe954ce4"},"source":["## Author\n","\n","Alberto BOSIO - Ph. D."]}],"metadata":{"kernelspec":{"display_name":"Python 3","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.8.5"},"vscode":{"interpreter":{"hash":"9e3efbebb05da2d4a1968abe9a0645745f54b63feb7a85a514e4da0495be97eb"}},"colab":{"provenance":[],"gpuType":"T4"},"accelerator":"GPU"},"nbformat":4,"nbformat_minor":5}
\ No newline at end of file
{"cells":[{"cell_type":"markdown","id":"7edf7168","metadata":{"id":"7edf7168"},"source":["# TD2: Deep learning"]},{"cell_type":"markdown","id":"fbb8c8df","metadata":{"id":"fbb8c8df"},"source":["In this TD, you must modify this notebook to answer the questions. To do this,\n","\n","1. Fork this repository\n","2. Clone your forked repository on your local computer\n","3. Answer the questions\n","4. Commit and push regularly\n","\n","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","metadata":{"id":"3d167a29"},"source":["Install and test PyTorch from https://pytorch.org/get-started/locally."]},{"cell_type":"markdown","source":[],"metadata":{"id":"QCeGtWXR9J0y"},"id":"QCeGtWXR9J0y"},{"cell_type":"code","execution_count":27,"id":"330a42f5","metadata":{"colab":{"base_uri":"https://localhost:8080/","height":348},"id":"330a42f5","executionInfo":{"status":"ok","timestamp":1701426305624,"user_tz":-60,"elapsed":7349,"user":{"displayName":"Emilien Paganelli","userId":"14204960141695635735"}},"outputId":"2919d0d6-6505-4f44-c820-d714835dbf32"},"outputs":[{"output_type":"stream","name":"stdout","text":["Requirement already satisfied: torch in /usr/local/lib/python3.10/dist-packages (2.1.0+cu118)\n","Requirement already satisfied: torchvision in /usr/local/lib/python3.10/dist-packages (0.16.0+cu118)\n","Requirement already satisfied: filelock in /usr/local/lib/python3.10/dist-packages (from torch) (3.13.1)\n","Requirement already satisfied: typing-extensions in /usr/local/lib/python3.10/dist-packages (from torch) (4.5.0)\n","Requirement already satisfied: sympy in /usr/local/lib/python3.10/dist-packages (from torch) (1.12)\n","Requirement already satisfied: networkx in /usr/local/lib/python3.10/dist-packages (from torch) (3.2.1)\n","Requirement already satisfied: jinja2 in /usr/local/lib/python3.10/dist-packages (from torch) (3.1.2)\n","Requirement already satisfied: fsspec in /usr/local/lib/python3.10/dist-packages (from torch) (2023.6.0)\n","Requirement already satisfied: triton==2.1.0 in /usr/local/lib/python3.10/dist-packages (from torch) (2.1.0)\n","Requirement already satisfied: numpy in /usr/local/lib/python3.10/dist-packages (from torchvision) (1.23.5)\n","Requirement already satisfied: requests in /usr/local/lib/python3.10/dist-packages (from torchvision) (2.31.0)\n","Requirement already satisfied: pillow!=8.3.*,>=5.3.0 in /usr/local/lib/python3.10/dist-packages (from torchvision) (9.4.0)\n","Requirement already satisfied: MarkupSafe>=2.0 in /usr/local/lib/python3.10/dist-packages (from jinja2->torch) (2.1.3)\n","Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.10/dist-packages (from requests->torchvision) (3.3.2)\n","Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.10/dist-packages (from requests->torchvision) (3.4)\n","Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.10/dist-packages (from requests->torchvision) (2.0.7)\n","Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.10/dist-packages (from requests->torchvision) (2023.7.22)\n","Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.10/dist-packages (from sympy->torch) (1.3.0)\n"]},{"output_type":"execute_result","data":{"text/plain":["'/content'"],"application/vnd.google.colaboratory.intrinsic+json":{"type":"string"}},"metadata":{},"execution_count":27}],"source":["%pip install torch torchvision\n","%pwd"]},{"cell_type":"markdown","id":"0882a636","metadata":{"id":"0882a636"},"source":["\n","To test run the following code"]},{"cell_type":"code","execution_count":28,"id":"b1950f0a","metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"b1950f0a","executionInfo":{"status":"ok","timestamp":1701426306511,"user_tz":-60,"elapsed":894,"user":{"displayName":"Emilien Paganelli","userId":"14204960141695635735"}},"outputId":"ad7c03d1-2f59-4fc4-fc8a-95cd79d1dbc0"},"outputs":[{"output_type":"stream","name":"stdout","text":["tensor([[ 3.5464e-01, -2.5162e-01, -3.4084e-01, -4.0203e-01, 3.5056e-01,\n"," -6.9368e-01, 3.9031e-01, 3.7319e-01, -1.4964e+00, -4.2178e-01],\n"," [-4.0251e-01, 1.5534e+00, -1.0358e+00, -5.9098e-01, -6.0426e-02,\n"," -9.6500e-01, -7.1777e-01, -3.0196e-01, -2.0247e-01, 2.8037e-01],\n"," [-4.0223e-01, -7.3649e-01, -8.6344e-01, -7.9131e-01, -6.1953e-02,\n"," -1.8424e+00, 9.4855e-01, -1.0007e-01, -1.4111e+00, -6.5363e-01],\n"," [ 1.3629e-01, -3.6519e-01, 1.7978e-01, -4.4087e-01, -4.5886e-01,\n"," 4.6493e-01, -1.0318e+00, 1.2653e-01, -3.5993e-01, 7.4553e-01],\n"," [-2.5067e-01, 9.4126e-01, -6.1452e-01, 7.3656e-01, -2.8452e-01,\n"," 9.6051e-01, 1.0045e+00, 4.4673e-04, 1.2508e+00, -9.4441e-01],\n"," [-1.3628e+00, -8.0748e-01, 8.7495e-01, -6.0305e-01, -3.0637e+00,\n"," -4.7690e-01, 7.7525e-01, -8.4844e-02, -8.0040e-01, -1.6611e+00],\n"," [-6.5572e-01, 2.8375e-01, -8.9761e-01, 6.8970e-01, -2.1472e+00,\n"," -5.3845e-01, -1.3347e-01, -4.6737e-01, 5.3647e-01, -9.9889e-02],\n"," [-6.5048e-01, 1.7173e-01, -2.7836e-01, 6.2470e-02, 2.4870e+00,\n"," 1.0898e+00, 7.3483e-01, -9.4346e-01, 1.0283e+00, 1.3574e-01],\n"," [ 5.7310e-01, -1.9131e-01, 6.2758e-01, 1.4844e-01, -7.4922e-01,\n"," -8.9184e-01, 8.0467e-01, -7.2978e-01, -7.0883e-01, -1.4534e-01],\n"," [ 1.1513e+00, -8.5424e-01, 1.3269e+00, -4.4614e-01, -4.5424e-01,\n"," -1.0125e+00, -7.7922e-01, -9.7093e-01, 2.2431e+00, -1.8060e+00],\n"," [ 1.0384e+00, -1.8293e+00, -4.7758e-01, -1.7817e+00, -3.3394e-01,\n"," 1.7667e+00, 1.1108e+00, -1.9820e-01, -5.5519e-01, -5.8780e-01],\n"," [-1.3990e+00, -1.7740e+00, -1.2106e+00, 3.2282e-03, -1.7323e+00,\n"," -2.3775e-01, 5.3892e-01, 9.7521e-01, -3.2019e-01, -1.3805e+00],\n"," [-5.7714e-02, 1.2586e-01, -1.7178e+00, 2.8869e+00, -8.5589e-01,\n"," -4.0656e-01, 1.0384e+00, 8.4800e-01, 4.2282e-01, 7.2093e-01],\n"," [-1.9805e-02, -2.7115e-01, 3.3575e-01, -1.1353e-01, -4.9451e-01,\n"," 2.2995e-01, 1.0682e+00, 1.1319e+00, -4.9516e-01, -1.2863e+00]])\n","AlexNet(\n"," (features): Sequential(\n"," (0): Conv2d(3, 64, kernel_size=(11, 11), stride=(4, 4), padding=(2, 2))\n"," (1): ReLU(inplace=True)\n"," (2): MaxPool2d(kernel_size=3, stride=2, padding=0, dilation=1, ceil_mode=False)\n"," (3): Conv2d(64, 192, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))\n"," (4): ReLU(inplace=True)\n"," (5): MaxPool2d(kernel_size=3, stride=2, padding=0, dilation=1, ceil_mode=False)\n"," (6): Conv2d(192, 384, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n"," (7): ReLU(inplace=True)\n"," (8): Conv2d(384, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n"," (9): ReLU(inplace=True)\n"," (10): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n"," (11): ReLU(inplace=True)\n"," (12): MaxPool2d(kernel_size=3, stride=2, padding=0, dilation=1, ceil_mode=False)\n"," )\n"," (avgpool): AdaptiveAvgPool2d(output_size=(6, 6))\n"," (classifier): Sequential(\n"," (0): Dropout(p=0.5, inplace=False)\n"," (1): Linear(in_features=9216, out_features=4096, bias=True)\n"," (2): ReLU(inplace=True)\n"," (3): Dropout(p=0.5, inplace=False)\n"," (4): Linear(in_features=4096, out_features=4096, bias=True)\n"," (5): ReLU(inplace=True)\n"," (6): Linear(in_features=4096, out_features=1000, bias=True)\n"," )\n",")\n"]}],"source":["import torch\n","\n","N, D = 14, 10\n","x = torch.randn(N, D).type(torch.FloatTensor)\n","print(x)\n","\n","from torchvision import models\n","\n","alexnet = models.alexnet()\n","print(alexnet)"]},{"cell_type":"markdown","id":"23f266da","metadata":{"id":"23f266da"},"source":["## Exercise 1: CNN on CIFAR10\n","\n","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.\n","\n","Have a look at the following documentation to be familiar with PyTorch.\n","\n","https://pytorch.org/tutorials/beginner/pytorch_with_examples.html\n","\n","https://pytorch.org/tutorials/beginner/deep_learning_60min_blitz.html"]},{"cell_type":"markdown","id":"4ba1c82d","metadata":{"id":"4ba1c82d"},"source":["You can test if GPU is available on your machine and thus train on it to speed up the process"]},{"cell_type":"code","execution_count":29,"id":"6e18f2fd","metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"6e18f2fd","executionInfo":{"status":"ok","timestamp":1701426306511,"user_tz":-60,"elapsed":3,"user":{"displayName":"Emilien Paganelli","userId":"14204960141695635735"}},"outputId":"02f0f21b-1da2-46f2-d67e-a27d41d7ff93"},"outputs":[{"output_type":"stream","name":"stdout","text":["CUDA is available! Training on GPU ...\n"]}],"source":["import torch\n","\n","# check if CUDA is available\n","train_on_gpu = torch.cuda.is_available()\n","\n","if not train_on_gpu:\n"," print(\"CUDA is not available. Training on CPU ...\")\n","else:\n"," print(\"CUDA is available! Training on GPU ...\")"]},{"cell_type":"markdown","id":"5cf214eb","metadata":{"id":"5cf214eb"},"source":["Next we load the CIFAR10 dataset"]},{"cell_type":"code","execution_count":30,"id":"462666a2","metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"462666a2","executionInfo":{"status":"ok","timestamp":1701426308369,"user_tz":-60,"elapsed":1860,"user":{"displayName":"Emilien Paganelli","userId":"14204960141695635735"}},"outputId":"a0158530-9554-4462-d7de-7b69df58e40b"},"outputs":[{"output_type":"stream","name":"stdout","text":["Files already downloaded and verified\n","Files already downloaded and verified\n"]}],"source":["import numpy as np\n","from torchvision import datasets, transforms\n","from torch.utils.data.sampler import SubsetRandomSampler\n","\n","# number of subprocesses to use for data loading\n","num_workers = 0\n","# how many samples per batch to load\n","batch_size = 20\n","# percentage of training set to use as validation\n","valid_size = 0.2\n","\n","# convert data to a normalized torch.FloatTensor\n","transform = transforms.Compose(\n"," [transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]\n",")\n","\n","# choose the training and test datasets\n","train_data = datasets.CIFAR10(\"data\", train=True, download=True, transform=transform)\n","test_data = datasets.CIFAR10(\"data\", train=False, download=True, transform=transform)\n","\n","# obtain training indices that will be used for validation\n","num_train = len(train_data)\n","indices = list(range(num_train))\n","np.random.shuffle(indices)\n","split = int(np.floor(valid_size * num_train))\n","train_idx, valid_idx = indices[split:], indices[:split]\n","\n","# define samplers for obtaining training and validation batches\n","train_sampler = SubsetRandomSampler(train_idx)\n","valid_sampler = SubsetRandomSampler(valid_idx)\n","\n","# prepare data loaders (combine dataset and sampler)\n","train_loader = torch.utils.data.DataLoader(\n"," train_data, batch_size=batch_size, sampler=train_sampler, num_workers=num_workers\n",")\n","valid_loader = torch.utils.data.DataLoader(\n"," train_data, batch_size=batch_size, sampler=valid_sampler, num_workers=num_workers\n",")\n","test_loader = torch.utils.data.DataLoader(\n"," test_data, batch_size=batch_size, num_workers=num_workers\n",")\n","\n","# specify the image classes\n","classes = [\n"," \"airplane\",\n"," \"automobile\",\n"," \"bird\",\n"," \"cat\",\n"," \"deer\",\n"," \"dog\",\n"," \"frog\",\n"," \"horse\",\n"," \"ship\",\n"," \"truck\",\n","]"]},{"cell_type":"markdown","id":"58ec3903","metadata":{"id":"58ec3903"},"source":["CNN definition (this one is an example)"]},{"cell_type":"code","execution_count":31,"id":"317bf070","metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"317bf070","executionInfo":{"status":"ok","timestamp":1701426308369,"user_tz":-60,"elapsed":4,"user":{"displayName":"Emilien Paganelli","userId":"14204960141695635735"}},"outputId":"39844deb-a37a-4d6b-dc9d-a5824620d7ad"},"outputs":[{"output_type":"stream","name":"stdout","text":["Net(\n"," (conv1): Conv2d(3, 6, kernel_size=(5, 5), stride=(1, 1))\n"," (pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n"," (conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))\n"," (fc1): Linear(in_features=400, out_features=120, bias=True)\n"," (fc2): Linear(in_features=120, out_features=84, bias=True)\n"," (fc3): Linear(in_features=84, out_features=10, bias=True)\n",")\n"]}],"source":["import torch.nn as nn\n","import torch.nn.functional as F\n","\n","# define the CNN architecture\n","\n","\n","class Net(nn.Module):\n"," def __init__(self):\n"," super(Net, self).__init__()\n"," self.conv1 = nn.Conv2d(3, 6, 5)\n"," self.pool = nn.MaxPool2d(2, 2)\n"," self.conv2 = nn.Conv2d(6, 16, 5)\n"," self.fc1 = nn.Linear(16 * 5 * 5, 120)\n"," self.fc2 = nn.Linear(120, 84)\n"," self.fc3 = nn.Linear(84, 10)\n","\n"," def forward(self, x):\n"," x = self.pool(F.relu(self.conv1(x)))\n"," x = self.pool(F.relu(self.conv2(x)))\n"," x = x.view(-1, 16 * 5 * 5)\n"," x = F.relu(self.fc1(x))\n"," x = F.relu(self.fc2(x))\n"," x = self.fc3(x)\n"," return x\n","\n","\n","# create a complete CNN\n","model = Net()\n","print(model)\n","# move tensors to GPU if CUDA is available\n","if train_on_gpu:\n"," model.cuda()"]},{"cell_type":"markdown","id":"a2dc4974","metadata":{"id":"a2dc4974"},"source":["Loss function and training using SGD (Stochastic Gradient Descent) optimizer"]},{"cell_type":"code","execution_count":null,"id":"4b53f229","metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"4b53f229","outputId":"ffb784e2-4c61-46f8-dee6-8b81f12e9662"},"outputs":[{"output_type":"stream","name":"stdout","text":["Epoch: 0 \tTraining Loss: 43.538748 \tValidation Loss: 39.015653\n","Validation loss decreased (inf --> 39.015653). Saving model ...\n"]}],"source":["import torch.optim as optim\n","\n","criterion = nn.CrossEntropyLoss() # specify loss function\n","optimizer = optim.SGD(model.parameters(), lr=0.01) # specify optimizer\n","\n","n_epochs = 30 # number of epochs to train the model\n","train_loss_list = [] # list to store loss to visualize\n","valid_loss_min = np.Inf # track change in validation loss\n","\n","for epoch in range(n_epochs):\n"," # Keep track of training and validation loss\n"," train_loss = 0.0\n"," valid_loss = 0.0\n","\n"," # Train the model\n"," model.train()\n"," for data, target in train_loader:\n"," # Move tensors to GPU if CUDA is available\n"," if train_on_gpu:\n"," data, target = data.cuda(), target.cuda()\n"," # Clear the gradients of all optimized variables\n"," optimizer.zero_grad()\n"," # Forward pass: compute predicted outputs by passing inputs to the model\n"," output = model(data)\n"," # Calculate the batch loss\n"," loss = criterion(output, target)\n"," # Backward pass: compute gradient of the loss with respect to model parameters\n"," loss.backward()\n"," # Perform a single optimization step (parameter update)\n"," optimizer.step()\n"," # Update training loss\n"," train_loss += loss.item() * data.size(0)\n","\n"," # Validate the model\n"," model.eval()\n"," for data, target in valid_loader:\n"," # Move tensors to GPU if CUDA is available\n"," if train_on_gpu:\n"," data, target = data.cuda(), target.cuda()\n"," # Forward pass: compute predicted outputs by passing inputs to the model\n"," output = model(data)\n"," # Calculate the batch loss\n"," loss = criterion(output, target)\n"," # Update average validation loss\n"," valid_loss += loss.item() * data.size(0)\n","\n"," # Calculate average losses\n"," train_loss = train_loss / len(train_loader)\n"," valid_loss = valid_loss / len(valid_loader)\n"," train_loss_list.append(train_loss)\n","\n"," # Print training/validation statistics\n"," print(\n"," \"Epoch: {} \\tTraining Loss: {:.6f} \\tValidation Loss: {:.6f}\".format(\n"," epoch, train_loss, valid_loss\n"," )\n"," )\n","\n"," # Save model if validation loss has decreased\n"," if valid_loss <= valid_loss_min:\n"," print(\n"," \"Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...\".format(\n"," valid_loss_min, valid_loss\n"," )\n"," )\n"," torch.save(model.state_dict(), \"model_cifar.pt\")\n"," valid_loss_min = valid_loss"]},{"cell_type":"markdown","id":"13e1df74","metadata":{"id":"13e1df74"},"source":["Does overfit occur? If so, do an early stopping."]},{"cell_type":"code","execution_count":null,"id":"d39df818","metadata":{"id":"d39df818"},"outputs":[],"source":["import matplotlib.pyplot as plt\n","\n","plt.plot(range(n_epochs), train_loss_list)\n","plt.xlabel(\"Epoch\")\n","plt.ylabel(\"Loss\")\n","plt.title(\"Performance of Model 1\")\n","plt.show()"]},{"cell_type":"markdown","id":"11df8fd4","metadata":{"id":"11df8fd4"},"source":["Now loading the model with the lowest validation loss value\n"]},{"cell_type":"code","execution_count":null,"id":"e93efdfc","metadata":{"id":"e93efdfc"},"outputs":[],"source":["model.load_state_dict(torch.load(\"./model_cifar.pt\"))\n","\n","# track test loss\n","test_loss = 0.0\n","class_correct = list(0.0 for i in range(10))\n","class_total = list(0.0 for i in range(10))\n","\n","model.eval()\n","# iterate over test data\n","for data, target in test_loader:\n"," # move tensors to GPU if CUDA is available\n"," if train_on_gpu:\n"," data, target = data.cuda(), target.cuda()\n"," # forward pass: compute predicted outputs by passing inputs to the model\n"," output = model(data)\n"," # calculate the batch loss\n"," loss = criterion(output, target)\n"," # update test loss\n"," test_loss += loss.item() * data.size(0)\n"," # convert output probabilities to predicted class\n"," _, pred = torch.max(output, 1)\n"," # compare predictions to true label\n"," correct_tensor = pred.eq(target.data.view_as(pred))\n"," correct = (\n"," np.squeeze(correct_tensor.numpy())\n"," if not train_on_gpu\n"," else np.squeeze(correct_tensor.cpu().numpy())\n"," )\n"," # calculate test accuracy for each object class\n"," for i in range(batch_size):\n"," label = target.data[i]\n"," class_correct[label] += correct[i].item()\n"," class_total[label] += 1\n","\n","# average test loss\n","test_loss = test_loss / len(test_loader)\n","print(\"Test Loss: {:.6f}\\n\".format(test_loss))\n","\n","for i in range(10):\n"," if class_total[i] > 0:\n"," print(\n"," \"Test Accuracy of %5s: %2d%% (%2d/%2d)\"\n"," % (\n"," classes[i],\n"," 100 * class_correct[i] / class_total[i],\n"," np.sum(class_correct[i]),\n"," np.sum(class_total[i]),\n"," )\n"," )\n"," else:\n"," print(\"Test Accuracy of %5s: N/A (no training examples)\" % (classes[i]))\n","\n","print(\n"," \"\\nTest Accuracy (Overall): %2d%% (%2d/%2d)\"\n"," % (\n"," 100.0 * np.sum(class_correct) / np.sum(class_total),\n"," np.sum(class_correct),\n"," np.sum(class_total),\n"," )\n",")"]},{"cell_type":"markdown","id":"944991a2","metadata":{"id":"944991a2"},"source":["Build a new network with the following structure.\n","\n","- It has 3 convolutional layers of kernel size 3 and padding of 1.\n","- The first convolutional layer must output 16 channels, the second 32 and the third 64.\n","- At each convolutional layer output, we apply a ReLU activation then a MaxPool with kernel size of 2.\n","- Then, three fully connected layers, the first two being followed by a ReLU activation and a dropout whose value you will suggest.\n","- The first fully connected layer will have an output size of 512.\n","- The second fully connected layer will have an output size of 64.\n","\n","Compare the results obtained with this new network to those obtained previously."]},{"cell_type":"markdown","source":["Net(\n"," (conv1): Conv2d(3, 6, kernel_size=(5, 5), stride=(1, 1))\n"," (pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n"," (conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))\n"," (fc1): Linear(in_features=400, out_features=120, bias=True)\n"," (fc2): Linear(in_features=120, out_features=84, bias=True)\n"," (fc3): Linear(in_features=84, out_features=10, bias=True)\n",")"],"metadata":{"id":"fgfXjKBy3mwR"},"id":"fgfXjKBy3mwR"},{"cell_type":"code","source":["import torch.nn as nn\n","import torch.nn.functional as F\n","\n","# define the CNN architecture\n","\n","\n","class Net(nn.Module):\n"," def __init__(self):\n"," super(Net, self).__init__()\n"," self.conv1 = nn.Conv2d(3, 16, 3, padding=1)\n"," self.conv2 = nn.Conv2d(16, 32 , 3, padding=1)\n"," self.conv3 = nn.Conv2d(32, 64 , 3, padding=1)\n"," self.pool = nn.MaxPool2d(2, 2)\n"," self.fc1 = nn.Linear(64 * 4 * 4, 512)\n"," self.fc2 = nn.Linear(512, 64)\n"," self.fc3 = nn.Linear(64, 10)\n"," self.dropout = nn.Dropout()\n","\n"," def forward(self, x):\n"," x = self.pool(F.relu(self.conv1(x)))\n"," x = self.pool(F.relu(self.conv2(x)))\n"," x = self.pool(F.relu(self.conv3(x)))\n"," x = x.view(-1, 64 * 4 * 4)\n"," x = F.relu(x)\n"," x = self.dropout(self.fc1(x))\n"," x = F.relu(x)\n"," x = self.dropout(self.fc2(x))\n"," x = self.fc3(x)\n"," return x\n","\n","\n","# create a complete CNN\n","model = Net()\n","print(model)\n","# move tensors to GPU if CUDA is available\n","if train_on_gpu:\n"," model.cuda()"],"metadata":{"id":"BNqCMzKT3SfJ"},"id":"BNqCMzKT3SfJ","execution_count":null,"outputs":[]},{"cell_type":"code","source":["import torch.optim as optim\n","\n","criterion = nn.CrossEntropyLoss() # specify loss function\n","optimizer = optim.SGD(model.parameters(), lr=0.01) # specify optimizer\n","\n","n_epochs = 30 # number of epochs to train the model\n","train_loss_list = [] # list to store loss to visualize\n","valid_loss_min = np.Inf # track change in validation loss\n","\n","for epoch in range(n_epochs):\n"," # Keep track of training and validation loss\n"," train_loss = 0.0\n"," valid_loss = 0.0\n","\n"," # Train the model\n"," model.train()\n"," for data, target in train_loader:\n"," # Move tensors to GPU if CUDA is available\n"," if train_on_gpu:\n"," data, target = data.cuda(), target.cuda()\n"," # Clear the gradients of all optimized variables\n"," optimizer.zero_grad()\n"," # Forward pass: compute predicted outputs by passing inputs to the model\n"," output = model(data)\n"," # Calculate the batch loss\n"," loss = criterion(output, target)\n"," # Backward pass: compute gradient of the loss with respect to model parameters\n"," loss.backward()\n"," # Perform a single optimization step (parameter update)\n"," optimizer.step()\n"," # Update training loss\n"," train_loss += loss.item() * data.size(0)\n","\n"," # Validate the model\n"," model.eval()\n"," for data, target in valid_loader:\n"," # Move tensors to GPU if CUDA is available\n"," if train_on_gpu:\n"," data, target = data.cuda(), target.cuda()\n"," # Forward pass: compute predicted outputs by passing inputs to the model\n"," output = model(data)\n"," # Calculate the batch loss\n"," loss = criterion(output, target)\n"," # Update average validation loss\n"," valid_loss += loss.item() * data.size(0)\n","\n"," # Calculate average losses\n"," train_loss = train_loss / len(train_loader)\n"," valid_loss = valid_loss / len(valid_loader)\n"," train_loss_list.append(train_loss)\n","\n"," # Print training/validation statistics\n"," print(\n"," \"Epoch: {} \\tTraining Loss: {:.6f} \\tValidation Loss: {:.6f}\".format(\n"," epoch, train_loss, valid_loss\n"," )\n"," )\n","\n"," # Save model if validation loss has decreased\n"," if valid_loss <= valid_loss_min:\n"," print(\n"," \"Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...\".format(\n"," valid_loss_min, valid_loss\n"," )\n"," )\n"," torch.save(model.state_dict(), \"model_cifar_3D.pt\")\n"," valid_loss_min = valid_loss"],"metadata":{"id":"heaTYMsTZIEu"},"id":"heaTYMsTZIEu","execution_count":null,"outputs":[]},{"cell_type":"code","source":["import matplotlib.pyplot as plt\n","\n","plt.plot(range(n_epochs), train_loss_list)\n","plt.xlabel(\"Epoch\")\n","plt.ylabel(\"Loss\")\n","plt.title(\"Performance of Model 2\")\n","plt.show()"],"metadata":{"id":"K5lIwyTZZNTt"},"id":"K5lIwyTZZNTt","execution_count":null,"outputs":[]},{"cell_type":"code","source":["model.load_state_dict(torch.load(\"./model_cifar_3D.pt\"))\n","\n","# track test loss\n","test_loss = 0.0\n","class_correct = list(0.0 for i in range(10))\n","class_total = list(0.0 for i in range(10))\n","\n","model.eval()\n","# iterate over test data\n","for data, target in test_loader:\n"," # move tensors to GPU if CUDA is available\n"," if train_on_gpu:\n"," data, target = data.cuda(), target.cuda()\n"," # forward pass: compute predicted outputs by passing inputs to the model\n"," output = model(data)\n"," # calculate the batch loss\n"," loss = criterion(output, target)\n"," # update test loss\n"," test_loss += loss.item() * data.size(0)\n"," # convert output probabilities to predicted class\n"," _, pred = torch.max(output, 1)\n"," # compare predictions to true label\n"," correct_tensor = pred.eq(target.data.view_as(pred))\n"," correct = (\n"," np.squeeze(correct_tensor.numpy())\n"," if not train_on_gpu\n"," else np.squeeze(correct_tensor.cpu().numpy())\n"," )\n"," # calculate test accuracy for each object class\n"," for i in range(batch_size):\n"," label = target.data[i]\n"," class_correct[label] += correct[i].item()\n"," class_total[label] += 1\n","\n","# average test loss\n","test_loss = test_loss / len(test_loader)\n","print(\"Test Loss: {:.6f}\\n\".format(test_loss))\n","\n","for i in range(10):\n"," if class_total[i] > 0:\n"," print(\n"," \"Test Accuracy of %5s: %2d%% (%2d/%2d)\"\n"," % (\n"," classes[i],\n"," 100 * class_correct[i] / class_total[i],\n"," np.sum(class_correct[i]),\n"," np.sum(class_total[i]),\n"," )\n"," )\n"," else:\n"," print(\"Test Accuracy of %5s: N/A (no training examples)\" % (classes[i]))\n","\n","print(\n"," \"\\nTest Accuracy (Overall): %2d%% (%2d/%2d)\"\n"," % (\n"," 100.0 * np.sum(class_correct) / np.sum(class_total),\n"," np.sum(class_correct),\n"," np.sum(class_total),\n"," )\n",")"],"metadata":{"id":"oAeC05EmZN8P"},"id":"oAeC05EmZN8P","execution_count":null,"outputs":[]},{"cell_type":"markdown","id":"bc381cf4","metadata":{"id":"bc381cf4"},"source":["## Exercise 2: Quantization: try to compress the CNN to save space\n","\n","Quantization doc is available from https://pytorch.org/docs/stable/quantization.html#torch.quantization.quantize_dynamic\n"," \n","The Exercise is to quantize post training the above CNN model. Compare the size reduction and the impact on the classification accuracy\n","\n","\n","The size of the model is simply the size of the file."]},{"cell_type":"code","execution_count":null,"id":"ef623c26","metadata":{"id":"ef623c26"},"outputs":[],"source":["import os\n","\n","def print_size_of_model(model, label=\"\"):\n"," torch.save(model.state_dict(), \"temp.p\")\n"," size = os.path.getsize(\"temp.p\")\n"," print(\"model: \", label, \" \\t\", \"Size (KB):\", size / 1e3)\n"," os.remove(\"temp.p\")\n"," return size\n","\n","\n","size_model=print_size_of_model(model, \"fp32\")"]},{"cell_type":"markdown","id":"05c4e9ad","metadata":{"id":"05c4e9ad"},"source":["Post training quantization example"]},{"cell_type":"code","execution_count":null,"id":"c4c65d4b","metadata":{"id":"c4c65d4b"},"outputs":[],"source":["import torch.quantization\n","\n","\n","quantized_model = torch.quantization.quantize_dynamic(model, {torch.nn.Linear}, dtype=torch.qint8)\n","torch.save(quantized_model.state_dict(), \"quantized_model_cifar.pt\")\n","\n","size_quantized = print_size_of_model(quantized_model, \"int8\")\n","\n","print(\"The size of the original model has been divided by %.2f compared to the Quantized model\" % (size_model / size_quantized))"]},{"cell_type":"markdown","id":"7b108e17","metadata":{"id":"7b108e17"},"source":["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","metadata":{"id":"a0a34b90"},"source":["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":"code","source":["quantized_model.load_state_dict(torch.load(\"./quantized_model_cifar.pt\", map_location=torch.device('cpu')))\n","\n","# track test loss\n","test_loss_quantized = 0.0\n","class_correct_quantized = list(0.0 for i in range(10))\n","class_total_quantized = list(0.0 for i in range(10))\n","\n","quantized_model.eval()\n","quantized_model.cpu()\n","# iterate over test data\n","for data, target in test_loader:\n"," # forward pass: compute predicted outputs by passing inputs to the model\n"," output = quantized_model(data)\n"," # calculate the batch loss\n"," loss = criterion(output, target)\n"," # update test loss\n"," test_loss_quantized += loss.item() * data.size(0)\n"," # convert output probabilities to predicted class\n"," _, pred = torch.max(output, 1)\n"," # compare predictions to true label\n"," correct_tensor = pred.eq(target.data.view_as(pred))\n"," correct = np.squeeze(correct_tensor.numpy()) #np.squeeze(correct_tensor.cpu().numpy()\n"," # calculate test accuracy for each object class\n"," for i in range(batch_size):\n"," label = target.data[i]\n"," class_correct_quantized[label] += correct[i].item()\n"," class_total_quantized[label] += 1\n","\n","# average test loss\n","test_loss_quantized = test_loss_quantized / len(test_loader)\n","loss_delta = test_loss_quantized - test_loss\n","print(\"Original Test Loss: {:.6f}\\n\".format(test_loss))\n","print(\"Quantized Test Loss: {:.6f}\\n\".format(test_loss_quantized))\n","print(\"Loss Delta: {:.6f}\\n\".format(loss_delta))\n","\n","for i in range(10):\n"," if class_total[i] > 0:\n"," print(\n"," \"Quantized Test Accuracy of %5s: %2d%% (%2d/%2d)\"\n"," % (\n"," classes[i],\n"," 100 * class_correct_quantized[i] / class_total_quantized[i],\n"," np.sum(class_correct_quantized[i]),\n"," np.sum(class_total_quantized[i]),\n"," ))\n"," print(\n"," \"Original Test Accuracy of %5s: %2d%% (%2d/%2d)\"\n"," % (\n"," classes[i],\n"," 100 * class_correct[i] / class_total[i],\n"," np.sum(class_correct[i]),\n"," np.sum(class_total[i]),\n"," ))\n"," print(\n"," \"Difference in Instances Correctly classified of %5s: %2d \\n\"\n"," % (\n"," classes[i],\n"," class_correct[i]-class_correct_quantized[i],\n","\n"," )\n"," )\n"," else:\n"," print(\"Test Accuracy of %5s: N/A (no training examples)\" % (classes[i]))\n","\n","print(\n"," \"\\nQuantized Test Accuracy (Overall): %2d%% (%2d/%2d)\"\n"," % (\n"," 100.0 * np.sum(class_correct_quantized) / np.sum(class_total_quantized),\n"," np.sum(class_correct_quantized),\n"," np.sum(class_total_quantized),\n"," )\n",")\n","print(\n"," \"\\nOriginal Test Accuracy (Overall): %2d%% (%2d/%2d)\"\n"," % (\n"," 100.0 * np.sum(class_correct) / np.sum(class_total),\n"," np.sum(class_correct),\n"," np.sum(class_total),\n"," )\n",")\n","print(\n"," \"\\nDifference in Instances Correctly classified overall: %2d \\n\"\n"," % (\n"," np.sum(class_correct)-np.sum(class_correct_quantized),\n"," )\n"," )"],"metadata":{"id":"-1DG65AMAHFd"},"id":"-1DG65AMAHFd","execution_count":null,"outputs":[]},{"cell_type":"markdown","id":"201470f9","metadata":{"id":"201470f9"},"source":["## Exercise 3: working with pre-trained models.\n","\n","PyTorch offers several pre-trained models https://pytorch.org/vision/0.8/models.html \n","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.\n"]},{"cell_type":"code","execution_count":null,"id":"b4d13080","metadata":{"id":"b4d13080"},"outputs":[],"source":["import json\n","from PIL import Image\n","\n","# Choose an image to pass through the model\n","test_image = \"dog.png\"\n","\n","# Configure matplotlib for pretty inline plots\n","#%matplotlib inline\n","#%config InlineBackend.figure_format = 'retina'\n","\n","# Prepare the labels\n","with open(\"imagenet-simple-labels.json\") as f:\n"," labels = json.load(f)\n","\n","# First prepare the transformations: resize the image to what the model was trained on and convert it to a tensor\n","data_transform = transforms.Compose(\n"," [\n"," transforms.Resize((224, 224)),\n"," transforms.ToTensor(),\n"," transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n"," ]\n",")\n","# Load the image\n","\n","image = Image.open(test_image)\n","plt.imshow(image), plt.xticks([]), plt.yticks([])\n","\n","# Now apply the transformation, expand the batch dimension, and send the image to the GPU\n","# image = data_transform(image).unsqueeze(0).cuda()\n","image = data_transform(image).unsqueeze(0)\n","\n","# Download the model if it's not there already. It will take a bit on the first run, after that it's fast\n","model = models.resnet50(pretrained=True)\n","# Send the model to the GPU\n","# model.cuda()\n","# Set layers such as dropout and batchnorm in evaluation mode\n","model.eval()\n","\n","# Get the 1000-dimensional model output\n","out = model(image)\n","# Find the predicted class\n","print(\"Predicted class is: {}\".format(labels[out.argmax()]))"]},{"cell_type":"markdown","id":"184cfceb","metadata":{"id":"184cfceb"},"source":["Experiments:\n","\n","Study the code and the results obtained. Possibly add other images downloaded from the internet.\n","\n","What is the size of the model? Quantize it and then check if the model is still able to correctly classify the other images.\n","\n","Experiment with other pre-trained CNN models.\n","\n"," \n"]},{"cell_type":"code","source":["import json\n","from PIL import Image\n","\n","# Choose an image to pass through the model\n","test_image1 = \"koala.jpg\"\n","test_image2 = \"raton.jpg\"\n","\n","# Configure matplotlib for pretty inline plots\n","#%matplotlib inline\n","#%config InlineBackend.figure_format = 'retina'\n","\n","# Prepare the labels\n","with open(\"imagenet-simple-labels.json\") as f:\n"," labels = json.load(f)\n","\n","# First prepare the transformations: resize the image to what the model was trained on and convert it to a tensor\n","data_transform = transforms.Compose(\n"," [\n"," transforms.Resize((224, 224)),\n"," transforms.ToTensor(),\n"," transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n"," ]\n",")\n","# Load the image\n","image1 = Image.open(test_image1)\n","image2 = Image.open(test_image2)\n","\n","plt.figure()\n","\n","\n","f, axarr = plt.subplots(2,1)\n","\n","axarr[0].imshow(image1)\n","axarr[1].imshow(image2)\n","\n","#plt.imshow(image), plt.xticks([]), plt.yticks([])\n","\n","# Now apply the transformation, expand the batch dimension, and send the image to the GPU\n","# image = data_transform(image).unsqueeze(0).cuda()\n","image1 = data_transform(image1).unsqueeze(0)\n","image2 = data_transform(image2).unsqueeze(0)\n","\n","# Download the model if it's not there already. It will take a bit on the first run, after that it's fast\n","\n","resnet50_model=models.resnet50(pretrained=True)\n","resnet50_model_quantized=torch.quantization.quantize_dynamic(resnet50_model, dtype=torch.qint8)\n","\n","googlenet_model = models.googlenet(pretrained=True)\n","googlenet_model_quantized = torch.quantization.quantize_dynamic(googlenet_model, dtype=torch.qint8)\n","\n","\n","# Send the model to the GPU\n","# model.cuda()\n","# Set layers such as dropout and batchnorm in evaluation mode\n","resnet50_model.eval()\n","resnet50_model_quantized.eval()\n","\n","googlenet_model.eval()\n","googlenet_model_quantized.eval()\n","\n","out1=resnet50_model(image1)\n","out1q=resnet50_model_quantized(image1)\n","out2=googlenet_model(image1)\n","out2q=googlenet_model_quantized(image1)\n","\n","out3=resnet50_model(image2)\n","out3q=resnet50_model_quantized(image2)\n","out4=googlenet_model(image2)\n","out4q=googlenet_model_quantized(image2)\n","\n","\n","# Get the 1000-dimensional model output\n","\n","# Find the predicted class\n","print(\"Predicted class for Resnet50 is Koala: {}\".format(labels[out1.argmax()]))\n","print(\"Predicted class for GoogleNet is Koala: {}\".format(labels[out2.argmax()]))\n","print(\"Predicted class for Quantized_Resnet is Koala: {}\".format(labels[out1q.argmax()]))\n","print(\"Predicted class for Quantized_GoogleNet is Koala: {}\".format(labels[out2q.argmax()]))\n","print(\"Predicted class for Resnet50 is Racoon: {}\".format(labels[out3.argmax()]))\n","print(\"Predicted class for GoogleNet is Racoon: {}\".format(labels[out4.argmax()]))\n","print(\"Predicted class for Quantized_Resnet is Racoon: {}\".format(labels[out3q.argmax()]))\n","print(\"Predicted class for Quantized_GoogleNet is Racoon: {}\".format(labels[out4q.argmax()]))"],"metadata":{"id":"wfgNGDlsnYBg"},"id":"wfgNGDlsnYBg","execution_count":null,"outputs":[]},{"cell_type":"code","source":["size_resnet50=print_size_of_model(resnet50_model, \"int8\")\n","size_resnet50_quantized = print_size_of_model(resnet50_model_quantized, \"int8\")\n","\n","print(\"The size of the original ResNet50 model has been divided by %.2f compared to the Quantized ResNet50 model\" % (size_resnet50 /size_resnet50_quantized))\n","\n","size_googlenet=print_size_of_model(googlenet_model, \"int8\")\n","size_googlenet_quantized = print_size_of_model(googlenet_model_quantized, \"int8\")\n","\n","print(\"The size of the original GoogleNet model has been divided by %.2f compared to the Quantized GoogleNet model\" % (size_resnet50 /size_resnet50_quantized))"],"metadata":{"id":"ehW_YwAp5CiO"},"id":"ehW_YwAp5CiO","execution_count":null,"outputs":[]},{"cell_type":"markdown","id":"5d57da4b","metadata":{"id":"5d57da4b"},"source":["## Exercise 4: Transfer Learning\n"," \n"," \n","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.\n","Download and unzip in your working directory the dataset available at the address :\n"," \n","https://download.pytorch.org/tutorial/hymenoptera_data.zip\n"," \n","Execute the following code in order to display some images of the dataset."]},{"cell_type":"code","source":["!wget https://download.pytorch.org/tutorial/hymenoptera_data.zip\n","!unzip hymenoptera_data.zip"],"metadata":{"id":"-GhBj4ORpEr3"},"id":"-GhBj4ORpEr3","execution_count":null,"outputs":[]},{"cell_type":"code","execution_count":null,"id":"be2d31f5","metadata":{"id":"be2d31f5"},"outputs":[],"source":["import os\n","\n","import matplotlib.pyplot as plt\n","import numpy as np\n","import torch\n","import torchvision\n","from torchvision import datasets, transforms\n","\n","# Data augmentation and normalization for training\n","# Just normalization for validation\n","data_transforms = {\n"," \"train\": transforms.Compose(\n"," [\n"," transforms.RandomResizedCrop(\n"," 224\n"," ), # ImageNet models were trained on 224x224 images\n"," transforms.RandomHorizontalFlip(), # flip horizontally 50% of the time - increases train set variability\n"," transforms.ToTensor(), # convert it to a PyTorch tensor\n"," transforms.Normalize(\n"," [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]\n"," ), # ImageNet models expect this norm\n"," ]\n"," ),\n"," \"val\": transforms.Compose(\n"," [\n"," transforms.Resize(256),\n"," transforms.CenterCrop(224),\n"," transforms.ToTensor(),\n"," transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n"," ]\n"," ),\n","}\n","\n","data_dir = \"hymenoptera_data\"\n","# Create train and validation datasets and loaders\n","image_datasets = {\n"," x: datasets.ImageFolder(os.path.join(data_dir, x), data_transforms[x])\n"," for x in [\"train\", \"val\"]\n","}\n","dataloaders = {\n"," x: torch.utils.data.DataLoader(\n"," image_datasets[x], batch_size=4, shuffle=True, num_workers=0\n"," )\n"," for x in [\"train\", \"val\"]\n","}\n","dataset_sizes = {x: len(image_datasets[x]) for x in [\"train\", \"val\"]}\n","class_names = image_datasets[\"train\"].classes\n","device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n","\n","# Helper function for displaying images\n","def imshow(inp, title=None):\n"," \"\"\"Imshow for Tensor.\"\"\"\n"," inp = inp.numpy().transpose((1, 2, 0))\n"," mean = np.array([0.485, 0.456, 0.406])\n"," std = np.array([0.229, 0.224, 0.225])\n","\n"," # Un-normalize the images\n"," inp = std * inp + mean\n"," # Clip just in case\n"," inp = np.clip(inp, 0, 1)\n"," plt.imshow(inp)\n"," if title is not None:\n"," plt.title(title)\n"," plt.pause(0.001) # pause a bit so that plots are updated\n"," plt.show()\n","\n","\n","# Get a batch of training data\n","inputs, classes = next(iter(dataloaders[\"train\"]))\n","\n","# Make a grid from batch\n","out = torchvision.utils.make_grid(inputs)\n","\n","imshow(out, title=[class_names[x] for x in classes])\n","\n"]},{"cell_type":"markdown","id":"bbd48800","metadata":{"id":"bbd48800"},"source":["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","execution_count":null,"id":"572d824c","metadata":{"id":"572d824c"},"outputs":[],"source":["import copy\n","import os\n","import time\n","\n","import matplotlib.pyplot as plt\n","import numpy as np\n","import torch\n","import torch.nn as nn\n","import torch.optim as optim\n","import torchvision\n","from torch.optim import lr_scheduler\n","from torchvision import datasets, transforms\n","\n","# Data augmentation and normalization for training\n","# Just normalization for validation\n","data_transforms = {\n"," \"train\": transforms.Compose(\n"," [\n"," transforms.RandomResizedCrop(\n"," 224\n"," ), # ImageNet models were trained on 224x224 images\n"," transforms.RandomHorizontalFlip(), # flip horizontally 50% of the time - increases train set variability\n"," transforms.ToTensor(), # convert it to a PyTorch tensor\n"," transforms.Normalize(\n"," [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]\n"," ), # ImageNet models expect this norm\n"," ]\n"," ),\n"," \"val\": transforms.Compose(\n"," [\n"," transforms.Resize(256),\n"," transforms.CenterCrop(224),\n"," transforms.ToTensor(),\n"," transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n"," ]\n"," ),\n","}\n","\n","data_dir = \"hymenoptera_data\"\n","# Create train and validation datasets and loaders\n","image_datasets = {\n"," x: datasets.ImageFolder(os.path.join(data_dir, x), data_transforms[x])\n"," for x in [\"train\", \"val\"]\n","}\n","dataloaders = {\n"," x: torch.utils.data.DataLoader(\n"," image_datasets[x], batch_size=4, shuffle=True, num_workers=4\n"," )\n"," for x in [\"train\", \"val\"]\n","}\n","dataset_sizes = {x: len(image_datasets[x]) for x in [\"train\", \"val\"]}\n","class_names = image_datasets[\"train\"].classes\n","device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n","\n","# Helper function for displaying images\n","def imshow(inp, title=None):\n"," \"\"\"Imshow for Tensor.\"\"\"\n"," inp = inp.numpy().transpose((1, 2, 0))\n"," mean = np.array([0.485, 0.456, 0.406])\n"," std = np.array([0.229, 0.224, 0.225])\n","\n"," # Un-normalize the images\n"," inp = std * inp + mean\n"," # Clip just in case\n"," inp = np.clip(inp, 0, 1)\n"," plt.imshow(inp)\n"," if title is not None:\n"," plt.title(title)\n"," plt.pause(0.001) # pause a bit so that plots are updated\n"," plt.show()\n","\n","\n","# Get a batch of training data\n","# inputs, classes = next(iter(dataloaders['train']))\n","\n","# Make a grid from batch\n","# out = torchvision.utils.make_grid(inputs)\n","\n","# imshow(out, title=[class_names[x] for x in classes])\n","# training\n","\n","\n","def train_model(model, criterion, optimizer, scheduler, num_epochs=25):\n"," since = time.time()\n","\n"," best_model_wts = copy.deepcopy(model.state_dict())\n"," best_acc = 0.0\n","\n"," epoch_time = [] # we'll keep track of the time needed for each epoch\n","\n"," for epoch in range(num_epochs):\n"," epoch_start = time.time()\n"," print(\"Epoch {}/{}\".format(epoch + 1, num_epochs))\n"," print(\"-\" * 10)\n","\n"," # Each epoch has a training and validation phase\n"," for phase in [\"train\", \"val\"]:\n"," if phase == \"train\":\n"," scheduler.step()\n"," model.train() # Set model to training mode\n"," else:\n"," model.eval() # Set model to evaluate mode\n","\n"," running_loss = 0.0\n"," running_corrects = 0\n","\n"," # Iterate over data.\n"," for inputs, labels in dataloaders[phase]:\n"," inputs = inputs.to(device)\n"," labels = labels.to(device)\n","\n"," # zero the parameter gradients\n"," optimizer.zero_grad()\n","\n"," # Forward\n"," # Track history if only in training phase\n"," with torch.set_grad_enabled(phase == \"train\"):\n"," outputs = model(inputs)\n"," _, preds = torch.max(outputs, 1)\n"," loss = criterion(outputs, labels)\n","\n"," # backward + optimize only if in training phase\n"," if phase == \"train\":\n"," loss.backward()\n"," optimizer.step()\n","\n"," # Statistics\n"," running_loss += loss.item() * inputs.size(0)\n"," running_corrects += torch.sum(preds == labels.data)\n","\n"," epoch_loss = running_loss / dataset_sizes[phase]\n"," epoch_acc = running_corrects.double() / dataset_sizes[phase]\n","\n"," print(\"{} Loss: {:.4f} Acc: {:.4f}\".format(phase, epoch_loss, epoch_acc))\n","\n"," # Deep copy the model\n"," if phase == \"val\" and epoch_acc > best_acc:\n"," best_acc = epoch_acc\n"," best_model_wts = copy.deepcopy(model.state_dict())\n","\n"," # Add the epoch time\n"," t_epoch = time.time() - epoch_start\n"," epoch_time.append(t_epoch)\n"," print()\n","\n"," time_elapsed = time.time() - since\n"," print(\n"," \"Training complete in {:.0f}m {:.0f}s\".format(\n"," time_elapsed // 60, time_elapsed % 60\n"," )\n"," )\n"," print(\"Best val Acc: {:4f}\".format(best_acc))\n","\n"," # Load best model weights\n"," model.load_state_dict(best_model_wts)\n"," return model, epoch_time\n","\n","\n"]},{"cell_type":"code","source":["# Download a pre-trained ResNet18 model and freeze its weights\n","resNet18 = torchvision.models.resnet18(pretrained=True)\n","for param in resNet18.parameters():\n"," param.requires_grad = False\n","\n","# Replace the final fully connected layer\n","# Parameters of newly constructed modules have requires_grad=True by default\n","num_ftrs = resNet18.fc.in_features\n","resNet18.fc = nn.Linear(num_ftrs, 2)\n","# Send the model to the GPU\n","resNet18 = resNet18.to(device)\n","# Set the loss function\n","criterion = nn.CrossEntropyLoss()\n","\n","# Observe that only the parameters of the final layer are being optimized\n","optimizer_conv = optim.SGD(resNet18.fc.parameters(), lr=0.001, momentum=0.9)\n","exp_lr_scheduler = lr_scheduler.StepLR(optimizer_conv, step_size=7, gamma=0.1)\n","resNet18, epoch_time = train_model(\n"," resNet18, criterion, optimizer_conv, exp_lr_scheduler, num_epochs=10\n",")\n"],"metadata":{"id":"aRrvPNdgSPJd"},"id":"aRrvPNdgSPJd","execution_count":null,"outputs":[]},{"cell_type":"code","source":["def eval_model(model, test_loader, criterion):\n"," model.eval()\n","\n"," test_loss = 0.0\n"," class_correct = list(0.0 for i in range(2))\n"," class_total = list(0.0 for i in range(2))\n","\n"," with torch.no_grad():\n"," for data, target in test_loader:\n"," data, target = data.to(device), target.to(device)\n","\n"," # Forward pass\n"," output = model(data)\n"," loss = criterion(output, target)\n","\n"," # Update statistics\n"," test_loss += loss.item() * data.size(0)\n"," _, pred = torch.max(output, 1)\n"," correct = pred.eq(target.data.view_as(pred))\n","\n"," for i in range(len(target)):\n"," label = target.data[i]\n"," class_correct[label] += correct[i].item()\n"," class_total[label] += 1\n","\n"," # Calculate average test loss\n"," test_loss = test_loss / len(test_loader.dataset)\n"," print(f\"Test Loss: {test_loss:.6f}\\n\")\n","\n"," # Print accuracy for each class\n"," for i in range(2):\n"," if class_total[i] > 0:\n"," print(\n"," f\"Test Accuracy of {class_names[i]}: {100 * class_correct[i] / class_total[i]:.2f}% \"\n"," f\"({int(np.sum(class_correct[i]))}/{int(np.sum(class_total[i]))})\"\n"," )\n"," else:\n"," print(f\"Test Accuracy of {class_names[i]}: N/A (no training examples)\")\n","\n"," # Print overall accuracy\n"," overall_accuracy = 100.0 * np.sum(class_correct) / np.sum(class_total)\n"," print(f\"\\nTest Accuracy (Overall): {overall_accuracy:.2f}% \"\n"," f\"({int(np.sum(class_correct))}/{int(np.sum(class_total))})\")\n","\n","\n","\n","\n"],"metadata":{"id":"06D2WVv_Wwu4"},"id":"06D2WVv_Wwu4","execution_count":null,"outputs":[]},{"cell_type":"markdown","metadata":{"id":"CiWFsGydy1TB"},"source":["Experiments:\n","Study the code and the results obtained.\n","\n","Modify the code and add an \"eval_model\" function to allow\n","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.\n","\n","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.\n","\n","Apply ther quantization (post and quantization aware) and evaluate impact on model size and accuracy."],"id":"CiWFsGydy1TB"},{"cell_type":"code","source":["import copy\n","import os\n","import time\n","import matplotlib.pyplot as plt\n","import numpy as np\n","import torch\n","import torch.nn as nn\n","import torch.nn.functional as F\n","import torch.optim as optim\n","from torch.optim import lr_scheduler\n","from torchvision import datasets, transforms\n","\n","# Function to train the model\n","def train_model(model, criterion, optimizer, scheduler, num_epochs=25):\n"," since = time.time()\n","\n"," best_model_wts = copy.deepcopy(model.state_dict())\n"," best_acc = 0.0\n","\n"," epoch_time = [] # we'll keep track of the time needed for each epoch\n","\n"," for epoch in range(num_epochs):\n"," epoch_start = time.time()\n"," print(\"Epoch {}/{}\".format(epoch + 1, num_epochs))\n"," print(\"-\" * 10)\n","\n"," # Each epoch has a training and validation phase\n"," for phase in [\"train\", \"val\"]:\n"," if phase == \"train\":\n"," scheduler.step()\n"," model.train() # Set model to training mode\n"," else:\n"," model.eval() # Set model to evaluate mode\n","\n"," running_loss = 0.0\n"," running_corrects = 0\n","\n"," # Iterate over data.\n"," for inputs, labels in dataloaders[phase]:\n"," inputs = inputs.to(device)\n"," labels = labels.to(device)\n","\n"," optimizer.zero_grad()\n","\n"," with torch.set_grad_enabled(phase == \"train\"):\n"," outputs = model(inputs)\n"," _, preds = torch.max(outputs, 1)\n"," loss = criterion(outputs, labels)\n","\n"," if phase == \"train\":\n"," loss.backward()\n"," optimizer.step()\n","\n"," running_loss += loss.item() * inputs.size(0)\n"," running_corrects += torch.sum(preds == labels.data)\n","\n"," epoch_loss = running_loss / dataset_sizes[phase]\n"," epoch_acc = running_corrects.double() / dataset_sizes[phase]\n","\n"," print(\"{} Loss: {:.4f} Acc: {:.4f}\".format(phase, epoch_loss, epoch_acc))\n","\n"," if phase == \"val\" and epoch_acc > best_acc:\n"," best_acc = epoch_acc\n"," best_model_wts = copy.deepcopy(model.state_dict())\n","\n"," t_epoch = time.time() - epoch_start\n"," epoch_time.append(t_epoch)\n"," print()\n","\n"," time_elapsed = time.time() - since\n"," print(\n"," \"Training complete in {:.0f}m {:.0f}s\".format(\n"," time_elapsed // 60, time_elapsed % 60\n"," )\n"," )\n"," print(\"Best val Acc: {:4f}\".format(best_acc))\n","\n"," model.load_state_dict(best_model_wts)\n"," return model, epoch_time\n","\n","# Define the modified ResNet18 model\n","class ModifiedResNet18(nn.Module):\n"," def __init__(self, num_classes=2):\n"," super(ModifiedResNet18, self).__init__()\n"," resnet18 = torchvision.models.resnet18(pretrained=True)\n"," for param in resnet18.parameters():\n"," param.requires_grad = False\n","\n"," # Remove the original fully connected layer\n"," self.features = nn.Sequential(*list(resnet18.children())[:-1])\n","\n"," # Add two new fully connected layers\n"," self.fc = nn.Linear(resnet18.fc.in_features, 16)\n"," self.fc2 = nn.Linear(16, num_classes)\n","\n"," def forward(self, x):\n"," x = self.features(x)\n"," x = x.view(x.size(0), -1)\n"," x = F.relu(self.fc(x))\n"," x = self.fc2(x)\n"," return x\n","\n","# Data transformations\n","data_transforms = {\n"," \"train\": transforms.Compose(\n"," [\n"," transforms.RandomResizedCrop(224),\n"," transforms.RandomHorizontalFlip(),\n"," transforms.ToTensor(),\n"," transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n"," ]\n"," ),\n"," \"val\": transforms.Compose(\n"," [\n"," transforms.Resize(256),\n"," transforms.CenterCrop(224),\n"," transforms.ToTensor(),\n"," transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n"," ]\n"," ),\n","}\n","\n","# Load the data\n","data_dir = \"hymenoptera_data\"\n","image_datasets = {\n"," x: datasets.ImageFolder(os.path.join(data_dir, x), data_transforms[x])\n"," for x in [\"train\", \"val\"]\n","}\n","dataloaders = {\n"," x: torch.utils.data.DataLoader(\n"," image_datasets[x], batch_size=4, shuffle=True, num_workers=0\n"," )\n"," for x in [\"train\", \"val\"]\n","}\n","dataset_sizes = {x: len(image_datasets[x]) for x in [\"train\", \"val\"]}\n","class_names = image_datasets[\"train\"].classes\n","device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n","\n","# Initialize the modified model\n","new_resNet18 = ModifiedResNet18(num_classes=2)\n","new_resNet18 = new_resNet18.to(device)\n","\n","# Set the loss function\n","criterion = nn.CrossEntropyLoss()\n","\n","# Observe that only the parameters of the final layer are being optimized\n","optimizer_conv = optim.SGD(new_resNet18.parameters(), lr=0.001, momentum=0.9)\n","exp_lr_scheduler = lr_scheduler.StepLR(optimizer_conv, step_size=7, gamma=0.1)\n","\n","# Train the modified model\n","new_resNet18, epoch_time = train_model(new_resNet18, criterion, optimizer_conv, exp_lr_scheduler, num_epochs=10)\n"],"metadata":{"id":"XSy45U7fM72l"},"id":"XSy45U7fM72l","execution_count":null,"outputs":[]},{"cell_type":"code","source":["\n","print(\"Original Model: \\n\")\n","eval_model(resNet18.to(device), dataloaders[\"val\"], criterion)\n","print(\"\\n\"+\"New Model: \\n\")\n","eval_model(new_resNet18.to(device), dataloaders[\"val\"], criterion)\n"],"metadata":{"id":"mNfk6kNI3AsQ"},"id":"mNfk6kNI3AsQ","execution_count":null,"outputs":[]},{"cell_type":"code","source":["import torchvision.models as models\n","new_resNet18_quantized = torch.quantization.quantize_dynamic(new_resNet18, dtype=torch.qint8)\n","\n","size_resNet18 = print_size_of_model(new_resNet18, \"fp32\")\n","size_resNet18_quantized = print_size_of_model(new_resNet18_quantized, \"fp32_quant\")\n","\n","print(\n"," \"\\nThe size of the resNet18 model is %.2fMB, which is %.0f times bigger than the resNet18_quantized model\"\n"," % (\n"," size_resNet18 / 1000000,\n"," size_resNet18 / size_resNet18_quantized\n"," )\n",")"],"metadata":{"id":"AGeIeacy2Xgd"},"id":"AGeIeacy2Xgd","execution_count":null,"outputs":[]},{"cell_type":"markdown","id":"04a263f0","metadata":{"id":"04a263f0"},"source":["## Optional\n"," \n","Try this at home!!\n","\n","\n","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/\n","\n","The Exercise consists in deploying the CNN of Exercise 4 in your phone and then test it on live.\n","\n"]},{"cell_type":"markdown","id":"fe954ce4","metadata":{"id":"fe954ce4"},"source":["## Author\n","\n","Alberto BOSIO - Ph. D."]}],"metadata":{"kernelspec":{"display_name":"Python 3","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.8.5"},"vscode":{"interpreter":{"hash":"9e3efbebb05da2d4a1968abe9a0645745f54b63feb7a85a514e4da0495be97eb"}},"colab":{"provenance":[],"gpuType":"T4"},"accelerator":"GPU"},"nbformat":4,"nbformat_minor":5}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment