forked from Lightning-AI/pytorch-lightning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimple_image_classifier.py
104 lines (84 loc) · 3.28 KB
/
simple_image_classifier.py
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
# Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
MNIST simple image classifier example.
To run:
python simple_image_classifier.py --trainer.max_epochs=50
"""
import torch
from torch.nn import functional as F
import pytorch_lightning as pl
from pl_examples import cli_lightning_logo
from pl_examples.basic_examples.mnist_datamodule import MNISTDataModule
from pytorch_lightning.utilities.cli import LightningCLI, SaveConfigCallback
class LitClassifier(pl.LightningModule):
"""
>>> LitClassifier() # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
LitClassifier(
(l1): Linear(...)
(l2): Linear(...)
)
"""
def __init__(
self,
l1: torch.nn.Linear,
l2: torch.nn.Linear,
learning_rate: float = 0.0001,
):
super().__init__()
self.save_hyperparameters()
self.l1 = l1
self.l2 = l2
# self.l1 = torch.nn.Linear(28 * 28, self.hparams.hidden_dim)
# self.l2 = torch.nn.Linear(self.hparams.hidden_dim, 10)
def forward(self, x):
x = x.view(x.size(0), -1)
x = torch.relu(self.l1(x))
x = torch.relu(self.l2(x))
return x
def training_step(self, batch, batch_idx):
x, y = batch
y_hat = self(x)
loss = F.cross_entropy(y_hat, y)
return loss
def validation_step(self, batch, batch_idx):
x, y = batch
y_hat = self(x)
loss = F.cross_entropy(y_hat, y)
self.log('valid_loss', loss)
def test_step(self, batch, batch_idx):
x, y = batch
y_hat = self(x)
loss = F.cross_entropy(y_hat, y)
self.log('test_loss', loss)
def configure_optimizers(self):
return torch.optim.Adam(self.parameters(), lr=self.hparams.learning_rate)
class WandBandSafeConfigCallBackFixCLI(LightningCLI):
def add_arguments_to_parser(self, parser):
parser.add_argument('save_config_callback_filename', default='',
help='Change config filename in order to avoid clashes with wandb.'
'Discussed already in https://github.com/PyTorchLightning/pytorch-lightning/pull/7675')
def before_fit(self):
save_config_cb = [c for c in self.trainer.callbacks if isinstance(c, SaveConfigCallback)]
if save_config_cb:
config_filename = self.config.get('save_config_callback_filename', '')
if config_filename:
save_config_cb[0].config_filename = config_filename
def cli_main():
# cli = LightningCLI(LitClassifier, MNISTDataModule, seed_everything_default=1234)
cli = WandBandSafeConfigCallBackFixCLI(LitClassifier, MNISTDataModule, seed_everything_default=1234)
cli.trainer.test(cli.model, datamodule=cli.datamodule)
if __name__ == '__main__':
cli_lightning_logo()
cli_main()