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