2020-09-23 04:19:46 +00:00
|
|
|
# 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.
|
2021-09-06 12:49:09 +00:00
|
|
|
"""MNIST autoencoder example.
|
2020-09-23 04:19:46 +00:00
|
|
|
|
2021-09-06 12:49:09 +00:00
|
|
|
To run: python autoencoder.py --trainer.max_epochs=50
|
2021-04-15 15:01:16 +00:00
|
|
|
"""
|
2020-11-20 18:10:40 +00:00
|
|
|
|
2020-09-23 04:19:46 +00:00
|
|
|
import torch
|
|
|
|
import torch.nn.functional as F
|
2020-11-20 18:10:40 +00:00
|
|
|
from torch import nn
|
2020-12-29 08:19:02 +00:00
|
|
|
from torch.utils.data import DataLoader, random_split
|
2020-09-23 21:58:03 +00:00
|
|
|
|
2020-11-20 18:10:40 +00:00
|
|
|
import pytorch_lightning as pl
|
2021-07-19 07:41:18 +00:00
|
|
|
from pl_examples import _DATASETS_PATH, cli_lightning_logo
|
|
|
|
from pl_examples.basic_examples.mnist_datamodule import MNIST
|
2021-04-15 15:01:16 +00:00
|
|
|
from pytorch_lightning.utilities.cli import LightningCLI
|
2021-04-13 16:33:32 +00:00
|
|
|
from pytorch_lightning.utilities.imports import _TORCHVISION_AVAILABLE
|
2020-11-20 18:10:40 +00:00
|
|
|
|
2021-03-11 11:19:48 +00:00
|
|
|
if _TORCHVISION_AVAILABLE:
|
2020-09-23 21:58:03 +00:00
|
|
|
from torchvision import transforms
|
2020-09-23 04:19:46 +00:00
|
|
|
|
|
|
|
|
|
|
|
class LitAutoEncoder(pl.LightningModule):
|
2020-12-17 10:13:48 +00:00
|
|
|
"""
|
|
|
|
>>> LitAutoEncoder() # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
|
|
|
|
LitAutoEncoder(
|
|
|
|
(encoder): ...
|
|
|
|
(decoder): ...
|
|
|
|
)
|
|
|
|
"""
|
2020-09-23 04:19:46 +00:00
|
|
|
|
2021-03-24 08:27:08 +00:00
|
|
|
def __init__(self, hidden_dim: int = 64):
|
2020-09-23 04:19:46 +00:00
|
|
|
super().__init__()
|
2021-07-26 11:37:35 +00:00
|
|
|
self.encoder = nn.Sequential(nn.Linear(28 * 28, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, 3))
|
|
|
|
self.decoder = nn.Sequential(nn.Linear(3, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, 28 * 28))
|
2020-09-23 04:19:46 +00:00
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
# in lightning, forward defines the prediction/inference actions
|
|
|
|
embedding = self.encoder(x)
|
|
|
|
return embedding
|
|
|
|
|
|
|
|
def training_step(self, batch, batch_idx):
|
|
|
|
x, y = batch
|
|
|
|
x = x.view(x.size(0), -1)
|
|
|
|
z = self.encoder(x)
|
|
|
|
x_hat = self.decoder(z)
|
|
|
|
loss = F.mse_loss(x_hat, x)
|
2020-09-30 12:31:16 +00:00
|
|
|
return loss
|
2020-09-23 04:19:46 +00:00
|
|
|
|
2021-02-16 19:31:07 +00:00
|
|
|
def validation_step(self, batch, batch_idx):
|
|
|
|
x, y = batch
|
|
|
|
x = x.view(x.size(0), -1)
|
|
|
|
z = self.encoder(x)
|
|
|
|
x_hat = self.decoder(z)
|
|
|
|
loss = F.mse_loss(x_hat, x)
|
2021-07-26 11:37:35 +00:00
|
|
|
self.log("valid_loss", loss, on_step=True)
|
2021-02-16 19:31:07 +00:00
|
|
|
|
|
|
|
def test_step(self, batch, batch_idx):
|
|
|
|
x, y = batch
|
|
|
|
x = x.view(x.size(0), -1)
|
|
|
|
z = self.encoder(x)
|
|
|
|
x_hat = self.decoder(z)
|
|
|
|
loss = F.mse_loss(x_hat, x)
|
2021-07-26 11:37:35 +00:00
|
|
|
self.log("test_loss", loss, on_step=True)
|
2021-02-16 19:31:07 +00:00
|
|
|
|
2021-06-16 11:23:27 +00:00
|
|
|
def predict_step(self, batch, batch_idx, dataloader_idx=None):
|
|
|
|
x, y = batch
|
|
|
|
x = x.view(x.size(0), -1)
|
|
|
|
z = self.encoder(x)
|
|
|
|
return self.decoder(z)
|
|
|
|
|
2020-09-23 04:19:46 +00:00
|
|
|
def configure_optimizers(self):
|
|
|
|
optimizer = torch.optim.Adam(self.parameters(), lr=1e-3)
|
|
|
|
return optimizer
|
|
|
|
|
|
|
|
|
2021-04-15 15:01:16 +00:00
|
|
|
class MyDataModule(pl.LightningDataModule):
|
2021-07-26 11:37:35 +00:00
|
|
|
def __init__(self, batch_size: int = 32):
|
2021-04-15 15:01:16 +00:00
|
|
|
super().__init__()
|
|
|
|
dataset = MNIST(_DATASETS_PATH, train=True, download=True, transform=transforms.ToTensor())
|
|
|
|
self.mnist_test = MNIST(_DATASETS_PATH, train=False, download=True, transform=transforms.ToTensor())
|
|
|
|
self.mnist_train, self.mnist_val = random_split(dataset, [55000, 5000])
|
|
|
|
self.batch_size = batch_size
|
|
|
|
|
|
|
|
def train_dataloader(self):
|
|
|
|
return DataLoader(self.mnist_train, batch_size=self.batch_size)
|
|
|
|
|
|
|
|
def val_dataloader(self):
|
|
|
|
return DataLoader(self.mnist_val, batch_size=self.batch_size)
|
|
|
|
|
|
|
|
def test_dataloader(self):
|
|
|
|
return DataLoader(self.mnist_test, batch_size=self.batch_size)
|
|
|
|
|
2021-06-16 11:23:27 +00:00
|
|
|
def predict_dataloader(self):
|
|
|
|
return DataLoader(self.mnist_test, batch_size=self.batch_size)
|
|
|
|
|
2021-04-15 15:01:16 +00:00
|
|
|
|
2020-09-23 04:19:46 +00:00
|
|
|
def cli_main():
|
2021-08-28 04:43:14 +00:00
|
|
|
cli = LightningCLI(
|
|
|
|
LitAutoEncoder, MyDataModule, seed_everything_default=1234, save_config_overwrite=True, run=False
|
|
|
|
)
|
|
|
|
cli.trainer.fit(cli.model, datamodule=cli.datamodule)
|
|
|
|
cli.trainer.test(ckpt_path="best")
|
|
|
|
predictions = cli.trainer.predict(ckpt_path="best")
|
2021-06-16 11:23:27 +00:00
|
|
|
print(predictions[0])
|
2020-09-23 04:19:46 +00:00
|
|
|
|
|
|
|
|
2021-07-26 11:37:35 +00:00
|
|
|
if __name__ == "__main__":
|
2020-12-17 09:21:00 +00:00
|
|
|
cli_lightning_logo()
|
2020-09-23 04:19:46 +00:00
|
|
|
cli_main()
|