Naresh617 commited on
Commit
8c8d8bb
·
1 Parent(s): edbf23a

Delete task_day11.py

Browse files
Files changed (1) hide show
  1. task_day11.py +0 -468
task_day11.py DELETED
@@ -1,468 +0,0 @@
1
- #!/usr/bin/env python
2
- # coding: utf-8
3
-
4
- # In[ ]:
5
-
6
-
7
- # For tips on running notebooks in Google Colab, see
8
- # https://pytorch.org/tutorials/beginner/colab
9
- get_ipython().run_line_magic('matplotlib', 'inline')
10
-
11
-
12
- #
13
- # # Training a Classifier
14
- #
15
- # This is it. You have seen how to define neural networks, compute loss and make
16
- # updates to the weights of the network.
17
- #
18
- # Now you might be thinking,
19
- #
20
- # ## What about data?
21
- #
22
- # Generally, when you have to deal with image, text, audio or video data,
23
- # you can use standard python packages that load data into a numpy array.
24
- # Then you can convert this array into a ``torch.*Tensor``.
25
- #
26
- # - For images, packages such as Pillow, OpenCV are useful
27
- # - For audio, packages such as scipy and librosa
28
- # - For text, either raw Python or Cython based loading, or NLTK and
29
- # SpaCy are useful
30
- #
31
- # Specifically for vision, we have created a package called
32
- # ``torchvision``, that has data loaders for common datasets such as
33
- # ImageNet, CIFAR10, MNIST, etc. and data transformers for images, viz.,
34
- # ``torchvision.datasets`` and ``torch.utils.data.DataLoader``.
35
- #
36
- # This provides a huge convenience and avoids writing boilerplate code.
37
- #
38
- # For this tutorial, we will use the CIFAR10 dataset.
39
- # It has the classes: ‘airplane’, ‘automobile’, ‘bird’, ‘cat’, ‘deer’,
40
- # ‘dog’, ‘frog’, ‘horse’, ‘ship’, ‘truck’. The images in CIFAR-10 are of
41
- # size 3x32x32, i.e. 3-channel color images of 32x32 pixels in size.
42
- #
43
- # .. figure:: /_static/img/cifar10.png
44
- # :alt: cifar10
45
- #
46
- # cifar10
47
- #
48
- #
49
- # ## Training an image classifier
50
- #
51
- # We will do the following steps in order:
52
- #
53
- # 1. Load and normalize the CIFAR10 training and test datasets using
54
- # ``torchvision``
55
- # 2. Define a Convolutional Neural Network
56
- # 3. Define a loss function
57
- # 4. Train the network on the training data
58
- # 5. Test the network on the test data
59
- #
60
- # ### 1. Load and normalize CIFAR10
61
- #
62
- # Using ``torchvision``, it’s extremely easy to load CIFAR10.
63
- #
64
-
65
- # In[1]:
66
-
67
-
68
- import torch
69
- import torchvision
70
- import torchvision.transforms as transforms
71
-
72
-
73
- # The output of torchvision datasets are PILImage images of range [0, 1].
74
- # We transform them to Tensors of normalized range [-1, 1].
75
- #
76
- #
77
-
78
- # <div class="alert alert-info"><h4>Note</h4><p>If running on Windows and you get a BrokenPipeError, try setting
79
- # the num_worker of torch.utils.data.DataLoader() to 0.</p></div>
80
- #
81
- #
82
-
83
- # In[2]:
84
-
85
-
86
- transform = transforms.Compose(
87
- [transforms.ToTensor(),
88
- transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
89
-
90
- batch_size = 4
91
-
92
- trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
93
- download=True, transform=transform)
94
- trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size,
95
- shuffle=True, num_workers=2)
96
-
97
- testset = torchvision.datasets.CIFAR10(root='./data', train=False,
98
- download=True, transform=transform)
99
- testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size,
100
- shuffle=False, num_workers=2)
101
-
102
- classes = ('plane', 'car', 'bird', 'cat',
103
- 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
104
-
105
-
106
- # Let us show some of the training images, for fun.
107
- #
108
- #
109
-
110
- # In[3]:
111
-
112
-
113
- import matplotlib.pyplot as plt
114
- import numpy as np
115
-
116
- # functions to show an image
117
-
118
-
119
- def imshow(img):
120
- img = img / 2 + 0.5 # unnormalize
121
- npimg = img.numpy()
122
- plt.imshow(np.transpose(npimg, (1, 2, 0)))
123
- plt.show()
124
-
125
-
126
- # get some random training images
127
- dataiter = iter(trainloader)
128
- images, labels = next(dataiter)
129
-
130
- # show images
131
- imshow(torchvision.utils.make_grid(images))
132
- # print labels
133
- print(' '.join(f'{classes[labels[j]]:5s}' for j in range(batch_size)))
134
-
135
-
136
- # ### 2. Define a Convolutional Neural Network
137
- # Copy the neural network from the Neural Networks section before and modify it to
138
- # take 3-channel images (instead of 1-channel images as it was defined).
139
- #
140
- #
141
-
142
- # In[4]:
143
-
144
-
145
- import torch.nn as nn
146
- import torch.nn.functional as F
147
-
148
-
149
- class Net(nn.Module):
150
- def __init__(self):
151
- super().__init__()
152
- self.conv1 = nn.Conv2d(3, 6, 5)
153
- self.pool = nn.MaxPool2d(2, 2)
154
- self.conv2 = nn.Conv2d(6, 16, 5)
155
- self.fc1 = nn.Linear(16 * 5 * 5, 120)
156
- self.fc2 = nn.Linear(120, 84)
157
- self.fc3 = nn.Linear(84, 10)
158
-
159
- def forward(self, x):
160
- x = self.pool(F.relu(self.conv1(x)))
161
- x = self.pool(F.relu(self.conv2(x)))
162
- x = torch.flatten(x, 1) # flatten all dimensions except batch
163
- x = F.relu(self.fc1(x))
164
- x = F.relu(self.fc2(x))
165
- x = self.fc3(x)
166
- return x
167
-
168
-
169
- net = Net()
170
-
171
-
172
- # ### 3. Define a Loss function and optimizer
173
- # Let's use a Classification Cross-Entropy loss and SGD with momentum.
174
- #
175
- #
176
-
177
- # In[5]:
178
-
179
-
180
- import torch.optim as optim
181
-
182
- criterion = nn.CrossEntropyLoss()
183
- optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
184
-
185
-
186
- # ### 4. Train the network
187
- #
188
- # This is when things start to get interesting.
189
- # We simply have to loop over our data iterator, and feed the inputs to the
190
- # network and optimize.
191
- #
192
- #
193
-
194
- # In[6]:
195
-
196
-
197
- for epoch in range(2): # loop over the dataset multiple times
198
-
199
- running_loss = 0.0
200
- for i, data in enumerate(trainloader, 0):
201
- # get the inputs; data is a list of [inputs, labels]
202
- inputs, labels = data
203
-
204
- # zero the parameter gradients
205
- optimizer.zero_grad()
206
-
207
- # forward + backward + optimize
208
- outputs = net(inputs)
209
- loss = criterion(outputs, labels)
210
- loss.backward()
211
- optimizer.step()
212
-
213
- # print statistics
214
- running_loss += loss.item()
215
- if i % 2000 == 1999: # print every 2000 mini-batches
216
- print(f'[{epoch + 1}, {i + 1:5d}] loss: {running_loss / 2000:.3f}')
217
- running_loss = 0.0
218
-
219
- print('Finished Training')
220
-
221
-
222
- # Let's quickly save our trained model:
223
- #
224
- #
225
-
226
- # In[7]:
227
-
228
-
229
- PATH = './cifar_net.pth'
230
- torch.save(net.state_dict(), PATH)
231
-
232
-
233
- # See [here](https://pytorch.org/docs/stable/notes/serialization.html)
234
- # for more details on saving PyTorch models.
235
- #
236
- # ### 5. Test the network on the test data
237
- #
238
- # We have trained the network for 2 passes over the training dataset.
239
- # But we need to check if the network has learnt anything at all.
240
- #
241
- # We will check this by predicting the class label that the neural network
242
- # outputs, and checking it against the ground-truth. If the prediction is
243
- # correct, we add the sample to the list of correct predictions.
244
- #
245
- # Okay, first step. Let us display an image from the test set to get familiar.
246
- #
247
- #
248
-
249
- # In[8]:
250
-
251
-
252
- dataiter = iter(testloader)
253
- images, labels = next(dataiter)
254
-
255
- # print images
256
- imshow(torchvision.utils.make_grid(images))
257
- print('GroundTruth: ', ' '.join(f'{classes[labels[j]]:5s}' for j in range(4)))
258
-
259
-
260
- # Next, let's load back in our saved model (note: saving and re-loading the model
261
- # wasn't necessary here, we only did it to illustrate how to do so):
262
- #
263
- #
264
-
265
- # In[9]:
266
-
267
-
268
- net = Net()
269
- net.load_state_dict(torch.load(PATH))
270
-
271
-
272
- # Okay, now let us see what the neural network thinks these examples above are:
273
- #
274
- #
275
-
276
- # In[10]:
277
-
278
-
279
- outputs = net(images)
280
-
281
-
282
- # The outputs are energies for the 10 classes.
283
- # The higher the energy for a class, the more the network
284
- # thinks that the image is of the particular class.
285
- # So, let's get the index of the highest energy:
286
- #
287
- #
288
-
289
- # In[11]:
290
-
291
-
292
- _, predicted = torch.max(outputs, 1)
293
-
294
- print('Predicted: ', ' '.join(f'{classes[predicted[j]]:5s}'
295
- for j in range(4)))
296
-
297
-
298
- # The results seem pretty good.
299
- #
300
- # Let us look at how the network performs on the whole dataset.
301
- #
302
- #
303
-
304
- # In[12]:
305
-
306
-
307
- correct = 0
308
- total = 0
309
- # since we're not training, we don't need to calculate the gradients for our outputs
310
- with torch.no_grad():
311
- for data in testloader:
312
- images, labels = data
313
- # calculate outputs by running images through the network
314
- outputs = net(images)
315
- # the class with the highest energy is what we choose as prediction
316
- _, predicted = torch.max(outputs.data, 1)
317
- total += labels.size(0)
318
- correct += (predicted == labels).sum().item()
319
-
320
- print(f'Accuracy of the network on the 10000 test images: {100 * correct // total} %')
321
-
322
-
323
- # That looks way better than chance, which is 10% accuracy (randomly picking
324
- # a class out of 10 classes).
325
- # Seems like the network learnt something.
326
- #
327
- # Hmmm, what are the classes that performed well, and the classes that did
328
- # not perform well:
329
- #
330
- #
331
-
332
- # In[13]:
333
-
334
-
335
- # prepare to count predictions for each class
336
- correct_pred = {classname: 0 for classname in classes}
337
- total_pred = {classname: 0 for classname in classes}
338
-
339
- # again no gradients needed
340
- with torch.no_grad():
341
- for data in testloader:
342
- images, labels = data
343
- outputs = net(images)
344
- _, predictions = torch.max(outputs, 1)
345
- # collect the correct predictions for each class
346
- for label, prediction in zip(labels, predictions):
347
- if label == prediction:
348
- correct_pred[classes[label]] += 1
349
- total_pred[classes[label]] += 1
350
-
351
-
352
- # print accuracy for each class
353
- for classname, correct_count in correct_pred.items():
354
- accuracy = 100 * float(correct_count) / total_pred[classname]
355
- print(f'Accuracy for class: {classname:5s} is {accuracy:.1f} %')
356
-
357
-
358
- # Okay, so what next?
359
- #
360
- # How do we run these neural networks on the GPU?
361
- #
362
- # ## Training on GPU
363
- # Just like how you transfer a Tensor onto the GPU, you transfer the neural
364
- # net onto the GPU.
365
- #
366
- # Let's first define our device as the first visible cuda device if we have
367
- # CUDA available:
368
- #
369
- #
370
-
371
- # In[14]:
372
-
373
-
374
- device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
375
-
376
- # Assuming that we are on a CUDA machine, this should print a CUDA device:
377
-
378
- print(device)
379
-
380
-
381
- # In[ ]:
382
-
383
-
384
-
385
-
386
-
387
- # The rest of this section assumes that ``device`` is a CUDA device.
388
- #
389
- # Then these methods will recursively go over all modules and convert their
390
- # parameters and buffers to CUDA tensors:
391
- #
392
- # .. code:: python
393
- #
394
- # net.to(device)
395
- #
396
- #
397
- # Remember that you will have to send the inputs and targets at every step
398
- # to the GPU too:
399
- #
400
- # .. code:: python
401
- #
402
- # inputs, labels = data[0].to(device), data[1].to(device)
403
- #
404
- # Why don't I notice MASSIVE speedup compared to CPU? Because your network
405
- # is really small.
406
- #
407
- # **Exercise:** Try increasing the width of your network (argument 2 of
408
- # the first ``nn.Conv2d``, and argument 1 of the second ``nn.Conv2d`` –
409
- # they need to be the same number), see what kind of speedup you get.
410
- #
411
- # **Goals achieved**:
412
- #
413
- # - Understanding PyTorch's Tensor library and neural networks at a high level.
414
- # - Train a small neural network to classify images
415
- #
416
- # ## Training on multiple GPUs
417
- # If you want to see even more MASSIVE speedup using all of your GPUs,
418
- # please check out :doc:`data_parallel_tutorial`.
419
- #
420
- # ## Where do I go next?
421
- #
422
- # - :doc:`Train neural nets to play video games </intermediate/reinforcement_q_learning>`
423
- # - `Train a state-of-the-art ResNet network on imagenet`_
424
- # - `Train a face generator using Generative Adversarial Networks`_
425
- # - `Train a word-level language model using Recurrent LSTM networks`_
426
- # - `More examples`_
427
- # - `More tutorials`_
428
- # - `Discuss PyTorch on the Forums`_
429
- # - `Chat with other users on Slack`_
430
- #
431
- #
432
- #
433
-
434
- # In[ ]:
435
-
436
-
437
- del dataiter
438
-
439
-
440
- # In[ ]:
441
-
442
-
443
-
444
-
445
-
446
- # In[ ]:
447
-
448
-
449
-
450
-
451
-
452
- # In[ ]:
453
-
454
-
455
-
456
-
457
-
458
- # In[ ]:
459
-
460
-
461
-
462
-
463
-
464
- # In[ ]:
465
-
466
-
467
-
468
-