28.pdf

    1. import torch
    2. import torch.nn as nn
    3. import torch.nn.functional as F
    4. import torch.optim as optim
    5. from torchvision import datasets, transforms
    6. batch_size=200
    7. learning_rate=0.01
    8. epochs=10
    9. train_loader = torch.utils.data.DataLoader(
    10. datasets.MNIST('../data', train=True, download=True,
    11. transform=transforms.Compose([
    12. transforms.ToTensor(),
    13. transforms.Normalize((0.1307,), (0.3081,))
    14. ])),
    15. batch_size=batch_size, shuffle=True)
    16. test_loader = torch.utils.data.DataLoader(
    17. datasets.MNIST('../data', train=False, transform=transforms.Compose([
    18. transforms.ToTensor(),
    19. transforms.Normalize((0.1307,), (0.3081,))
    20. ])),
    21. batch_size=batch_size, shuffle=True)
    22. class MLP(nn.Module):
    23. def __init__(self):
    24. super(MLP, self).__init__()
    25. self.model = nn.Sequential(
    26. nn.Linear(784, 200),
    27. nn.LeakyReLU(inplace=True),
    28. nn.Linear(200, 200),
    29. nn.LeakyReLU(inplace=True),
    30. nn.Linear(200, 10),
    31. nn.LeakyReLU(inplace=True),
    32. )
    33. def forward(self, x):
    34. x = self.model(x)
    35. return x
    36. device = torch.device('cuda:0')
    37. net = MLP().to(device)
    38. optimizer = optim.SGD(net.parameters(), lr=learning_rate)
    39. criteon = nn.CrossEntropyLoss().to(device)
    40. for epoch in range(epochs):
    41. for batch_idx, (data, target) in enumerate(train_loader):
    42. data = data.view(-1, 28*28)
    43. data, target = data.to(device), target.cuda()
    44. logits = net(data)
    45. loss = criteon(logits, target)
    46. optimizer.zero_grad()
    47. loss.backward()
    48. # print(w1.grad.norm(), w2.grad.norm())
    49. optimizer.step()
    50. if batch_idx % 100 == 0:
    51. print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
    52. epoch, batch_idx * len(data), len(train_loader.dataset),
    53. 100. * batch_idx / len(train_loader), loss.item()))
    54. test_loss = 0
    55. correct = 0
    56. for data, target in test_loader:
    57. data = data.view(-1, 28 * 28)
    58. data, target = data.to(device), target.cuda()
    59. logits = net(data)
    60. test_loss += criteon(logits, target).item()
    61. pred = logits.data.max(1)[1]
    62. correct += pred.eq(target.data).sum()
    63. test_loss /= len(test_loader.dataset)
    64. print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
    65. test_loss, correct, len(test_loader.dataset),
    66. 100. * correct / len(test_loader.dataset)))