用 Lightning 最佳化模型訓練
透過加入像 ModelCheckpoint 與 EarlyStopping 這類自動化技術,你會讓模型選出表現最佳的參數,同時避免不必要的計算。
本資料集是 Osmanya MNIST 的子集,提供一個真實情境,讓可擴充的 AI 訓練技術能大幅提升效率與準確度。
OsmanyaDataModule 與 ImageClassifier 已為你預先定義。
本練習屬於課程
Scalable AI Models with PyTorch Lightning
練習說明
- 匯入你要用來做模型檢查點與提早停止的 callbacks。
- 使用
ModelCheckpoint與EarlyStopping這兩個 callback 訓練模型。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import relevant checkpoints
from lightning.pytorch.callbacks import ____, ____
class EvaluatedImageClassifier(ImageClassifier):
def validation_step(self, batch, batch_idx):
x, y = batch
y_hat = self(x)
acc = (y_hat.argmax(dim=1) == y).float().mean()
self.log("val_acc", acc)
model = EvaluatedImageClassifier()
data_module = OsmanyaDataModule()
# Train the model with ModelCheckpoint and EarlyStopping checkpoints
trainer = Trainer(____=[____(monitor="val_acc", save_top_k=1), ____(monitor="val_acc", patience=3)])
trainer.fit(model, datamodule=data_module)