Advertisement
Guest User

Untitled

a guest
Jun 27th, 2019
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. # TODO: Define your network architecture here
  2. import torch
  3. from torch import nn
  4. from torch import optim
  5. from torchvision import datasets, transforms
  6. import helper
  7.  
  8. # Define a transform to normalize the data
  9. transform = transforms.Compose([transforms.ToTensor(),
  10. transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
  11. # Download and load the training data
  12. trainset = datasets.FashionMNIST('~/.pytorch/F_MNIST_data/', download=True, train=True, transform=transform)
  13. trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)
  14.  
  15. images, labels = next(iter(trainloader))
  16. images.resize_(64, 784)
  17.  
  18. model = nn.Sequential(nn.Linear(784, 128),
  19. nn.ReLU(),
  20. nn.Linear(128, 64),
  21. nn.ReLU(),
  22. nn.Linear(64, 10),
  23. nn.LogSoftmax(dim=1))
  24.  
  25. criterion = nn.CrossEntropyLoss()
  26. optimizer = optim.SGD(model.parameters(), lr=0.003)
  27.  
  28. epochs = 50
  29. for e in range(epochs):
  30. running_loss = 0
  31. for images, labels in trainloader:
  32. # Flatten MNIST images into a 784 long vector
  33. images = images.view(images.shape[0], -1)
  34.  
  35. # TODO: Training pass
  36. optimizer.zero_grad()
  37. logits = model(images)
  38. loss = criterion(logits, labels)
  39. loss.backward()
  40. optimizer.step()
  41.  
  42. running_loss += loss.item()
  43. else:
  44. print(f"Step {e} => Training loss: {running_loss/len(trainloader)}")
  45.  
  46. # Use the training
  47.  
  48. %matplotlib inline
  49. %config InlineBackend.figure_format = 'retina'
  50.  
  51. import helper
  52. import torch.nn.functional as F
  53.  
  54. # Test out your network!
  55.  
  56. dataiter = iter(testloader)
  57. images, labels = dataiter.next()
  58. img = images[0]
  59. # Convert 2D image to 1D vector
  60. img = img.resize_(1, 784)
  61.  
  62. # TODO: Calculate the class probabilities (softmax) for img
  63. with torch.no_grad():
  64. logits = model.forward(img)
  65.  
  66. # Output of the network are logits, need to take softmax for probabilities
  67. ps = F.softmax(logits, dim=1)
  68.  
  69. # Plot the image and probabilities
  70. helper.view_classify(img.resize_(1, 28, 28), ps, version='Fashion')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement