33.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. from visdom import Visdom
    7. batch_size=200
    8. learning_rate=0.01
    9. epochs=10
    10. train_loader = torch.utils.data.DataLoader(
    11. datasets.MNIST('../data', train=True, download=True,
    12. transform=transforms.Compose([
    13. transforms.ToTensor(),
    14. # transforms.Normalize((0.1307,), (0.3081,))
    15. ])),
    16. batch_size=batch_size, shuffle=True)
    17. test_loader = torch.utils.data.DataLoader(
    18. datasets.MNIST('../data', train=False, transform=transforms.Compose([
    19. transforms.ToTensor(),
    20. # transforms.Normalize((0.1307,), (0.3081,))
    21. ])),
    22. batch_size=batch_size, shuffle=True)
    23. class MLP(nn.Module):
    24. def __init__(self):
    25. super(MLP, self).__init__()
    26. self.model = nn.Sequential(
    27. nn.Linear(784, 200),
    28. nn.LeakyReLU(inplace=True),
    29. nn.Linear(200, 200),
    30. nn.LeakyReLU(inplace=True),
    31. nn.Linear(200, 10),
    32. nn.LeakyReLU(inplace=True),
    33. )
    34. def forward(self, x):
    35. x = self.model(x)
    36. return x
    37. device = torch.device('cuda:0')
    38. net = MLP().to(device)
    39. optimizer = optim.SGD(net.parameters(), lr=learning_rate, weight_decay=0.01)
    40. criteon = nn.CrossEntropyLoss().to(device)
    41. viz = Visdom()
    42. viz.line([0.], [0.], win='train_loss', opts=dict(title='train loss'))
    43. viz.line([[0.0, 0.0]], [0.], win='test', opts=dict(title='test loss&acc.',
    44. legend=['loss', 'acc.']))
    45. global_step = 0
    46. for epoch in range(epochs):
    47. for batch_idx, (data, target) in enumerate(train_loader):
    48. data = data.view(-1, 28*28)
    49. data, target = data.to(device), target.cuda()
    50. logits = net(data)
    51. loss = criteon(logits, target)
    52. optimizer.zero_grad()
    53. loss.backward()
    54. # print(w1.grad.norm(), w2.grad.norm())
    55. optimizer.step()
    56. global_step += 1
    57. viz.line([loss.item()], [global_step], win='train_loss', update='append')
    58. if batch_idx % 100 == 0:
    59. print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
    60. epoch, batch_idx * len(data), len(train_loader.dataset),
    61. 100. * batch_idx / len(train_loader), loss.item()))
    62. test_loss = 0
    63. correct = 0
    64. for data, target in test_loader:
    65. data = data.view(-1, 28 * 28)
    66. data, target = data.to(device), target.cuda()
    67. logits = net(data)
    68. test_loss += criteon(logits, target).item()
    69. pred = logits.argmax(dim=1)
    70. correct += pred.eq(target).float().sum().item()
    71. viz.line([[test_loss, correct / len(test_loader.dataset)]],
    72. [global_step], win='test', update='append')
    73. viz.images(data.view(-1, 1, 28, 28), win='x')
    74. viz.text(str(pred.detach().cpu().numpy()), win='pred',
    75. opts=dict(title='pred'))
    76. test_loss /= len(test_loader.dataset)
    77. print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
    78. test_loss, correct, len(test_loader.dataset),
    79. 100. * correct / len(test_loader.dataset)))