PyTorch Lightning 是一个轻量级的 PyTorch 框架,它简化了深度学习模型的训练流程,使代码更易于编写和维护。以下是如何使用 PyTorch Lightning 加速模型训练流程的步骤:
pip install pytorch-lightning
import pytorch_lightning as pl
import torch
class MyModel(pl.LightningModule):
def __init__(self):
super(MyModel, self).__init__()
self.model = torch.nn.Linear(10, 1)
def forward(self, x):
return self.model(x)
def training_step(self, batch, batch_idx):
x, y = batch
y_pred = self(x)
loss = torch.nn.functional.mse_loss(y_pred, y)
return loss
def configure_optimizers(self):
return torch.optim.Adam(self.parameters(), lr=0.001)
class MyDataModule(pl.LightningDataModule):
def __init__(self):
super(MyDataModule, self).__init__()
self.train_dataset = ...
self.val_dataset = ...
def prepare_data(self):
# Download and preprocess data
...
def setup(self, stage=None):
if stage == 'fit' or stage is None:
self.train_loader = DataLoader(self.train_dataset, batch_size=32)
self.val_loader = DataLoader(self.val_dataset, batch_size=32)
model = MyModel()
data_module = MyDataModule()
trainer = pl.Trainer(max_epochs=10)
trainer.fit(model, data_module)
通过使用 PyTorch Lightning,您可以更轻松地管理模型训练流程,加速开发过程并提升代码的可读性和可维护性。