Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pytorch
GitHub Repository: pytorch/tutorials
Path: blob/main/beginner_source/blitz/cifar10_tutorial.py
2095 views
1
# -*- coding: utf-8 -*-
2
"""
3
Training a Classifier
4
=====================
5
6
This is it. You have seen how to define neural networks, compute loss and make
7
updates to the weights of the network.
8
9
Now you might be thinking,
10
11
What about data?
12
----------------
13
14
Generally, when you have to deal with image, text, audio or video data,
15
you can use standard python packages that load data into a numpy array.
16
Then you can convert this array into a ``torch.*Tensor``.
17
18
- For images, packages such as Pillow, OpenCV are useful
19
- For audio, packages such as scipy and librosa
20
- For text, either raw Python or Cython based loading, or NLTK and
21
SpaCy are useful
22
23
Specifically for vision, we have created a package called
24
``torchvision``, that has data loaders for common datasets such as
25
ImageNet, CIFAR10, MNIST, etc. and data transformers for images, viz.,
26
``torchvision.datasets`` and ``torch.utils.data.DataLoader``.
27
28
This provides a huge convenience and avoids writing boilerplate code.
29
30
For this tutorial, we will use the CIFAR10 dataset.
31
It has the classes: ‘airplane’, ‘automobile’, ‘bird’, ‘cat’, ‘deer’,
32
‘dog’, ‘frog’, ‘horse’, ‘ship’, ‘truck’. The images in CIFAR-10 are of
33
size 3x32x32, i.e. 3-channel color images of 32x32 pixels in size.
34
35
.. figure:: /_static/img/cifar10.png
36
:alt: cifar10
37
38
cifar10
39
40
41
Training an image classifier
42
----------------------------
43
44
We will do the following steps in order:
45
46
1. Load and normalize the CIFAR10 training and test datasets using
47
``torchvision``
48
2. Define a Convolutional Neural Network
49
3. Define a loss function
50
4. Train the network on the training data
51
5. Test the network on the test data
52
53
1. Load and normalize CIFAR10
54
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
55
56
Using ``torchvision``, it’s extremely easy to load CIFAR10.
57
"""
58
import torch
59
import torchvision
60
import torchvision.transforms as transforms
61
62
########################################################################
63
# The output of torchvision datasets are PILImage images of range [0, 1].
64
# We transform them to Tensors of normalized range [-1, 1].
65
66
########################################################################
67
# .. note::
68
# If you are running this tutorial on Windows or MacOS and encounter a
69
# BrokenPipeError or RuntimeError related to multiprocessing, try setting
70
# the num_worker of torch.utils.data.DataLoader() to 0.
71
72
transform = transforms.Compose(
73
[transforms.ToTensor(),
74
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
75
76
batch_size = 4
77
78
trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
79
download=True, transform=transform)
80
trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size,
81
shuffle=True, num_workers=2)
82
83
testset = torchvision.datasets.CIFAR10(root='./data', train=False,
84
download=True, transform=transform)
85
testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size,
86
shuffle=False, num_workers=2)
87
88
classes = ('plane', 'car', 'bird', 'cat',
89
'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
90
91
########################################################################
92
# Let us show some of the training images, for fun.
93
94
import matplotlib.pyplot as plt
95
import numpy as np
96
97
# functions to show an image
98
99
100
def imshow(img):
101
img = img / 2 + 0.5 # unnormalize
102
npimg = img.numpy()
103
plt.imshow(np.transpose(npimg, (1, 2, 0)))
104
plt.show()
105
106
107
# get some random training images
108
dataiter = iter(trainloader)
109
images, labels = next(dataiter)
110
111
# show images
112
imshow(torchvision.utils.make_grid(images))
113
# print labels
114
print(' '.join(f'{classes[labels[j]]:5s}' for j in range(batch_size)))
115
116
117
########################################################################
118
# 2. Define a Convolutional Neural Network
119
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
120
# Copy the neural network from the Neural Networks section before and modify it to
121
# take 3-channel images (instead of 1-channel images as it was defined).
122
123
import torch.nn as nn
124
import torch.nn.functional as F
125
126
127
class Net(nn.Module):
128
def __init__(self):
129
super().__init__()
130
self.conv1 = nn.Conv2d(3, 6, 5)
131
self.pool = nn.MaxPool2d(2, 2)
132
self.conv2 = nn.Conv2d(6, 16, 5)
133
self.fc1 = nn.Linear(16 * 5 * 5, 120)
134
self.fc2 = nn.Linear(120, 84)
135
self.fc3 = nn.Linear(84, 10)
136
137
def forward(self, x):
138
x = self.pool(F.relu(self.conv1(x)))
139
x = self.pool(F.relu(self.conv2(x)))
140
x = torch.flatten(x, 1) # flatten all dimensions except batch
141
x = F.relu(self.fc1(x))
142
x = F.relu(self.fc2(x))
143
x = self.fc3(x)
144
return x
145
146
147
net = Net()
148
149
########################################################################
150
# 3. Define a Loss function and optimizer
151
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
152
# Let's use a Classification Cross-Entropy loss and SGD with momentum.
153
154
import torch.optim as optim
155
156
criterion = nn.CrossEntropyLoss()
157
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
158
159
########################################################################
160
# 4. Train the network
161
# ^^^^^^^^^^^^^^^^^^^^
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 the
165
# network and optimize.
166
167
for epoch in range(2): # loop over the dataset multiple times
168
169
running_loss = 0.0
170
for i, data in enumerate(trainloader, 0):
171
# get the inputs; data is a list of [inputs, labels]
172
inputs, labels = data
173
174
# zero the parameter gradients
175
optimizer.zero_grad()
176
177
# forward + backward + optimize
178
outputs = net(inputs)
179
loss = criterion(outputs, labels)
180
loss.backward()
181
optimizer.step()
182
183
# print statistics
184
running_loss += loss.item()
185
if i % 2000 == 1999: # print every 2000 mini-batches
186
print(f'[{epoch + 1}, {i + 1:5d}] loss: {running_loss / 2000:.3f}')
187
running_loss = 0.0
188
189
print('Finished Training')
190
191
########################################################################
192
# Let's quickly save our trained model:
193
194
PATH = './cifar_net.pth'
195
torch.save(net.state_dict(), PATH)
196
197
########################################################################
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 data
202
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
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 network
208
# outputs, and checking it against the ground-truth. If the prediction is
209
# 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.
212
213
dataiter = iter(testloader)
214
images, labels = next(dataiter)
215
216
# print images
217
imshow(torchvision.utils.make_grid(images))
218
print('GroundTruth: ', ' '.join(f'{classes[labels[j]]:5s}' for j in range(4)))
219
220
########################################################################
221
# Next, let's load back in our saved model (note: saving and re-loading the model
222
# wasn't necessary here, we only did it to illustrate how to do so):
223
224
net = Net()
225
net.load_state_dict(torch.load(PATH, weights_only=True))
226
227
########################################################################
228
# Okay, now let us see what the neural network thinks these examples above are:
229
230
outputs = net(images)
231
232
########################################################################
233
# The outputs are energies for the 10 classes.
234
# The higher the energy for a class, the more the network
235
# 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)
238
239
print('Predicted: ', ' '.join(f'{classes[predicted[j]]:5s}'
240
for j in range(4)))
241
242
########################################################################
243
# The results seem pretty good.
244
#
245
# Let us look at how the network performs on the whole dataset.
246
247
correct = 0
248
total = 0
249
# since we're not training, we don't need to calculate the gradients for our outputs
250
with torch.no_grad():
251
for data in testloader:
252
images, labels = data
253
# calculate outputs by running images through the network
254
outputs = net(images)
255
# the class with the highest energy is what we choose as prediction
256
_, predicted = torch.max(outputs, 1)
257
total += labels.size(0)
258
correct += (predicted == labels).sum().item()
259
260
print(f'Accuracy of the network on the 10000 test images: {100 * correct // total} %')
261
262
########################################################################
263
# That looks way better than chance, which is 10% accuracy (randomly picking
264
# 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 did
268
# not perform well:
269
270
# prepare to count predictions for each class
271
correct_pred = {classname: 0 for classname in classes}
272
total_pred = {classname: 0 for classname in classes}
273
274
# again no gradients needed
275
with torch.no_grad():
276
for data in testloader:
277
images, labels = data
278
outputs = net(images)
279
_, predictions = torch.max(outputs, 1)
280
# collect the correct predictions for each class
281
for label, prediction in zip(labels, predictions):
282
if label == prediction:
283
correct_pred[classes[label]] += 1
284
total_pred[classes[label]] += 1
285
286
287
# print accuracy for each class
288
for classname, correct_count in correct_pred.items():
289
accuracy = 100 * float(correct_count) / total_pred[classname]
290
print(f'Accuracy for class: {classname:5s} is {accuracy:.1f} %')
291
292
########################################################################
293
# Okay, so what next?
294
#
295
# How do we run these neural networks on the GPU?
296
#
297
# Training on GPU
298
# ----------------
299
# Just like how you transfer a Tensor onto the GPU, you transfer the neural
300
# net onto the GPU.
301
#
302
# Let's first define our device as the first visible cuda device if we have
303
# CUDA available:
304
305
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
306
307
# Assuming that we are on a CUDA machine, this should print a CUDA device:
308
309
print(device)
310
311
########################################################################
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 their
315
# parameters and buffers to CUDA tensors:
316
#
317
# .. code:: python
318
#
319
# net.to(device)
320
#
321
#
322
# Remember that you will have to send the inputs and targets at every step
323
# to the GPU too:
324
#
325
# .. code:: python
326
#
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 network
330
# is really small.
331
#
332
# **Exercise:** Try increasing the width of your network (argument 2 of
333
# 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 images
340
#
341
# Training on multiple GPUs
342
# -------------------------
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/master/imagenet
359
# .. _Train a face generator using Generative Adversarial Networks: https://github.com/pytorch/examples/tree/master/dcgan
360
# .. _Train a word-level language model using Recurrent LSTM networks: https://github.com/pytorch/examples/tree/master/word_language_model
361
# .. _More examples: https://github.com/pytorch/examples
362
# .. _More tutorials: https://github.com/pytorch/tutorials
363
# .. _Discuss PyTorch on the Forums: https://discuss.pytorch.org/
364
# .. _Chat with other users on Slack: https://pytorch.slack.com/messages/beginner/
365
366
# %%%%%%INVISIBLE_CODE_BLOCK%%%%%%
367
del dataiter
368
# %%%%%%INVISIBLE_CODE_BLOCK%%%%%%
369
370