プリンキピア

第4章分類のための線形ニューラルネットワーク

4.4.3. The Cross-Entropy Loss4.4.3 交差エントロピー損失

Next we need to implement the cross-entropy loss function (introduced in Section 4.1.2). This may be the most common loss function in all of deep learning. At the moment, applications of deep learning easily cast as classification problems far outnumber those better treated as regression problems.
英語のヒント
次に、交差エントロピー損失関数(4.1.2節で導入した)を実装する必要がある。これは深層学習全体で最もよく使われる損失関数かもしれない。今のところ、分類問題として容易に定式化できる深層学習の応用は、回帰問題として扱うほうがよいものよりもはるかに多い。
Recall that cross-entropy takes the negative log-likelihood of the predicted probability assigned to the true label. For efficiency we avoid Python for-loops and use indexing instead. In particular, the one-hot encoding in 𝐲 allows us to select the matching terms in 𝐲ˆ.
英語のヒント
交差エントロピーは、真のラベルに割り当てられた予測確率の負の対数尤度をとることを思い出してほしい。効率のために、Pythonのforループは避け、代わりに添え字による参照を使う。特に、𝐲のワンホット符号化を使えば、𝐲ˆの中で対応する項を選び出せる。
To see this in action we create sample data y_hat with 2 examples of predicted probabilities over 3 classes and their corresponding labels y. The correct labels are 0 and 2 respectively (i.e., the first and third class). Using y as the indices of the probabilities in y_hat, we can pick out terms efficiently.
英語のヒント
これが実際に働くところを見るため、3クラスにわたる予測確率の事例2個からなる標本データy_hatと、それに対応するラベルyを作る。正しいラベルはそれぞれ0と2(つまり1番目と3番目のクラス)である。yをy_hatの中の確率の添え字として使えば、項を効率よく選び出せる。
y = torch.tensor([0, 2])
y_hat = torch.tensor([[0.1, 0.3, 0.6], [0.3, 0.2, 0.5]])
y_hat[[0, 1], y]
tensor([0.1000, 0.5000])
Now we can implement the cross-entropy loss function by averaging over the logarithms of the selected probabilities.
英語のヒント
これで、選び出した確率の対数の平均をとることで、交差エントロピー損失関数を実装できる。
def cross_entropy(y_hat, y):
    return -torch.log(y_hat[list(range(len(y_hat))), y]).mean()

cross_entropy(y_hat, y)
tensor(1.4979)
@d2l.add_to_class(SoftmaxRegressionScratch)
def loss(self, y_hat, y):
    return cross_entropy(y_hat, y)