27 全连接层.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.ReLU(inplace=True),
    28. nn.Linear(200, 200),
    29. nn.ReLU(inplace=True),
    30. nn.Linear(200, 10),
    31. nn.ReLU(inplace=True),
    32. )
    33. def forward(self, x):
    34. x = self.model(x)
    35. return x
    36. net = MLP()
    37. optimizer = optim.SGD(net.parameters(), lr=learning_rate)
    38. criteon = nn.CrossEntropyLoss()
    39. for epoch in range(epochs):
    40. for batch_idx, (data, target) in enumerate(train_loader):
    41. data = data.view(-1, 28*28)
    42. logits = net(data)
    43. loss = criteon(logits, target)
    44. optimizer.zero_grad()
    45. loss.backward()
    46. # print(w1.grad.norm(), w2.grad.norm())
    47. optimizer.step()
    48. if batch_idx % 100 == 0:
    49. print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
    50. epoch, batch_idx * len(data), len(train_loader.dataset),
    51. 100. * batch_idx / len(train_loader), loss.item()))
    52. test_loss = 0
    53. correct = 0
    54. for data, target in test_loader:
    55. data = data.view(-1, 28 * 28)
    56. logits = net(data)
    57. test_loss += criteon(logits, target).item()
    58. pred = logits.data.max(1)[1]
    59. correct += pred.eq(target.data).sum()
    60. test_loss /= len(test_loader.dataset)
    61. print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
    62. test_loss, correct, len(test_loader.dataset),
    63. 100. * correct / len(test_loader.dataset)))