image_classifier_1_pytorch.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. # Copyright The PyTorch Lightning team.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import argparse
  15. import torch
  16. import torch.nn as nn
  17. import torch.nn.functional as F
  18. import torch.optim as optim
  19. import torchvision.transforms as T
  20. from torch.optim.lr_scheduler import StepLR
  21. from pl_examples.mnist_datamodule import MNIST
  22. # Credit to the PyTorch Team
  23. # Taken from https://github.com/pytorch/examples/blob/master/mnist/main.py and slightly adapted.
  24. class Net(nn.Module):
  25. def __init__(self):
  26. super().__init__()
  27. self.conv1 = nn.Conv2d(1, 32, 3, 1)
  28. self.conv2 = nn.Conv2d(32, 64, 3, 1)
  29. self.dropout1 = nn.Dropout(0.25)
  30. self.dropout2 = nn.Dropout(0.5)
  31. self.fc1 = nn.Linear(9216, 128)
  32. self.fc2 = nn.Linear(128, 10)
  33. def forward(self, x):
  34. x = self.conv1(x)
  35. x = F.relu(x)
  36. x = self.conv2(x)
  37. x = F.relu(x)
  38. x = F.max_pool2d(x, 2)
  39. x = self.dropout1(x)
  40. x = torch.flatten(x, 1)
  41. x = self.fc1(x)
  42. x = F.relu(x)
  43. x = self.dropout2(x)
  44. x = self.fc2(x)
  45. output = F.log_softmax(x, dim=1)
  46. return output
  47. def run(hparams):
  48. torch.manual_seed(hparams.seed)
  49. use_cuda = torch.cuda.is_available()
  50. device = torch.device("cuda" if use_cuda else "cpu")
  51. transform = T.Compose([T.ToTensor(), T.Normalize((0.1307,), (0.3081,))])
  52. train_dataset = MNIST("./data", train=True, download=True, transform=transform)
  53. test_dataset = MNIST("./data", train=False, transform=transform)
  54. train_loader = torch.utils.data.DataLoader(
  55. train_dataset,
  56. batch_size=hparams.batch_size,
  57. )
  58. test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=hparams.batch_size)
  59. model = Net().to(device)
  60. optimizer = optim.Adadelta(model.parameters(), lr=hparams.lr)
  61. scheduler = StepLR(optimizer, step_size=1, gamma=hparams.gamma)
  62. # EPOCH LOOP
  63. for epoch in range(1, hparams.epochs + 1):
  64. # TRAINING LOOP
  65. model.train()
  66. for batch_idx, (data, target) in enumerate(train_loader):
  67. data, target = data.to(device), target.to(device)
  68. optimizer.zero_grad()
  69. output = model(data)
  70. loss = F.nll_loss(output, target)
  71. loss.backward()
  72. optimizer.step()
  73. if (batch_idx == 0) or ((batch_idx + 1) % hparams.log_interval == 0):
  74. print(
  75. "Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}".format(
  76. epoch,
  77. batch_idx * len(data),
  78. len(train_loader.dataset),
  79. 100.0 * batch_idx / len(train_loader),
  80. loss.item(),
  81. )
  82. )
  83. if hparams.dry_run:
  84. break
  85. scheduler.step()
  86. # TESTING LOOP
  87. model.eval()
  88. test_loss = 0
  89. correct = 0
  90. with torch.no_grad():
  91. for data, target in test_loader:
  92. data, target = data.to(device), target.to(device)
  93. output = model(data)
  94. test_loss += F.nll_loss(output, target, reduction="sum").item() # sum up batch loss
  95. pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability
  96. correct += pred.eq(target.view_as(pred)).sum().item()
  97. if hparams.dry_run:
  98. break
  99. test_loss /= len(test_loader.dataset)
  100. print(
  101. "\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n".format(
  102. test_loss, correct, len(test_loader.dataset), 100.0 * correct / len(test_loader.dataset)
  103. )
  104. )
  105. if hparams.dry_run:
  106. break
  107. if hparams.save_model:
  108. torch.save(model.state_dict(), "mnist_cnn.pt")
  109. def main():
  110. parser = argparse.ArgumentParser(description="PyTorch MNIST Example")
  111. parser.add_argument(
  112. "--batch-size", type=int, default=64, metavar="N", help="input batch size for training (default: 64)"
  113. )
  114. parser.add_argument("--epochs", type=int, default=14, metavar="N", help="number of epochs to train (default: 14)")
  115. parser.add_argument("--lr", type=float, default=1.0, metavar="LR", help="learning rate (default: 1.0)")
  116. parser.add_argument("--gamma", type=float, default=0.7, metavar="M", help="Learning rate step gamma (default: 0.7)")
  117. parser.add_argument("--dry-run", action="store_true", default=False, help="quickly check a single pass")
  118. parser.add_argument("--seed", type=int, default=1, metavar="S", help="random seed (default: 1)")
  119. parser.add_argument(
  120. "--log-interval",
  121. type=int,
  122. default=10,
  123. metavar="N",
  124. help="how many batches to wait before logging training status",
  125. )
  126. parser.add_argument("--save-model", action="store_true", default=False, help="For Saving the current Model")
  127. hparams = parser.parse_args()
  128. run(hparams)
  129. if __name__ == "__main__":
  130. main()