Viết vòng lặp huấn luyện đầu tiên

Nhập môn Deep Learning với PyTorch

Jasmin Ludolf

Senior Data Science Content Developer, DataCamp

Huấn luyện mạng nơ-ron

  1. Tạo mô hình
  2. Chọn hàm mất mát
  3. Xác định tập dữ liệu
  4. Đặt bộ tối ưu
  5. Chạy vòng lặp huấn luyện:
    • Tính loss (lan truyền thuận)
    • Tính gradient (lan truyền ngược)
    • Cập nhật tham số mô hình
Nhập môn Deep Learning với PyTorch

Giới thiệu tập dữ liệu Lương Khoa học Dữ liệu

 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

$$

  • Đặc trưng: phân loại, mục tiêu: lương (USD)
  • Đầu ra cuối: lớp tuyến tính
  • Loss: dành cho hồi quy
Nhập môn Deep Learning với PyTorch

Hàm mất mát MSE

$$

  • MSE là trung bình bình phương chênh lệch giữa dự đoán và nhãn gốc
def mean_squared_loss(prediction, target):
  return np.mean((prediction - target)**2)

$$

  • trong PyTorch:
criterion = nn.MSELoss()
# Prediction and target are float tensors
loss = criterion(prediction, target)
Nhập môn Deep Learning với PyTorch

Trước vòng lặp huấn luyện

# 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)
Nhập môn Deep Learning với PyTorch

Vòng lặp huấn luyện

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()
Nhập môn Deep Learning với PyTorch

Hãy thực hành!

Nhập môn Deep Learning với PyTorch

Preparing Video For Download...