【PyTorch Lightning】

python 复制代码
import os
from torch import optim, nn, utils, Tensor
from torchvision.datasets import MNIST
from torchvision.transforms import ToTensor
import lightning as L

# define any number of nn.Modules (or use your current ones)
encoder = nn.Sequential(nn.Linear(28 * 28, 64), nn.ReLU(), nn.Linear(64, 3))
decoder = nn.Sequential(nn.Linear(3, 64), nn.ReLU(), nn.Linear(64, 28 * 28))


# define the LightningModule
class LitAutoEncoder(L.LightningModule):
    def __init__(self, encoder, decoder):
        super().__init__()
        self.encoder = encoder
        self.decoder = decoder

    def training_step(self, batch, batch_idx):
        # training_step defines the train loop.
        # it is independent of forward
        x, _ = batch
        x = x.view(x.size(0), -1)
        z = self.encoder(x)
        x_hat = self.decoder(z)
        loss = nn.functional.mse_loss(x_hat, x)
        # Logging to TensorBoard (if installed) by default
        self.log("train_loss", loss)
        return loss

    def configure_optimizers(self):
        optimizer = optim.Adam(self.parameters(), lr=1e-3)
        return optimizer


# init the autoencoder
autoencoder = LitAutoEncoder(encoder, decoder)

# setup data
dataset = MNIST(os.getcwd(), download=True, transform=ToTensor())
train_loader = utils.data.DataLoader(dataset)

# train the model (hint: here are some helpful Trainer arguments for rapid idea iteration)
trainer = L.Trainer(limit_train_batches=100, max_epochs=1)
trainer.fit(model=autoencoder, train_dataloaders=train_loader)

# load checkpoint
checkpoint = "./lightning_logs/version_0/checkpoints/epoch=0-step=100.ckpt"
autoencoder = LitAutoEncoder.load_from_checkpoint(checkpoint, encoder=encoder, decoder=decoder)

# choose your trained nn.Module
encoder = autoencoder.encoder
encoder.eval()

# embed 4 fake images!
fake_image_batch = torch.rand(4, 28 * 28, device=autoencoder.device)
embeddings = encoder(fake_image_batch)
print("⚡" * 20, "\nPredictions (4 image embeddings):\n", embeddings, "\n", "⚡" * 20)
python 复制代码
tensorboard --logdir .

Module中要定义forward函数;

Lightning Module中除了forward函数,还要定义configure_optimizers, training_step和validation_step函数

相关推荐
泯泷29 分钟前
让 Agent 分清“马上办、等一等、顺手办”
人工智能·llm·agent
鲜于言悠9051 小时前
Claude Fable 5.2 登场,专治复杂推理与长任务
人工智能
大可不必了1 小时前
03 函数定义和调用
开发语言·python
联犀2 小时前
如何工程化降低语音交互AI设备的延迟(小智ai,芙崽这样的ai设备)
人工智能
杉岩数据2 小时前
杉岩数据董事长陈坚:从数据存储到行业智能——杉岩的AI时代战略布局
人工智能
冬奇Lab2 小时前
Loop 工程到底是高深的新技术,还是炒冷饭?用训练一个识别狗的模型讲明白
人工智能
冬奇Lab2 小时前
一天一个开源项目(第260篇):Plannotator —— 给 AI 编码 Agent 配一块「可批注的审阅台」,计划和代码改动都能在浏览器里逐条批示
人工智能·开源·claude
泯泷2 小时前
语音,正在成为 AI Agent 最自然的接口
人工智能·llm·agent
承渊政道3 小时前
【Python编程—从入门到实践】(记分与闯关:用Python+Pygame,打造越战越精彩的太空大战!)
开发语言·python·pycharm·游戏程序·pygame
爱学习的程序媛3 小时前
Python常用框架梳理
开发语言·后端·python·ai·web·后端框架·python框架