32.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_db = datasets.MNIST('../data', train=True, download=True,
    10. transform=transforms.Compose([
    11. transforms.ToTensor(),
    12. transforms.Normalize((0.1307,), (0.3081,))
    13. ]))
    14. train_loader = torch.utils.data.DataLoader(
    15. train_db,
    16. batch_size=batch_size, shuffle=True)
    17. test_db = datasets.MNIST('../data', train=False, transform=transforms.Compose([
    18. transforms.ToTensor(),
    19. transforms.Normalize((0.1307,), (0.3081,))
    20. ]))
    21. test_loader = torch.utils.data.DataLoader(test_db,
    22. batch_size=batch_size, shuffle=True)
    23. print('train:', len(train_db), 'test:', len(test_db))
    24. train_db, val_db = torch.utils.data.random_split(train_db, [50000, 10000])
    25. print('db1:', len(train_db), 'db2:', len(val_db))
    26. train_loader = torch.utils.data.DataLoader(
    27. train_db,
    28. batch_size=batch_size, shuffle=True)
    29. val_loader = torch.utils.data.DataLoader(
    30. val_db,
    31. batch_size=batch_size, shuffle=True)
    32. class MLP(nn.Module):
    33. def __init__(self):
    34. super(MLP, self).__init__()
    35. self.model = nn.Sequential(
    36. nn.Linear(784, 200),
    37. nn.LeakyReLU(inplace=True),
    38. nn.Linear(200, 200),
    39. nn.LeakyReLU(inplace=True),
    40. nn.Linear(200, 10),
    41. nn.LeakyReLU(inplace=True),
    42. )
    43. def forward(self, x):
    44. x = self.model(x)
    45. return x
    46. device = torch.device('cuda:0')
    47. net = MLP().to(device)
    48. optimizer = optim.SGD(net.parameters(), lr=learning_rate)
    49. criteon = nn.CrossEntropyLoss().to(device)
    50. for epoch in range(epochs):
    51. for batch_idx, (data, target) in enumerate(train_loader):
    52. data = data.view(-1, 28*28)
    53. data, target = data.to(device), target.cuda()
    54. logits = net(data)
    55. loss = criteon(logits, target)
    56. optimizer.zero_grad()
    57. loss.backward()
    58. # print(w1.grad.norm(), w2.grad.norm())
    59. optimizer.step()
    60. if batch_idx % 100 == 0:
    61. print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
    62. epoch, batch_idx * len(data), len(train_loader.dataset),
    63. 100. * batch_idx / len(train_loader), loss.item()))
    64. test_loss = 0
    65. correct = 0
    66. for data, target in val_loader:
    67. data = data.view(-1, 28 * 28)
    68. data, target = data.to(device), target.cuda()
    69. logits = net(data)
    70. test_loss += criteon(logits, target).item()
    71. pred = logits.data.max(1)[1]
    72. correct += pred.eq(target.data).sum()
    73. test_loss /= len(val_loader.dataset)
    74. print('\nVAL set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
    75. test_loss, correct, len(val_loader.dataset),
    76. 100. * correct / len(val_loader.dataset)))
    77. test_loss = 0
    78. correct = 0
    79. for data, target in test_loader:
    80. data = data.view(-1, 28 * 28)
    81. data, target = data.to(device), target.cuda()
    82. logits = net(data)
    83. test_loss += criteon(logits, target).item()
    84. pred = logits.data.max(1)[1]
    85. correct += pred.eq(target.data).sum()
    86. test_loss /= len(test_loader.dataset)
    87. print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
    88. test_loss, correct, len(test_loader.dataset),
    89. 100. * correct / len(test_loader.dataset)))