Path: blob/main/beginner_source/blitz/cifar10_tutorial.py
2095 views
# -*- coding: utf-8 -*-1"""2Training a Classifier3=====================45This is it. You have seen how to define neural networks, compute loss and make6updates to the weights of the network.78Now you might be thinking,910What about data?11----------------1213Generally, when you have to deal with image, text, audio or video data,14you can use standard python packages that load data into a numpy array.15Then you can convert this array into a ``torch.*Tensor``.1617- For images, packages such as Pillow, OpenCV are useful18- For audio, packages such as scipy and librosa19- For text, either raw Python or Cython based loading, or NLTK and20SpaCy are useful2122Specifically for vision, we have created a package called23``torchvision``, that has data loaders for common datasets such as24ImageNet, CIFAR10, MNIST, etc. and data transformers for images, viz.,25``torchvision.datasets`` and ``torch.utils.data.DataLoader``.2627This provides a huge convenience and avoids writing boilerplate code.2829For this tutorial, we will use the CIFAR10 dataset.30It has the classes: ‘airplane’, ‘automobile’, ‘bird’, ‘cat’, ‘deer’,31‘dog’, ‘frog’, ‘horse’, ‘ship’, ‘truck’. The images in CIFAR-10 are of32size 3x32x32, i.e. 3-channel color images of 32x32 pixels in size.3334.. figure:: /_static/img/cifar10.png35:alt: cifar103637cifar10383940Training an image classifier41----------------------------4243We will do the following steps in order:44451. Load and normalize the CIFAR10 training and test datasets using46``torchvision``472. Define a Convolutional Neural Network483. Define a loss function494. Train the network on the training data505. Test the network on the test data51521. Load and normalize CIFAR1053^^^^^^^^^^^^^^^^^^^^^^^^^^^^^5455Using ``torchvision``, it’s extremely easy to load CIFAR10.56"""57import torch58import torchvision59import torchvision.transforms as transforms6061########################################################################62# The output of torchvision datasets are PILImage images of range [0, 1].63# We transform them to Tensors of normalized range [-1, 1].6465########################################################################66# .. note::67# If you are running this tutorial on Windows or MacOS and encounter a68# BrokenPipeError or RuntimeError related to multiprocessing, try setting69# the num_worker of torch.utils.data.DataLoader() to 0.7071transform = transforms.Compose(72[transforms.ToTensor(),73transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])7475batch_size = 47677trainset = torchvision.datasets.CIFAR10(root='./data', train=True,78download=True, transform=transform)79trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size,80shuffle=True, num_workers=2)8182testset = torchvision.datasets.CIFAR10(root='./data', train=False,83download=True, transform=transform)84testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size,85shuffle=False, num_workers=2)8687classes = ('plane', 'car', 'bird', 'cat',88'deer', 'dog', 'frog', 'horse', 'ship', 'truck')8990########################################################################91# Let us show some of the training images, for fun.9293import matplotlib.pyplot as plt94import numpy as np9596# functions to show an image979899def imshow(img):100img = img / 2 + 0.5 # unnormalize101npimg = img.numpy()102plt.imshow(np.transpose(npimg, (1, 2, 0)))103plt.show()104105106# get some random training images107dataiter = iter(trainloader)108images, labels = next(dataiter)109110# show images111imshow(torchvision.utils.make_grid(images))112# print labels113print(' '.join(f'{classes[labels[j]]:5s}' for j in range(batch_size)))114115116########################################################################117# 2. Define a Convolutional Neural Network118# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^119# Copy the neural network from the Neural Networks section before and modify it to120# take 3-channel images (instead of 1-channel images as it was defined).121122import torch.nn as nn123import torch.nn.functional as F124125126class Net(nn.Module):127def __init__(self):128super().__init__()129self.conv1 = nn.Conv2d(3, 6, 5)130self.pool = nn.MaxPool2d(2, 2)131self.conv2 = nn.Conv2d(6, 16, 5)132self.fc1 = nn.Linear(16 * 5 * 5, 120)133self.fc2 = nn.Linear(120, 84)134self.fc3 = nn.Linear(84, 10)135136def forward(self, x):137x = self.pool(F.relu(self.conv1(x)))138x = self.pool(F.relu(self.conv2(x)))139x = torch.flatten(x, 1) # flatten all dimensions except batch140x = F.relu(self.fc1(x))141x = F.relu(self.fc2(x))142x = self.fc3(x)143return x144145146net = Net()147148########################################################################149# 3. Define a Loss function and optimizer150# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^151# Let's use a Classification Cross-Entropy loss and SGD with momentum.152153import torch.optim as optim154155criterion = nn.CrossEntropyLoss()156optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)157158########################################################################159# 4. Train the network160# ^^^^^^^^^^^^^^^^^^^^161#162# This is when things start to get interesting.163# We simply have to loop over our data iterator, and feed the inputs to the164# network and optimize.165166for epoch in range(2): # loop over the dataset multiple times167168running_loss = 0.0169for i, data in enumerate(trainloader, 0):170# get the inputs; data is a list of [inputs, labels]171inputs, labels = data172173# zero the parameter gradients174optimizer.zero_grad()175176# forward + backward + optimize177outputs = net(inputs)178loss = criterion(outputs, labels)179loss.backward()180optimizer.step()181182# print statistics183running_loss += loss.item()184if i % 2000 == 1999: # print every 2000 mini-batches185print(f'[{epoch + 1}, {i + 1:5d}] loss: {running_loss / 2000:.3f}')186running_loss = 0.0187188print('Finished Training')189190########################################################################191# Let's quickly save our trained model:192193PATH = './cifar_net.pth'194torch.save(net.state_dict(), PATH)195196########################################################################197# See `here <https://pytorch.org/docs/stable/notes/serialization.html>`_198# for more details on saving PyTorch models.199#200# 5. Test the network on the test data201# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^202#203# We have trained the network for 2 passes over the training dataset.204# But we need to check if the network has learnt anything at all.205#206# We will check this by predicting the class label that the neural network207# outputs, and checking it against the ground-truth. If the prediction is208# correct, we add the sample to the list of correct predictions.209#210# Okay, first step. Let us display an image from the test set to get familiar.211212dataiter = iter(testloader)213images, labels = next(dataiter)214215# print images216imshow(torchvision.utils.make_grid(images))217print('GroundTruth: ', ' '.join(f'{classes[labels[j]]:5s}' for j in range(4)))218219########################################################################220# Next, let's load back in our saved model (note: saving and re-loading the model221# wasn't necessary here, we only did it to illustrate how to do so):222223net = Net()224net.load_state_dict(torch.load(PATH, weights_only=True))225226########################################################################227# Okay, now let us see what the neural network thinks these examples above are:228229outputs = net(images)230231########################################################################232# The outputs are energies for the 10 classes.233# The higher the energy for a class, the more the network234# thinks that the image is of the particular class.235# So, let's get the index of the highest energy:236_, predicted = torch.max(outputs, 1)237238print('Predicted: ', ' '.join(f'{classes[predicted[j]]:5s}'239for j in range(4)))240241########################################################################242# The results seem pretty good.243#244# Let us look at how the network performs on the whole dataset.245246correct = 0247total = 0248# since we're not training, we don't need to calculate the gradients for our outputs249with torch.no_grad():250for data in testloader:251images, labels = data252# calculate outputs by running images through the network253outputs = net(images)254# the class with the highest energy is what we choose as prediction255_, predicted = torch.max(outputs, 1)256total += labels.size(0)257correct += (predicted == labels).sum().item()258259print(f'Accuracy of the network on the 10000 test images: {100 * correct // total} %')260261########################################################################262# That looks way better than chance, which is 10% accuracy (randomly picking263# a class out of 10 classes).264# Seems like the network learnt something.265#266# Hmmm, what are the classes that performed well, and the classes that did267# not perform well:268269# prepare to count predictions for each class270correct_pred = {classname: 0 for classname in classes}271total_pred = {classname: 0 for classname in classes}272273# again no gradients needed274with torch.no_grad():275for data in testloader:276images, labels = data277outputs = net(images)278_, predictions = torch.max(outputs, 1)279# collect the correct predictions for each class280for label, prediction in zip(labels, predictions):281if label == prediction:282correct_pred[classes[label]] += 1283total_pred[classes[label]] += 1284285286# print accuracy for each class287for classname, correct_count in correct_pred.items():288accuracy = 100 * float(correct_count) / total_pred[classname]289print(f'Accuracy for class: {classname:5s} is {accuracy:.1f} %')290291########################################################################292# Okay, so what next?293#294# How do we run these neural networks on the GPU?295#296# Training on GPU297# ----------------298# Just like how you transfer a Tensor onto the GPU, you transfer the neural299# net onto the GPU.300#301# Let's first define our device as the first visible cuda device if we have302# CUDA available:303304device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')305306# Assuming that we are on a CUDA machine, this should print a CUDA device:307308print(device)309310########################################################################311# The rest of this section assumes that ``device`` is a CUDA device.312#313# Then these methods will recursively go over all modules and convert their314# parameters and buffers to CUDA tensors:315#316# .. code:: python317#318# net.to(device)319#320#321# Remember that you will have to send the inputs and targets at every step322# to the GPU too:323#324# .. code:: python325#326# inputs, labels = data[0].to(device), data[1].to(device)327#328# Why don't I notice MASSIVE speedup compared to CPU? Because your network329# is really small.330#331# **Exercise:** Try increasing the width of your network (argument 2 of332# the first ``nn.Conv2d``, and argument 1 of the second ``nn.Conv2d`` –333# they need to be the same number), see what kind of speedup you get.334#335# **Goals achieved**:336#337# - Understanding PyTorch's Tensor library and neural networks at a high level.338# - Train a small neural network to classify images339#340# Training on multiple GPUs341# -------------------------342# If you want to see even more MASSIVE speedup using all of your GPUs,343# please check out :doc:`data_parallel_tutorial`.344#345# Where do I go next?346# -------------------347#348# - :doc:`Train neural nets to play video games </intermediate/reinforcement_q_learning>`349# - `Train a state-of-the-art ResNet network on imagenet`_350# - `Train a face generator using Generative Adversarial Networks`_351# - `Train a word-level language model using Recurrent LSTM networks`_352# - `More examples`_353# - `More tutorials`_354# - `Discuss PyTorch on the Forums`_355# - `Chat with other users on Slack`_356#357# .. _Train a state-of-the-art ResNet network on imagenet: https://github.com/pytorch/examples/tree/master/imagenet358# .. _Train a face generator using Generative Adversarial Networks: https://github.com/pytorch/examples/tree/master/dcgan359# .. _Train a word-level language model using Recurrent LSTM networks: https://github.com/pytorch/examples/tree/master/word_language_model360# .. _More examples: https://github.com/pytorch/examples361# .. _More tutorials: https://github.com/pytorch/tutorials362# .. _Discuss PyTorch on the Forums: https://discuss.pytorch.org/363# .. _Chat with other users on Slack: https://pytorch.slack.com/messages/beginner/364365# %%%%%%INVISIBLE_CODE_BLOCK%%%%%%366del dataiter367# %%%%%%INVISIBLE_CODE_BLOCK%%%%%%368369370