https://pytorch-lightning.readthedocs.io/en/latest/starter/introduction_guide.html

模型部分

定义模型

设计一个三层的神经网络,定义类时继承自LightningModule
对比:Pytorch中直接定义网络时,继承自nn.Module

  1. import torch
  2. from torch.nn import functional as F
  3. from torch import nn
  4. from pytorch_lightning.core.lightning import LightningModule
  5. class LitMNIST(LightningModule):
  6. def __init__(self):
  7. super().__init__()
  8. # mnist images are (1, 28, 28) (channels, height, width)
  9. self.layer_1 = nn.Linear(28 * 28, 128)
  10. self.layer_2 = nn.Linear(128, 256)
  11. self.layer_3 = nn.Linear(256, 10)
  12. def forward(self, x):
  13. batch_size, channels, height, width = x.size()
  14. # (b, 1, 28, 28) -> (b, 1*28*28)
  15. x = x.view(batch_size, -1)
  16. x = self.layer_1(x)
  17. x = F.relu(x)
  18. x = self.layer_2(x)
  19. x = F.relu(x)
  20. x = self.layer_3(x)
  21. x = F.log_softmax(x, dim=1)
  22. return x

LightningModule 和 Pytorch里的模块相同的,但增加了一些功能
实例化的用法相同

  1. net = LitMNIST()
  2. x = torch.randn(1, 1, 28, 28)
  3. out = net(x)
  4. print(out.shape)

训练

增加training_step

  1. class LitMNIST(LightningModule):
  2. def training_step(self, batch, batch_idx):
  3. x, y = batch
  4. logits = self(x)
  5. loss = F.nll_loss(logits, y)
  6. return loss

优化器Optimizer

Pytorch里面用法

  1. from torch.optim import Adam
  2. optimizer = Adam(LitMNIST().parameters(), lr=1e-3)

Lightning里面重新定义configure_optimizers()方法

  1. class LitMNIST(LightningModule):
  2. def configure_optimizers(self):
  3. return Adam(self.parameters(), lr=1e-3)

如果有学习率的变化

  1. from torch.optim.lr_scheduler import CosineAnnealingLR
  2. class LitMNIST(LightningModule):
  3. def configure_optimizers(self):
  4. opt = Adam(self.parameters(), lr=1e-3)
  5. scheduler = CosineAnnealingLR(opt, T_max=10)
  6. return [opt], [scheduler]

数据

Pytorch里加载数据

主要是使用DatasetsDataLoader

  1. from torch.utils.data import DataLoader, random_split
  2. from torchvision.datasets import MNIST
  3. import os
  4. from torchvision import datasets, transforms
  5. from pytorch_lightning import Trainer
  6. # transforms
  7. # prepare transforms standard to MNIST
  8. transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])
  9. # data
  10. mnist_train = MNIST(os.getcwd(), train=True, download=True, transform=transform)
  11. mnist_train = DataLoader(mnist_train, batch_size=64)

Lightning里