用導數來更新模型參數

使用 PyTorch 的深度學習入門

Jasmin Ludolf

Senior Data Science Content Developer, DataCamp

導數的類比

$$

導數代表曲線的「斜率」

$$

  • 斜率很陡(紅色箭頭):
    • 步伐大,導數很高
  • 斜率較緩(綠色箭頭):
    • 步伐小,導數很低
  • 谷底(藍色箭頭):
    • 平坦,導數為 0

$$

山谷示意圖

使用 PyTorch 的深度學習入門

凸與非凸函式

這是凸函式

凸函式範例

這是非凸函式

非凸函式範例,標出全域最小值

使用 PyTorch 的深度學習入門

連結導數與模型訓練

  • 訓練時在前向傳遞計算損失

$$ 計算損失

使用 PyTorch 的深度學習入門

連結導數與模型訓練

  • 梯度用來最小化損失,調整各層的權重與偏差
  • 重複直到各層都調好

$$ 計算梯度

使用 PyTorch 的深度學習入門

反向傳播概念

$$

  • 想像由三層組成的網路:

    • 從 $L2$ 的損失梯度開始
    • 用 $L2$ 來計算 $L1$ 的梯度
    • 對所有層重複($L1$、$L0$)

反向傳播示意圖

使用 PyTorch 的深度學習入門

PyTorch 中的反向傳播

# Run a forward pass 
model = nn.Sequential(nn.Linear(16, 8),
                      nn.Linear(8, 4),
                      nn.Linear(4, 2))
prediction = model(sample)


# Calculate the loss and gradients criterion = CrossEntropyLoss() loss = criterion(prediction, target) loss.backward()
# Access each layer's gradients
model[0].weight.grad
model[0].bias.grad
model[1].weight.grad
model[1].bias.grad
model[2].weight.grad
model[2].bias.grad
使用 PyTorch 的深度學習入門

手動更新模型參數

# Learning rate is typically small
lr = 0.001

# Update the weights
weight = model[0].weight
weight_grad = model[0].weight.grad


weight = weight - lr * weight_grad
# Update the biases bias = model[0].bias bias_grad = model[0].bias.grad
bias = bias - lr * bias_grad

$$

  • 讀取每層的梯度
  • 乘上學習率
  • 從權重中減去該乘積
使用 PyTorch 的深度學習入門

梯度下降

  • 對非凸函式,使用梯度下降

  • PyTorch 透過最佳化器簡化此事

    • 隨機梯度下降(SGD)
import torch.optim as optim

# Create the optimizer
optimizer = optim.SGD(model.parameters(), lr=0.001)

# Perform parameter updates optimizer.step()
使用 PyTorch 的深度學習入門

一起來練習吧!

使用 PyTorch 的深度學習入門

Preparing Video For Download...