第4章分類のための線形ニューラルネットワーク
4.3.2. Accuracy4.3.2 正解率
Given the predicted probability distribution
y_hat, we typically choose the class with the highest predicted probability whenever we must output a hard prediction. Indeed, many applications require that we make a choice. For instance, Gmail must categorize an email into “Primary”, “Social”, “Updates”, “Forums”, or “Spam”. It might estimate probabilities internally, but at the end of the day it has to choose one among the classes.英語のヒント
予測された確率分布
y_hatが与えられたとき、硬い予測を出力しなければならない場合には、ふつうは予測確率が最も高いクラスを選ぶ。実際、多くの応用では選択をすることが求められる。たとえばGmailは、メールを「メイン」「ソーシャル」「新着」「フォーラム」「迷惑メール」のどれかに分類しなければならない。内部では確率を推定しているかもしれないが、結局はクラスのなかから一つを選ばなければならない。When predictions are consistent with the label class
y, they are correct. The classification accuracy is the fraction of all predictions that are correct. Although it can be difficult to optimize accuracy directly (it is not differentiable), it is often the performance measure that we care about the most. It is often the relevant quantity in benchmarks. As such, we will nearly always report it when training classifiers.英語のヒント
予測がラベルのクラス
yと一致するとき、その予測は正しい。分類の正解率とは、すべての予測のうち正しいものの割合である。正解率を直接最適化するのは難しいことがあるが(微分できないので)、多くの場合、最も気にかける性能の尺度はこれである。ベンチマークでも、多くの場合これが意味のある量である。そのため、分類器を訓練するときには、ほぼいつも正解率を報告する。Accuracy is computed as follows. First, if
y_hat is a matrix, we assume that the second dimension stores prediction scores for each class. We use argmax to obtain the predicted class by the index for the largest entry in each row. Then we compare the predicted class with the ground truth y elementwise. Since the equality operator == is sensitive to data types, we convert y_hat’s data type to match that of y. The result is a tensor containing entries of 0 (false) and 1 (true). Taking the sum yields the number of correct predictions.英語のヒント
正解率は次のように計算する。まず、
y_hatが行列なら、2番目の次元に各クラスの予測得点が入っていると仮定する。argmaxを使い、各行で最大の成分の添え字によって予測されたクラスを得る。次に、予測されたクラスを正解yと成分ごとに比べる。等号演算子==はデータ型の違いに敏感なので、y_hatのデータ型をyのデータ型に合わせて変換する。結果は、0(偽)と1(真)を成分とするテンソルである。その和をとれば、正しい予測の数が得られる。@d2l.add_to_class(Classifier) #@save
def accuracy(self, Y_hat, Y, averaged=True):
"""Compute the number of correct predictions."""
Y_hat = Y_hat.reshape((-1, Y_hat.shape[-1]))
preds = Y_hat.argmax(axis=1).type(Y.dtype)
compare = (preds == Y.reshape(-1)).type(torch.float32)
return compare.mean() if averaged else compare