訓練與評估 RNNs

Intermediate Deep Learning with PyTorch

Michal Oleszak

Machine Learning Engineer

均方誤差損失

  • 誤差:

    $$prediction - target$$

  • 平方誤差:

    $$(prediction - target)^2$$

  • 均方誤差(MSE):

    $$avg[(prediction - target)^2]$$

將誤差平方:

  • 避免正負誤差互相抵消
  • 對大誤差給予更高懲罰
  • 在 PyTorch 中:
      criterion = nn.MSELoss()
    
Intermediate Deep Learning with PyTorch

擴展張量維度

  • 循環層期望輸入形狀為 (batch_size, seq_length, num_features)
  • 我們目前是 (batch_size, seq_length)
  • 需要在最後多加一個維度
for seqs, labels in dataloader_train:
    print(seqs.shape)
torch.Size([32, 96])
seqs = seqs.view(32, 96, 1)
print(seqs.shape)
torch.Size([32, 96, 1])
Intermediate Deep Learning with PyTorch

Squeeze 張量

  • 在評估迴圈中,需要還原訓練迴圈的重塑形狀
  • 標籤形狀為 (batch_size)

    for seqs, labels in test_loader:
      print(labels.shape)
    
    torch.Size([32])
    
  • 模型輸出為 (batch_size, 1)

    out = net(seqs)
    
    torch.Size([32, 1])
    
  • 損失函式需要模型輸出與標籤形狀一致
  • 可將模型輸出的最後一個維度去除

    out = net(seqs).squeeze()
    
    torch.Size([32])
    
Intermediate Deep Learning with PyTorch

訓練迴圈

net = Net()
criterion = nn.MSELoss()
optimizer = optim.Adam(
  net.parameters(), lr=0.001
)


for epoch in range(num_epochs): for seqs, labels in dataloader_train:
seqs = seqs.view(32, 96, 1)
outputs = net(seqs) loss = criterion(outputs, labels) optimizer.zero_grad() loss.backward() optimizer.step()
  • 建立模型、定義損失與最佳化器
  • 迭代 epochs 與資料批次
  • 重塑輸入序列
  • 其餘步驟:照常
Intermediate Deep Learning with PyTorch

評估迴圈

mse = torchmetrics.MeanSquaredError()


net.eval() with torch.no_grad(): for seqs, labels in test_loader:
seqs = seqs.view(32, 96, 1)
outputs = net(seqs).squeeze()
mse(outputs, labels)
print(f"Test MSE: {mse.compute()}")
Test MSE: 0.13292162120342255
  • 設定 MSE 指標
  • 在無梯度下遍歷測試資料
  • 重塑模型輸入
  • 對模型輸出做 squeeze
  • 更新指標
  • 計算最終指標值
Intermediate Deep Learning with PyTorch

LSTM 與 GRU 比較

  • LSTM:
Test MSE: 0.13292162120342255
  • GRU:
Test MSE: 0.12187089771032333
  • 傾向使用 GRU:效能相當或更好、運算量更少
Intermediate Deep Learning with PyTorch

一起來練習吧!

Intermediate Deep Learning with PyTorch

Preparing Video For Download...