joxeankoret

Untitled

Dec 3rd, 2018
270
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 11.49 KB | None | 0 0
  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 normalizing the CIFAR10 training and test datasets using
  47.   ``torchvision``
  48. 2. Define a Convolution 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. Loading and normalizing 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. transform = transforms.Compose(
  67.     [transforms.ToTensor(),
  68.      transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
  69.  
  70. trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
  71.                                         download=True, transform=transform)
  72. trainloader = torch.utils.data.DataLoader(trainset, batch_size=4,
  73.                                           shuffle=True, num_workers=2)
  74.  
  75. testset = torchvision.datasets.CIFAR10(root='./data', train=False,
  76.                                        download=True, transform=transform)
  77. testloader = torch.utils.data.DataLoader(testset, batch_size=4,
  78.                                          shuffle=False, num_workers=2)
  79.  
  80. classes = ('plane', 'car', 'bird', 'cat',
  81.            'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
  82.  
  83. ########################################################################
  84. # Let us show some of the training images, for fun.
  85.  
  86. import matplotlib.pyplot as plt
  87. import numpy as np
  88.  
  89. # functions to show an image
  90.  
  91.  
  92. def imshow(img):
  93.     img = img / 2 + 0.5     # unnormalize
  94.     npimg = img.numpy()
  95.     plt.imshow(np.transpose(npimg, (1, 2, 0)))
  96.  
  97.  
  98. # get some random training images
  99. dataiter = iter(trainloader)
  100. images, labels = dataiter.next()
  101. print("IMAGES?", images, "LABELS?", labels)
  102. print("classes?", classes)
  103.  
  104. # show images
  105. imshow(torchvision.utils.make_grid(images))
  106. # print labels
  107. print(' '.join('%5s' % classes[labels[j]] for j in range(4)))
  108.  
  109.  
  110. ########################################################################
  111. # 2. Define a Convolution Neural Network
  112. # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  113. # Copy the neural network from the Neural Networks section before and modify it to
  114. # take 3-channel images (instead of 1-channel images as it was defined).
  115.  
  116. import torch.nn as nn
  117. import torch.nn.functional as F
  118.  
  119.  
  120. class Net(nn.Module):
  121.     def __init__(self):
  122.         super(Net, self).__init__()
  123.         self.conv1 = nn.Conv2d(3, 6, 5)
  124.         self.pool = nn.MaxPool2d(2, 2)
  125.         self.conv2 = nn.Conv2d(6, 16, 5)
  126.         self.fc1 = nn.Linear(16 * 5 * 5, 120)
  127.         self.fc2 = nn.Linear(120, 84)
  128.         self.fc3 = nn.Linear(84, 10)
  129.  
  130.     def forward(self, x):
  131.         x = self.pool(F.relu(self.conv1(x)))
  132.         x = self.pool(F.relu(self.conv2(x)))
  133.         x = x.view(-1, 16 * 5 * 5)
  134.         x = F.relu(self.fc1(x))
  135.         x = F.relu(self.fc2(x))
  136.         x = self.fc3(x)
  137.         return x
  138.  
  139.  
  140. net = Net()
  141.  
  142. ########################################################################
  143. # 3. Define a Loss function and optimizer
  144. # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  145. # Let's use a Classification Cross-Entropy loss and SGD with momentum.
  146.  
  147. import torch.optim as optim
  148.  
  149. criterion = nn.CrossEntropyLoss()
  150. optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
  151.  
  152. ########################################################################
  153. # 4. Train the network
  154. # ^^^^^^^^^^^^^^^^^^^^
  155. #
  156. # This is when things start to get interesting.
  157. # We simply have to loop over our data iterator, and feed the inputs to the
  158. # network and optimize.
  159.  
  160. for epoch in range(5):  # loop over the dataset multiple times
  161.     running_loss = 0.0
  162.     for i, data in enumerate(trainloader, 0):
  163.         # get the inputs
  164.         inputs, labels = data
  165.  
  166.         # zero the parameter gradients
  167.         optimizer.zero_grad()
  168.  
  169.         # forward + backward + optimize
  170.         outputs = net(inputs)
  171.         loss = criterion(outputs, labels)
  172.         loss.backward()
  173.         optimizer.step()
  174.  
  175.         # print statistics
  176.         running_loss += loss.item()
  177.         if i % 2000 == 1999:    # print every 2000 mini-batches
  178.             print('[%d, %5d] loss: %.3f' %
  179.                   (epoch + 1, i + 1, running_loss / 2000))
  180.             running_loss = 0.0
  181.  
  182. print('Finished Training')
  183.  
  184. ########################################################################
  185. # 5. Test the network on the test data
  186. # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  187. #
  188. # We have trained the network for 2 passes over the training dataset.
  189. # But we need to check if the network has learnt anything at all.
  190. #
  191. # We will check this by predicting the class label that the neural network
  192. # outputs, and checking it against the ground-truth. If the prediction is
  193. # correct, we add the sample to the list of correct predictions.
  194. #
  195. # Okay, first step. Let us display an image from the test set to get familiar.
  196.  
  197. dataiter = iter(testloader)
  198. images, labels = dataiter.next()
  199.  
  200. # print images
  201. imshow(torchvision.utils.make_grid(images))
  202. print('GroundTruth: ', ' '.join('%5s' % classes[labels[j]] for j in range(4)))
  203.  
  204. ########################################################################
  205. # Okay, now let us see what the neural network thinks these examples above are:
  206.  
  207. outputs = net(images)
  208.  
  209. ########################################################################
  210. # The outputs are energies for the 10 classes.
  211. # Higher the energy for a class, the more the network
  212. # thinks that the image is of the particular class.
  213. # So, let's get the index of the highest energy:
  214. _, predicted = torch.max(outputs, 1)
  215.  
  216. print('Predicted: ', ' '.join('%5s' % classes[predicted[j]]
  217.                               for j in range(4)))
  218.  
  219. ########################################################################
  220. # The results seem pretty good.
  221. #
  222. # Let us look at how the network performs on the whole dataset.
  223.  
  224. correct = 0
  225. total = 0
  226. with torch.no_grad():
  227.     for data in testloader:
  228.         images, labels = data
  229.         outputs = net(images)
  230.         _, predicted = torch.max(outputs.data, 1)
  231.         total += labels.size(0)
  232.         correct += (predicted == labels).sum().item()
  233.  
  234. print('Accuracy of the network on the 10000 test images: %d %%' % (
  235.     100 * correct / total))
  236.  
  237. ########################################################################
  238. # That looks waaay better than chance, which is 10% accuracy (randomly picking
  239. # a class out of 10 classes).
  240. # Seems like the network learnt something.
  241. #
  242. # Hmmm, what are the classes that performed well, and the classes that did
  243. # not perform well:
  244.  
  245. class_correct = list(0. for i in range(10))
  246. class_total = list(0. for i in range(10))
  247. with torch.no_grad():
  248.     for data in testloader:
  249.         images, labels = data
  250.         outputs = net(images)
  251.         _, predicted = torch.max(outputs, 1)
  252.         c = (predicted == labels).squeeze()
  253.         for i in range(4):
  254.             label = labels[i]
  255.             class_correct[label] += c[i].item()
  256.             class_total[label] += 1
  257.  
  258.  
  259. for i in range(10):
  260.     print('Accuracy of %5s : %2d %%' % (
  261.         classes[i], 100 * class_correct[i] / class_total[i]))
  262.  
  263. ########################################################################
  264. # Okay, so what next?
  265. #
  266. # How do we run these neural networks on the GPU?
  267. #
  268. # Training on GPU
  269. # ----------------
  270. # Just like how you transfer a Tensor on to the GPU, you transfer the neural
  271. # net onto the GPU.
  272. #
  273. # Let's first define our device as the first visible cuda device if we have
  274. # CUDA available:
  275.  
  276. device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
  277.  
  278. # Assume that we are on a CUDA machine, then this should print a CUDA device:
  279.  
  280. print(device)
  281.  
  282. ########################################################################
  283. # The rest of this section assumes that `device` is a CUDA device.
  284. #
  285. # Then these methods will recursively go over all modules and convert their
  286. # parameters and buffers to CUDA tensors:
  287. #
  288. # .. code:: python
  289. #
  290. #     net.to(device)
  291. #
  292. #
  293. # Remember that you will have to send the inputs and targets at every step
  294. # to the GPU too:
  295. #
  296. # .. code:: python
  297. #
  298. #         inputs, labels = inputs.to(device), labels.to(device)
  299. #
  300. # Why dont I notice MASSIVE speedup compared to CPU? Because your network
  301. # is realllly small.
  302. #
  303. # **Exercise:** Try increasing the width of your network (argument 2 of
  304. # the first ``nn.Conv2d``, and argument 1 of the second ``nn.Conv2d`` –
  305. # they need to be the same number), see what kind of speedup you get.
  306. #
  307. # **Goals achieved**:
  308. #
  309. # - Understanding PyTorch's Tensor library and neural networks at a high level.
  310. # - Train a small neural network to classify images
  311. #
  312. # Training on multiple GPUs
  313. # -------------------------
  314. # If you want to see even more MASSIVE speedup using all of your GPUs,
  315. # please check out :doc:`data_parallel_tutorial`.
  316. #
  317. # Where do I go next?
  318. # -------------------
  319. #
  320. # -  :doc:`Train neural nets to play video games </intermediate/reinforcement_q_learning>`
  321. # -  `Train a state-of-the-art ResNet network on imagenet`_
  322. # -  `Train a face generator using Generative Adversarial Networks`_
  323. # -  `Train a word-level language model using Recurrent LSTM networks`_
  324. # -  `More examples`_
  325. # -  `More tutorials`_
  326. # -  `Discuss PyTorch on the Forums`_
  327. # -  `Chat with other users on Slack`_
  328. #
  329. # .. _Train a state-of-the-art ResNet network on imagenet: https://github.com/pytorch/examples/tree/master/imagenet
  330. # .. _Train a face generator using Generative Adversarial Networks: https://github.com/pytorch/examples/tree/master/dcgan
  331. # .. _Train a word-level language model using Recurrent LSTM networks: https://github.com/pytorch/examples/tree/master/word_language_model
  332. # .. _More examples: https://github.com/pytorch/examples
  333. # .. _More tutorials: https://github.com/pytorch/tutorials
  334. # .. _Discuss PyTorch on the Forums: https://discuss.pytorch.org/
  335. # .. _Chat with other users on Slack: https://pytorch.slack.com/messages/beginner/
Advertisement
Add Comment
Please, Sign In to add comment