最初の学習ループを書く

PyTorchで学ぶIntroduction to Deep Learning

Jasmin Ludolf

Senior Data Science Content Developer, DataCamp

ニューラルネットワークの学習

  1. モデルを作成
  2. 損失関数を選択
  3. データセットを定義
  4. オプティマイザを設定
  5. 学習ループを実行:
    • 損失を計算(順伝播)
    • 勾配を計算(誤差逆伝播)
    • パラメータを更新
PyTorchで学ぶIntroduction to Deep Learning

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で学ぶIntroduction to Deep Learning

平均二乗誤差(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で学ぶIntroduction to Deep Learning

学習ループの前準備

# 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で学ぶIntroduction to Deep Learning

学習ループ

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で学ぶIntroduction to Deep Learning

練習しましょう!

PyTorchで学ぶIntroduction to Deep Learning

Preparing Video For Download...