การเขียน training loop แรกของเรา

Deep Learning เบื้องต้นด้วย PyTorch

Jasmin Ludolf

Senior Data Science Content Developer, DataCamp

การเทรนโครงข่ายประสาทเทียม

  1. สร้างโมเดล
  2. เลือก loss function
  3. กำหนดชุดข้อมูล
  4. ตั้ง optimizer
  5. รัน training loop:
    • คำนวณ loss (forward pass)
    • คำนวณ gradient (backpropagation)
    • อัปเดตพารามิเตอร์ของโมเดล
Deep Learning เบื้องต้นด้วย PyTorch

แนะนำชุดข้อมูลเงินเดือน Data Science

 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

$$

  • Features: ประเภทหมวดหมู่, target: เงินเดือน (USD)
  • เลเยอร์ผลลัพธ์สุดท้าย: linear layer
  • Loss: เฉพาะสำหรับ regression
Deep Learning เบื้องต้นด้วย PyTorch

Mean Squared Error Loss

$$

  • MSE loss คือค่าเฉลี่ยของผลต่างกำลังสองระหว่างค่าพยากรณ์กับค่าจริง
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)
Deep Learning เบื้องต้นด้วย PyTorch

ก่อนเริ่ม training loop

# 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)
Deep Learning เบื้องต้นด้วย PyTorch

Training loop

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()
Deep Learning เบื้องต้นด้วย PyTorch

มาฝึกกันเถอะ!

Deep Learning เบื้องต้นด้วย PyTorch

Preparing Video For Download...