Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

lit_image_classifier.py 3.2 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
  1. from argparse import ArgumentParser
  2. import torch
  3. import pytorch_lightning as pl
  4. from torch.nn import functional as F
  5. from torch.utils.data import DataLoader, random_split
  6. from torchvision.datasets.mnist import MNIST
  7. from torchvision import transforms
  8. class Backbone(torch.nn.Module):
  9. def __init__(self, hidden_dim=128):
  10. super().__init__()
  11. self.l1 = torch.nn.Linear(28 * 28, hidden_dim)
  12. self.l2 = torch.nn.Linear(hidden_dim, 10)
  13. def forward(self, x):
  14. x = x.view(x.size(0), -1)
  15. x = torch.relu(self.l1(x))
  16. x = torch.relu(self.l2(x))
  17. return x
  18. class LitClassifier(pl.LightningModule):
  19. def __init__(self, backbone, learning_rate=1e-3):
  20. super().__init__()
  21. self.save_hyperparameters()
  22. self.backbone = backbone
  23. def forward(self, x):
  24. # use forward for inference/predictions
  25. embedding = self.backbone(x)
  26. return embedding
  27. def training_step(self, batch, batch_idx):
  28. x, y = batch
  29. y_hat = self.backbone(x)
  30. loss = F.cross_entropy(y_hat, y)
  31. self.log('train_loss', loss, on_epoch=True)
  32. return loss
  33. def validation_step(self, batch, batch_idx):
  34. x, y = batch
  35. y_hat = self.backbone(x)
  36. loss = F.cross_entropy(y_hat, y)
  37. self.log('valid_loss', loss, on_step=True)
  38. def test_step(self, batch, batch_idx):
  39. x, y = batch
  40. y_hat = self.backbone(x)
  41. loss = F.cross_entropy(y_hat, y)
  42. self.log('test_loss', loss)
  43. def configure_optimizers(self):
  44. # self.hparams available because we called self.save_hyperparameters()
  45. return torch.optim.Adam(self.parameters(), lr=self.hparams.learning_rate)
  46. @staticmethod
  47. def add_model_specific_args(parent_parser):
  48. parser = ArgumentParser(parents=[parent_parser], add_help=False)
  49. parser.add_argument('--learning_rate', type=float, default=0.0001)
  50. return parser
  51. def cli_main():
  52. pl.seed_everything(1234)
  53. # ------------
  54. # args
  55. # ------------
  56. parser = ArgumentParser()
  57. parser.add_argument('--batch_size', default=32, type=int)
  58. parser.add_argument('--hidden_dim', type=int, default=128)
  59. parser = pl.Trainer.add_argparse_args(parser)
  60. parser = LitClassifier.add_model_specific_args(parser)
  61. args = parser.parse_args()
  62. # ------------
  63. # data
  64. # ------------
  65. dataset = MNIST('', train=True, download=True, transform=transforms.ToTensor())
  66. mnist_test = MNIST('', train=False, download=True, transform=transforms.ToTensor())
  67. mnist_train, mnist_val = random_split(dataset, [55000, 5000])
  68. train_loader = DataLoader(mnist_train, batch_size=args.batch_size)
  69. val_loader = DataLoader(mnist_val, batch_size=args.batch_size)
  70. test_loader = DataLoader(mnist_test, batch_size=args.batch_size)
  71. # ------------
  72. # model
  73. # ------------
  74. model = LitClassifier(Backbone(hidden_dim=args.hidden_dim), args.learning_rate)
  75. # ------------
  76. # training
  77. # ------------
  78. trainer = pl.Trainer.from_argparse_args(args)
  79. trainer.fit(model, train_loader, val_loader)
  80. # ------------
  81. # testing
  82. # ------------
  83. result = trainer.test(test_dataloaders=test_loader)
  84. print(result)
  85. if __name__ == '__main__':
  86. cli_main()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...