最佳化器、訓練與評估

Intermediate Deep Learning with PyTorch

Michal Oleszak

Machine Learning Engineer

訓練迴圈

import torch.nn as nn
import torch.optim as optim

criterion = nn.BCELoss()
optimizer = optim.SGD(net.parameters(), lr=0.01)


for epoch in range(1000): for features, labels in dataloader_train:
optimizer.zero_grad()
outputs = net(features)
loss = criterion( outputs, labels.view(-1, 1) )
loss.backward()
optimizer.step()
  • 定義損失函式與最佳化器
    • 二元分類用 BCELoss
    • SGD 最佳化器
  • 迭代 epoch 與訓練批次
  • 清空梯度
  • 前向傳遞:取得模型輸出
  • 計算損失
  • 計算梯度
  • 最佳化步驟:更新參數
Intermediate Deep Learning with PyTorch

最佳化器如何運作

 

兩個長度為 2 的向量:一個為參數值(1 與 0.5),另一個為梯度(0.9 與 -0.2)。

Intermediate Deep Learning with PyTorch

最佳化器如何運作

 

箭頭顯示帶有參數與梯度的兩個向量如何傳入最佳化器(繪成靶心)。

Intermediate Deep Learning with PyTorch

最佳化器如何運作

 

從最佳化器指向一個向量的箭頭,包含兩個參數更新:-0.5 與 0.5。

Intermediate Deep Learning with PyTorch

最佳化器如何運作

 

從參數更新指向更新後參數值的箭頭:0.5 與 1.0。

Intermediate Deep Learning with PyTorch

最佳化器如何運作

 

從參數更新指向更新後參數值的箭頭:0.5 與 1.0。

Intermediate Deep Learning with PyTorch

隨機梯度下降(SGD)

optimizer = optim.SGD(net.parameters(), lr=0.01)
  • 更新取決於學習率
  • 簡單高效,適合基礎模型
  • 實務上較少單獨使用
Intermediate Deep Learning with PyTorch

自適應梯度(Adagrad)

optimizer = optim.Adagrad(net.parameters(), lr=0.01)
  • 為每個參數自適應學習率
  • 適合稀疏資料
  • 可能使學習率下降過快
Intermediate Deep Learning with PyTorch

均方根傳播(RMSprop)

optimizer = optim.RMSprop(net.parameters(), lr=0.01)
  • 依各參數過去梯度大小調整其更新
Intermediate Deep Learning with PyTorch

自適應動量估計(Adam)

optimizer = optim.Adam(net.parameters(), lr=0.01)
  • 可說是最通用、最常用
  • 結合 RMSprop 與梯度動量
  • 常作為首選最佳化器
Intermediate Deep Learning with PyTorch

模型評估

from torchmetrics import Accuracy

acc = Accuracy(task="binary")


net.eval() with torch.no_grad(): for features, labels in dataloader_test:
outputs = net(features)
preds = (outputs >= 0.5).float()
acc(preds, labels.view(-1, 1))
accuracy = acc.compute() print(f"Accuracy: {accuracy}")
Accuracy: 0.6759443283081055
  • 設定準確率評估指標
  • 將模型設為評估模式,無梯度地遍歷測試批次
  • 將資料送入模型取得預測機率
  • 計算預測標籤
  • 更新準確率指標
Intermediate Deep Learning with PyTorch

一起來練習吧!

Intermediate Deep Learning with PyTorch

Preparing Video For Download...