编写第一个训练循环

使用 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 的深度学习入门

Passons à la pratique !

使用 PyTorch 的深度学习入门

Preparing Video For Download...