撰寫第一個訓練迴圈

使用 PyTorch 的深度學習入門

Jasmin Ludolf

Senior Data Science Content Developer, DataCamp

訓練神經網路

  1. 建立模型
  2. 選擇損失函式
  3. 定義資料集
  4. 設定最佳化器
  5. 執行訓練迴圈:
    • 計算損失(前向傳播)
    • 計算梯度(反向傳播)
    • 更新模型參數
使用 PyTorch 的深度學習入門

認識 Data Science Salary 資料集

 experience_level  employment_type  remote_ratio  company_size  salary_in_usd  
        0                0               0.5             1            0.036 
        1                0               1.0             2            0.133     
        2                0               0.0             1            0.234  
        1                0               1.0             0            0.076  
        2                0               1.0             1            0.170

$$

  • 特徵:類別型,目標:薪資(USD)
  • 最終輸出:線性層
  • 損失:回歸用
使用 PyTorch 的深度學習入門

均方誤差(MSE)損失

$$

  • MSE 是預測與真值之差的平方,取其平均
def mean_squared_loss(prediction, target):
  return np.mean((prediction - target)**2)

$$

  • 在 PyTorch 中:
criterion = nn.MSELoss()
# Prediction and target are float tensors
loss = criterion(prediction, target)
使用 PyTorch 的深度學習入門

進入訓練迴圈前

# Create the dataset and the dataloader
dataset = TensorDataset(torch.tensor(features).float(),
                        torch.tensor(target).float())


dataloader = DataLoader(dataset, batch_size=4, shuffle=True)
# Create the model model = nn.Sequential(nn.Linear(4, 2), nn.Linear(2, 1))
# Create the loss and optimizer criterion = nn.MSELoss() optimizer = optim.SGD(model.parameters(), lr=0.001)
使用 PyTorch 的深度學習入門

訓練迴圈

for epoch in range(num_epochs):

for data in dataloader:
# Set the gradients to zero optimizer.zero_grad()
# Get feature and target from the data loader feature, target = data
# Run a forward pass pred = model(feature) # Compute loss and gradients loss = criterion(pred, target) loss.backward()
# Update the parameters optimizer.step()
使用 PyTorch 的深度學習入門

一起來練習吧!

使用 PyTorch 的深度學習入門

Preparing Video For Download...