image_classifier_4_lightning_module.py 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. """Simple MNIST image classifier example with LightningModule.
  15. To run: python image_classifier_4_lightning_module.py --trainer.max_epochs=50
  16. """
  17. import torch
  18. import torchvision.transforms as T
  19. from torch.nn import functional as F
  20. from torchmetrics import Accuracy
  21. from pl_examples import cli_lightning_logo
  22. from pl_examples.mnist_datamodule import MNIST
  23. from pl_examples.image_classifier_1_pytorch import Net
  24. from pytorch_lightning import LightningModule
  25. from pytorch_lightning.utilities.cli import LightningCLI
  26. class ImageClassifier(LightningModule):
  27. def __init__(self, model=None, lr=1.0, gamma=0.7, batch_size=32):
  28. super().__init__()
  29. self.save_hyperparameters(ignore="model")
  30. self.model = model or Net()
  31. self.test_acc = Accuracy()
  32. def forward(self, x):
  33. return self.model(x)
  34. def training_step(self, batch, batch_idx):
  35. x, y = batch
  36. logits = self.forward(x)
  37. loss = F.nll_loss(logits, y.long())
  38. return loss
  39. def test_step(self, batch, batch_idx):
  40. x, y = batch
  41. logits = self.forward(x)
  42. loss = F.nll_loss(logits, y.long())
  43. self.test_acc(logits, y)
  44. self.log("test_acc", self.test_acc)
  45. self.log("test_loss", loss)
  46. def configure_optimizers(self):
  47. optimizer = torch.optim.Adadelta(self.model.parameters(), lr=self.hparams.lr)
  48. return [optimizer], [torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=self.hparams.gamma)]
  49. # Methods for the `LightningDataModule` conversion
  50. @property
  51. def transform(self):
  52. return T.Compose([T.ToTensor(), T.Normalize((0.1307,), (0.3081,))])
  53. def prepare_data(self) -> None:
  54. MNIST("./data", download=True)
  55. def train_dataloader(self):
  56. train_dataset = MNIST("./data", train=True, download=False, transform=self.transform)
  57. return torch.utils.data.DataLoader(train_dataset, batch_size=self.hparams.batch_size)
  58. def test_dataloader(self):
  59. test_dataset = MNIST("./data", train=False, download=False, transform=self.transform)
  60. return torch.utils.data.DataLoader(test_dataset, batch_size=self.hparams.batch_size)
  61. def cli_main():
  62. # The LightningCLI removes all the boilerplate associated with arguments parsing. This is purely optional.
  63. cli = LightningCLI(ImageClassifier, seed_everything_default=42, save_config_overwrite=True, run=False)
  64. cli.trainer.fit(cli.model, datamodule=cli.datamodule)
  65. cli.trainer.test(ckpt_path="best", datamodule=cli.datamodule)
  66. if __name__ == "__main__":
  67. cli_lightning_logo()
  68. cli_main()