Advertisement
Guest User

Untitled

a guest
Dec 9th, 2019
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.99 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. """SoftwareAIModel.ipynb
  3.  
  4. Automatically generated by Colaboratory.
  5.  
  6. Original file is located at
  7.    https://colab.research.google.com/drive/1sZUoUsKe8w5H25w5D2pfuSNQ6AcDvbbr
  8.  
  9. #Importing needed modules
  10. """
  11.  
  12. import torch
  13. import torchvision
  14. from torchvision import transforms, datasets
  15. import torch.nn as nn
  16. import torch.nn.functional as F
  17.  
  18. """#Creating Data Sets"""
  19.  
  20. # Batching Data for training and Testing
  21. train = datasets.MNIST('', train=True, download=True,
  22.                        transform=transforms.Compose([
  23.                            transforms.ToTensor()
  24.                        ]))
  25.  
  26. test = datasets.MNIST('', train=False, download=True,
  27.                        transform=transforms.Compose([
  28.                            transforms.ToTensor()
  29.                        ]))
  30.  
  31.  
  32. trainset = torch.utils.data.DataLoader(train, batch_size=10, shuffle=True)
  33. testset = torch.utils.data.DataLoader(test, batch_size=10, shuffle=False)
  34.  
  35. """#Creating actual AI learning Algorithm"""
  36.  
  37. # Training Class
  38. class Net(nn.Module):
  39.     def __init__(self):
  40.         super().__init__()
  41.         self.fc1 = nn.Linear(28*28, 64)
  42.         self.fc2 = nn.Linear(64, 64)
  43.         self.fc3 = nn.Linear(64, 64)
  44.         self.fc4 = nn.Linear(64, 10)
  45.  
  46.     def forward(self, x):
  47.         x = F.relu(self.fc1(x))
  48.         x = F.relu(self.fc2(x))
  49.         x = F.relu(self.fc3(x))
  50.         x = self.fc4(x)
  51.         return F.log_softmax(x, dim=1)
  52.  
  53. net = Net()
  54. print(net)
  55.  
  56. """# Optimiser"""
  57.  
  58. # Creating Optimiser Function
  59. import torch.optim as optim
  60.  
  61. loss_function = nn.CrossEntropyLoss()
  62. optimiser = optim.Adam(net.parameters(), lr=0.001)
  63. accploss = 5*(10**(-5)) #add acceptable loss amount here
  64.  
  65. """# Model Training"""
  66.  
  67. #Choose device for training
  68. if torch.cuda.is_available:
  69.     device = torch.device("cuda:0")
  70.     print("Running on GPU")
  71. else:
  72.     device = torch.device("cpu")
  73.     print("running on CPU")
  74.  
  75. net.to(device)
  76. net = Net().to(device)
  77.  
  78. for epoch in range(50): # n number of full passes over the data
  79.     for data in trainset:  # `data` is a batch of data
  80.         X, y = data  # X is the batch of features, y is the batch of targets.
  81.         X, y = X.to(device), y.to(device)
  82.         net.zero_grad()  # sets gradients to 0 before loss calc. You will do this likely every step.
  83.         output = net(X.view(-1,784))  # pass in the reshaped batch (recall they are 28x28 atm)
  84.         loss = F.nll_loss(output, y)  # calc and grab the loss value
  85.         loss.backward()  # apply this loss backwards through the network's parameters
  86.         optimiser.step()  # attempt to optimize weights to account for loss/gradients
  87.     print(loss)  # print loss
  88.     losslist.append(loss.item())
  89.     if loss < (1*(10**-5)):
  90.         break
  91.  
  92. """# Model Testing"""
  93.  
  94. # Testing model
  95.  
  96. correct = 0
  97. total = 0
  98.  
  99. X, y=  X.to(device), y.to(device)
  100.  
  101. with torch.no_grad():
  102.     for data in testset:
  103.         X, y = data
  104.         output = net(X.view(-1,784).to(device))
  105.         #print(output) # commented out, use for debugging
  106.         for idx, i in enumerate(output):
  107.             #print(torch.argmax(i), y[idx]) # commented out, use for debugging
  108.             if torch.argmax(i) == y[idx]:
  109.                 correct += 1
  110.             total += 1
  111.  
  112. print("Accuracy: ", round(correct/total, 3))
  113.  
  114. import matplotlib.pyplot as plt
  115.  
  116. plt.imshow(X[9].view(28,28))
  117. plt.show()
  118.  
  119. a_featureset = X[0]
  120. reshaped_for_network = a_featureset.view(-1,784) # 784 because 28*28 image resolution.
  121. output = net(reshaped_for_network.to(device)) #output will be a list of network predictions.
  122. first_pred = output[0]
  123. print(first_pred)
  124.  
  125. #Which index value is the greatest? We use 'argmax' to find this:
  126.  
  127. biggest_index = torch.argmax(first_pred)
  128. print(biggest_index)
  129.  
  130. #Code below is explained above
  131.  
  132. #print(torch.argmax(net(X[9].view(-1,784))[0]))
  133.  
  134. """The model gives acceptable results, therefore it is a reasonable idea to export it so we can have a model that can be implemented into the webcam number detection algorithm."""
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement