損失関数で予測を評価する

PyTorchで学ぶIntroduction to Deep Learning

Jasmin Ludolf

Senior Data Science Content Developer, DataCamp

なぜ損失関数が必要か

  • 学習中にモデルの良さを評価
  • モデルの予測 $\hat{y}$ と正解 $y$ を入力
  • 出力は float

$$

損失関数の図

PyTorchで学ぶIntroduction to Deep Learning

なぜ損失関数が必要か

  • クラス0 - 哺乳類、クラス1 - 鳥類、クラス2 - 爬虫類
Hair Feathers Eggs Milk Fins Legs Tail Domestic Catsize Class
1 0 0 1 0 4 0 0 1 0

$$

  • 予測クラス = 0 -> 正解 = 損失小
  • 予測クラス = 1 -> 不正解 = 損失大
  • 予測クラス = 2 -> 不正解 = 損失大

$$

  • 目標は損失の最小化
PyTorchで学ぶIntroduction to Deep Learning

One-hot エンコーディングの基礎

  • $loss = F(y, \hat{y})$
  • $y$ は単一の整数(クラスラベル)
    • 例: 哺乳類なら $y=0$
  • $\hat{y}$ はテンソル(softmax 前の予測)
    • N はクラス数(例: N = 3)
    • $\hat{y}$ は N 次元のテンソル
      • 例: $\hat{y}$ = [-5.2, 4.6, 0.8]
PyTorchで学ぶIntroduction to Deep Learning

One-hot エンコーディングの基礎

  • 整数の y を 0/1 のテンソルへ変換

One-hot エンコーディング

PyTorchで学ぶIntroduction to Deep Learning

ラベルを one-hot に変換する

import torch.nn.functional as F

print(F.one_hot(torch.tensor(0), num_classes = 3))
tensor([1, 0, 0])
print(F.one_hot(torch.tensor(1), num_classes = 3))
tensor([0, 1, 0])
print(F.one_hot(torch.tensor(2), num_classes = 3))
tensor([0, 0, 1])
PyTorchで学ぶIntroduction to Deep Learning

PyTorch のクロスエントロピー損失

from torch.nn import CrossEntropyLoss

scores = torch.tensor([-5.2, 4.6, 0.8])
one_hot_target = torch.tensor([1, 0, 0])

criterion = CrossEntropyLoss()
print(criterion(scores.double(), one_hot_target.double()))

$$

tensor(9.8222, dtype=torch.float64)
PyTorchで学ぶIntroduction to Deep Learning

まとめ

損失関数の入力:

  • scores - 最後の softmax 前のモデル予測
  • one_hot_target - one-hot 符号化した正解ラベル

損失関数の出力:

  • loss - 単一の float

値入りの損失関数の図

PyTorchで学ぶIntroduction to Deep Learning

練習しましょう!

PyTorchで学ぶIntroduction to Deep Learning

Preparing Video For Download...