Advertisement
Guest User

Untitled

a guest
Dec 11th, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. import torch
  2. from torch.autograd import Variable
  3. import torch.nn as nn
  4. import torch.nn.functional as F
  5. import torch.optim as optim
  6.  
  7. EPOCHS_TO_TRAIN = 5000
  8.  
  9. class Net(nn.Module):
  10.  
  11. def __init__(self):
  12. super(Net, self).__init__()
  13. self.fc1 = nn.Linear(2, 3, True)
  14. self.fc2 = nn.Linear(3, 1, True)
  15.  
  16. def forward(self, x):
  17. x = torch.sigmoid(self.fc1(x))
  18. x = self.fc2(x)
  19. return x
  20.  
  21. net = Net()
  22. inputs = list(map(lambda s: Variable(torch.Tensor([s])), [
  23. [0, 0],
  24. [0, 1],
  25. [1, 0],
  26. [1, 1]
  27. ]))
  28. targets = list(map(lambda s: Variable(torch.Tensor([s])), [
  29. [0],
  30. [1],
  31. [1],
  32. [0]
  33. ]))
  34.  
  35.  
  36. criterion = nn.MSELoss()
  37. optimizer = optim.SGD(net.parameters(), lr=0.1)
  38.  
  39. print("Training loop:")
  40. for idx in range(0, EPOCHS_TO_TRAIN):
  41. for input, target in zip(inputs, targets):
  42. optimizer.zero_grad() # zero the gradient buffers
  43. output = net(input)
  44. loss = criterion(output, target)
  45. loss.backward()
  46. optimizer.step() # Does the update
  47. if idx % 100 == 0:
  48. print("Epoch {: >8} Loss: {}".format(idx, loss.data.numpy()))
  49.  
  50.  
  51.  
  52. print("")
  53. print("Final results:")
  54. for input, target in zip(inputs, targets):
  55. output = net(input)
  56. print("Input:[{},{}] Target:[{}] Predicted:[{}] Error:[{}]".format(
  57. int(input.data.numpy()[0][0]),
  58. int(input.data.numpy()[0][1]),
  59. int(target.data.numpy()[0]),
  60. round(float(output.data.numpy()[0]), 4),
  61. round(float(abs(target.data.numpy()[0] - output.data.numpy()[0])), 4)
  62. ))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement