Path: blob/main/beginner_source/blitz/cifar10_tutorial.py
5712 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 torchvision59from torchvision.transforms import v26061########################################################################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 = v2.Compose([72v2.ToImage(),73v2.ToDtype(torch.float32, scale=True),74v2.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])7576batch_size = 47778trainset = torchvision.datasets.CIFAR10(root='./data', train=True,79download=True, transform=transform)80trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size,81shuffle=True, num_workers=2)8283testset = torchvision.datasets.CIFAR10(root='./data', train=False,84download=True, transform=transform)85testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size,86shuffle=False, num_workers=2)8788classes = ('plane', 'car', 'bird', 'cat',89'deer', 'dog', 'frog', 'horse', 'ship', 'truck')9091########################################################################92# Let us show some of the training images, for fun.9394import matplotlib.pyplot as plt95import numpy as np9697# functions to show an image9899100def imshow(img):101img = img / 2 + 0.5 # unnormalize102npimg = img.numpy()103plt.imshow(np.transpose(npimg, (1, 2, 0)))104plt.show()105106107# get some random training images108dataiter = iter(trainloader)109images, labels = next(dataiter)110111# show images112imshow(torchvision.utils.make_grid(images))113# print labels114print(' '.join(f'{classes[labels[j]]:5s}' for j in range(batch_size)))115116117########################################################################118# 2. Define a Convolutional Neural Network119# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^120# Copy the neural network from the Neural Networks section before and modify it to121# take 3-channel images (instead of 1-channel images as it was defined).122123import torch.nn as nn124import torch.nn.functional as F125126127class Net(nn.Module):128def __init__(self):129super().__init__()130self.conv1 = nn.Conv2d(3, 6, 5)131self.pool = nn.MaxPool2d(2, 2)132self.conv2 = nn.Conv2d(6, 16, 5)133self.fc1 = nn.Linear(16 * 5 * 5, 120)134self.fc2 = nn.Linear(120, 84)135self.fc3 = nn.Linear(84, 10)136137def forward(self, x):138x = self.pool(F.relu(self.conv1(x)))139x = self.pool(F.relu(self.conv2(x)))140x = torch.flatten(x, 1) # flatten all dimensions except batch141x = F.relu(self.fc1(x))142x = F.relu(self.fc2(x))143x = self.fc3(x)144return x145146147net = Net()148149########################################################################150# 3. Define a Loss function and optimizer151# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^152# Let's use a Classification Cross-Entropy loss and SGD with momentum.153154import torch.optim as optim155156criterion = nn.CrossEntropyLoss()157optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)158159########################################################################160# 4. Train the network161# ^^^^^^^^^^^^^^^^^^^^162#163# This is when things start to get interesting.164# We simply have to loop over our data iterator, and feed the inputs to the165# network and optimize.166167for epoch in range(2): # loop over the dataset multiple times168169running_loss = 0.0170for i, data in enumerate(trainloader, 0):171# get the inputs; data is a list of [inputs, labels]172inputs, labels = data173174# zero the parameter gradients175optimizer.zero_grad()176177# forward + backward + optimize178outputs = net(inputs)179loss = criterion(outputs, labels)180loss.backward()181optimizer.step()182183# print statistics184running_loss += loss.item()185if i % 2000 == 1999: # print every 2000 mini-batches186print(f'[{epoch + 1}, {i + 1:5d}] loss: {running_loss / 2000:.3f}')187running_loss = 0.0188189print('Finished Training')190191########################################################################192# Let's quickly save our trained model:193194PATH = './cifar_net.pt'195torch.save(net.state_dict(), PATH)196197########################################################################198# See `here <https://pytorch.org/docs/stable/notes/serialization.html>`_199# for more details on saving PyTorch models.200#201# 5. Test the network on the test data202# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^203#204# We have trained the network for 2 passes over the training dataset.205# But we need to check if the network has learnt anything at all.206#207# We will check this by predicting the class label that the neural network208# outputs, and checking it against the ground-truth. If the prediction is209# correct, we add the sample to the list of correct predictions.210#211# Okay, first step. Let us display an image from the test set to get familiar.212213dataiter = iter(testloader)214images, labels = next(dataiter)215216# print images217imshow(torchvision.utils.make_grid(images))218print('GroundTruth: ', ' '.join(f'{classes[labels[j]]:5s}' for j in range(4)))219220########################################################################221# Next, let's load back in our saved model (note: saving and re-loading the model222# wasn't necessary here, we only did it to illustrate how to do so):223224net = Net()225net.load_state_dict(torch.load(PATH, weights_only=True))226227########################################################################228# Okay, now let us see what the neural network thinks these examples above are:229230outputs = net(images)231232########################################################################233# The outputs are energies for the 10 classes.234# The higher the energy for a class, the more the network235# thinks that the image is of the particular class.236# So, let's get the index of the highest energy:237_, predicted = torch.max(outputs, 1)238239print('Predicted: ', ' '.join(f'{classes[predicted[j]]:5s}'240for j in range(4)))241242########################################################################243# The results seem pretty good.244#245# Let us look at how the network performs on the whole dataset.246247correct = 0248total = 0249# since we're not training, we don't need to calculate the gradients for our outputs250with torch.no_grad():251for data in testloader:252images, labels = data253# calculate outputs by running images through the network254outputs = net(images)255# the class with the highest energy is what we choose as prediction256_, predicted = torch.max(outputs, 1)257total += labels.size(0)258correct += (predicted == labels).sum().item()259260print(f'Accuracy of the network on the 10000 test images: {100 * correct // total} %')261262########################################################################263# That looks way better than chance, which is 10% accuracy (randomly picking264# a class out of 10 classes).265# Seems like the network learnt something.266#267# Hmmm, what are the classes that performed well, and the classes that did268# not perform well:269270# prepare to count predictions for each class271correct_pred = {classname: 0 for classname in classes}272total_pred = {classname: 0 for classname in classes}273274# again no gradients needed275with torch.no_grad():276for data in testloader:277images, labels = data278outputs = net(images)279_, predictions = torch.max(outputs, 1)280# collect the correct predictions for each class281for label, prediction in zip(labels, predictions):282if label == prediction:283correct_pred[classes[label]] += 1284total_pred[classes[label]] += 1285286287# print accuracy for each class288for classname, correct_count in correct_pred.items():289accuracy = 100 * float(correct_count) / total_pred[classname]290print(f'Accuracy for class: {classname:5s} is {accuracy:.1f} %')291292########################################################################293# Okay, so what next?294#295# How do we run these neural networks on the GPU?296#297# Training on GPU298# ----------------299# Just like how you transfer a Tensor onto the GPU, you transfer the neural300# net onto the GPU.301#302# Let's first define our device as the first visible cuda device if we have303# CUDA available:304305device = torch.device(torch.accelerator.current_accelerator().type if torch.accelerator.is_available() else 'cpu')306307# Assuming that we are on a CUDA machine, this should print a CUDA device:308309print(device)310311########################################################################312# The rest of this section assumes that ``device`` is a CUDA device.313#314# Then these methods will recursively go over all modules and convert their315# parameters and buffers to CUDA tensors:316#317# .. code:: python318#319# net.to(device)320#321#322# Remember that you will have to send the inputs and targets at every step323# to the GPU too:324#325# .. code:: python326#327# inputs, labels = data[0].to(device), data[1].to(device)328#329# Why don't I notice MASSIVE speedup compared to CPU? Because your network330# is really small.331#332# **Exercise:** Try increasing the width of your network (argument 2 of333# the first ``nn.Conv2d``, and argument 1 of the second ``nn.Conv2d`` –334# they need to be the same number), see what kind of speedup you get.335#336# **Goals achieved**:337#338# - Understanding PyTorch's Tensor library and neural networks at a high level.339# - Train a small neural network to classify images340#341# Training on multiple GPUs342# -------------------------343# If you want to see even more MASSIVE speedup using all of your GPUs,344# please check out :doc:`data_parallel_tutorial`.345#346# Where do I go next?347# -------------------348#349# - :doc:`Train neural nets to play video games </intermediate/reinforcement_q_learning>`350# - `Train a state-of-the-art ResNet network on imagenet`_351# - `Train a face generator using Generative Adversarial Networks`_352# - `Train a word-level language model using Recurrent LSTM networks`_353# - `More examples`_354# - `More tutorials`_355# - `Discuss PyTorch on the Forums`_356# - `Chat with other users on Slack`_357#358# .. _Train a state-of-the-art ResNet network on imagenet: https://github.com/pytorch/examples/tree/main/imagenet359# .. _Train a face generator using Generative Adversarial Networks: https://github.com/pytorch/examples/tree/main/dcgan360# .. _Train a word-level language model using Recurrent LSTM networks: https://github.com/pytorch/examples/tree/main/word_language_model361# .. _More examples: https://github.com/pytorch/examples362# .. _More tutorials: https://github.com/pytorch/tutorials363# .. _Discuss PyTorch on the Forums: https://discuss.pytorch.org/364# .. _Chat with other users on Slack: https://pytorch.slack.com/messages/beginner/365366# %%%%%%INVISIBLE_CODE_BLOCK%%%%%%367del dataiter368# %%%%%%INVISIBLE_CODE_BLOCK%%%%%%369370371