{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# For tips on running notebooks in Google Colab, see\n# https://pytorch.org/tutorials/beginner/colab\n%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Training a Classifier\n=====================\n\nThis is it. You have seen how to define neural networks, compute loss\nand make updates to the weights of the network.\n\nNow you might be thinking,\n\nWhat about data?\n----------------\n\nGenerally, when you have to deal with image, text, audio or video data,\nyou can use standard python packages that load data into a numpy array.\nThen you can convert this array into a `torch.*Tensor`.\n\n- For images, packages such as Pillow, OpenCV are useful\n- For audio, packages such as scipy and librosa\n- For text, either raw Python or Cython based loading, or NLTK and\n SpaCy are useful\n\nSpecifically for vision, we have created a package called `torchvision`,\nthat has data loaders for common datasets such as ImageNet, CIFAR10,\nMNIST, etc. and data transformers for images, viz.,\n`torchvision.datasets` and `torch.utils.data.DataLoader`.\n\nThis provides a huge convenience and avoids writing boilerplate code.\n\nFor this tutorial, we will use the CIFAR10 dataset. It has the classes:\n'airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse',\n'ship', 'truck'. The images in CIFAR-10 are of size 3x32x32, i.e.\n3-channel color images of 32x32 pixels in size.\n\n![cifar10](https://pytorch.org/tutorials/_static/img/cifar10.png)\n\nTraining an image classifier\n----------------------------\n\nWe will do the following steps in order:\n\n1. Load and normalize the CIFAR10 training and test datasets using\n `torchvision`\n2. Define a Convolutional Neural Network\n3. Define a loss function\n4. Train the network on the training data\n5. Test the network on the test data\n\n### 1. Load and normalize CIFAR10\n\nUsing `torchvision`, it's extremely easy to load CIFAR10.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import torch\nimport torchvision\nimport torchvision.transforms as transforms" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The output of torchvision datasets are PILImage images of range \\[0,\n1\\]. We transform them to Tensors of normalized range \\[-1, 1\\].\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```{=html}\n
NOTE:
\n```\n```{=html}\n
\n```\n```{=html}\n

If running on Windows and you get a BrokenPipeError, try settingthe num_worker of torch.utils.data.DataLoader() to 0.

\n```\n```{=html}\n
\n```\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "transform = transforms.Compose(\n [transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n\nbatch_size = 4\n\ntrainset = torchvision.datasets.CIFAR10(root='./data', train=True,\n download=True, transform=transform)\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size,\n shuffle=True, num_workers=2)\n\ntestset = torchvision.datasets.CIFAR10(root='./data', train=False,\n download=True, transform=transform)\ntestloader = torch.utils.data.DataLoader(testset, batch_size=batch_size,\n shuffle=False, num_workers=2)\n\nclasses = ('plane', 'car', 'bird', 'cat',\n 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let us show some of the training images, for fun.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nimport numpy as np\n\n# functions to show an image\n\n\ndef imshow(img):\n img = img / 2 + 0.5 # unnormalize\n npimg = img.numpy()\n plt.imshow(np.transpose(npimg, (1, 2, 0)))\n plt.show()\n\n\n# get some random training images\ndataiter = iter(trainloader)\nimages, labels = next(dataiter)\n\n# show images\nimshow(torchvision.utils.make_grid(images))\n# print labels\nprint(' '.join(f'{classes[labels[j]]:5s}' for j in range(batch_size)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "2. Define a Convolutional Neural Network\n========================================\n\nCopy the neural network from the Neural Networks section before and\nmodify it to take 3-channel images (instead of 1-channel images as it\nwas defined).\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass Net(nn.Module):\n def __init__(self):\n super().__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 = torch.flatten(x, 1) # flatten all dimensions except batch\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\n\nnet = Net()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "3. Define a Loss function and optimizer\n=======================================\n\nLet\\'s use a Classification Cross-Entropy loss and SGD with momentum.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import torch.optim as optim\n\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "4. Train the network\n====================\n\nThis is when things start to get interesting. We simply have to loop\nover our data iterator, and feed the inputs to the network and optimize.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "for epoch in range(2): # loop over the dataset multiple times\n\n running_loss = 0.0\n for i, data in enumerate(trainloader, 0):\n # get the inputs; data is a list of [inputs, labels]\n inputs, labels = data\n\n # zero the parameter gradients\n optimizer.zero_grad()\n\n # forward + backward + optimize\n outputs = net(inputs)\n loss = criterion(outputs, labels)\n loss.backward()\n optimizer.step()\n\n # print statistics\n running_loss += loss.item()\n if i % 2000 == 1999: # print every 2000 mini-batches\n print(f'[{epoch + 1}, {i + 1:5d}] loss: {running_loss / 2000:.3f}')\n running_loss = 0.0\n\nprint('Finished Training')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let\\'s quickly save our trained model:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "PATH = './cifar_net.pth'\ntorch.save(net.state_dict(), PATH)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "See [here](https://pytorch.org/docs/stable/notes/serialization.html) for\nmore details on saving PyTorch models.\n\n5. Test the network on the test data\n====================================\n\nWe have trained the network for 2 passes over the training dataset. But\nwe need to check if the network has learnt anything at all.\n\nWe will check this by predicting the class label that the neural network\noutputs, and checking it against the ground-truth. If the prediction is\ncorrect, we add the sample to the list of correct predictions.\n\nOkay, first step. Let us display an image from the test set to get\nfamiliar.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "dataiter = iter(testloader)\nimages, labels = next(dataiter)\n\n# print images\nimshow(torchvision.utils.make_grid(images))\nprint('GroundTruth: ', ' '.join(f'{classes[labels[j]]:5s}' for j in range(4)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Next, let\\'s load back in our saved model (note: saving and re-loading\nthe model wasn\\'t necessary here, we only did it to illustrate how to do\nso):\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "net = Net()\nnet.load_state_dict(torch.load(PATH, weights_only=True))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Okay, now let us see what the neural network thinks these examples above\nare:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "outputs = net(images)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The outputs are energies for the 10 classes. The higher the energy for a\nclass, the more the network thinks that the image is of the particular\nclass. So, let\\'s get the index of the highest energy:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "_, predicted = torch.max(outputs, 1)\n\nprint('Predicted: ', ' '.join(f'{classes[predicted[j]]:5s}'\n for j in range(4)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The results seem pretty good.\n\nLet us look at how the network performs on the whole dataset.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "correct = 0\ntotal = 0\n# since we're not training, we don't need to calculate the gradients for our outputs\nwith torch.no_grad():\n for data in testloader:\n images, labels = data\n # calculate outputs by running images through the network\n outputs = net(images)\n # the class with the highest energy is what we choose as prediction\n _, predicted = torch.max(outputs, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n\nprint(f'Accuracy of the network on the 10000 test images: {100 * correct // total} %')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "That looks way better than chance, which is 10% accuracy (randomly\npicking a class out of 10 classes). Seems like the network learnt\nsomething.\n\nHmmm, what are the classes that performed well, and the classes that did\nnot perform well:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# prepare to count predictions for each class\ncorrect_pred = {classname: 0 for classname in classes}\ntotal_pred = {classname: 0 for classname in classes}\n\n# again no gradients needed\nwith torch.no_grad():\n for data in testloader:\n images, labels = data\n outputs = net(images)\n _, predictions = torch.max(outputs, 1)\n # collect the correct predictions for each class\n for label, prediction in zip(labels, predictions):\n if label == prediction:\n correct_pred[classes[label]] += 1\n total_pred[classes[label]] += 1\n\n\n# print accuracy for each class\nfor classname, correct_count in correct_pred.items():\n accuracy = 100 * float(correct_count) / total_pred[classname]\n print(f'Accuracy for class: {classname:5s} is {accuracy:.1f} %')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Okay, so what next?\n\nHow do we run these neural networks on the GPU?\n\nTraining on GPU\n===============\n\nJust like how you transfer a Tensor onto the GPU, you transfer the\nneural net onto the GPU.\n\nLet\\'s first define our device as the first visible cuda device if we\nhave CUDA available:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n\n# Assuming that we are on a CUDA machine, this should print a CUDA device:\n\nprint(device)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The rest of this section assumes that `device` is a CUDA device.\n\nThen these methods will recursively go over all modules and convert\ntheir parameters and buffers to CUDA tensors:\n\n``` {.python}\nnet.to(device)\n```\n\nRemember that you will have to send the inputs and targets at every step\nto the GPU too:\n\n``` {.python}\ninputs, labels = data[0].to(device), data[1].to(device)\n```\n\nWhy don\\'t I notice MASSIVE speedup compared to CPU? Because your\nnetwork is really small.\n\n**Exercise:** Try increasing the width of your network (argument 2 of\nthe first `nn.Conv2d`, and argument 1 of the second `nn.Conv2d` -- they\nneed to be the same number), see what kind of speedup you get.\n\n**Goals achieved**:\n\n- Understanding PyTorch\\'s Tensor library and neural networks at a\n high level.\n- Train a small neural network to classify images\n\nTraining on multiple GPUs\n=========================\n\nIf you want to see even more MASSIVE speedup using all of your GPUs,\nplease check out `data_parallel_tutorial`{.interpreted-text role=\"doc\"}.\n\nWhere do I go next?\n===================\n\n- `Train neural nets to play video games `{.interpreted-text\n role=\"doc\"}\n- [Train a state-of-the-art ResNet network on\n imagenet](https://github.com/pytorch/examples/tree/master/imagenet)\n- [Train a face generator using Generative Adversarial\n Networks](https://github.com/pytorch/examples/tree/master/dcgan)\n- [Train a word-level language model using Recurrent LSTM\n networks](https://github.com/pytorch/examples/tree/master/word_language_model)\n- [More examples](https://github.com/pytorch/examples)\n- [More tutorials](https://github.com/pytorch/tutorials)\n- [Discuss PyTorch on the Forums](https://discuss.pytorch.org/)\n- [Chat with other users on\n Slack](https://pytorch.slack.com/messages/beginner/)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "del dataiter" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "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.10.12" } }, "nbformat": 4, "nbformat_minor": 0 }