プリンキピア

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

4.4.1. The Softmax4.4.1 ソフトマックス

Let’s begin with the most important part: the mapping from scalars to probabilities. For a refresher, recall the operation of the sum operator along specific dimensions in a tensor, as discussed in Section 2.3.6 and Section 2.3.7. Given a matrix X we can sum over all elements (by default) or only over elements in the same axis. The axis variable lets us compute row and column sums:
英語のヒント
最も重要な部分、つまりスカラーから確率への写像から始めよう。おさらいとして、2.3.6節と2.3.7節で論じたように、テンソルの特定の次元に沿った和の演算子の働きを思い出してほしい。行列Xが与えられたとき、(既定では)すべての要素にわたって和をとることも、同じ軸の要素だけにわたって和をとることもできる。変数axisを使えば、行の和と列の和を計算できる。
X = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
X.sum(0, keepdims=True), X.sum(1, keepdims=True)
(tensor([[5., 7., 9.]]),
 tensor([[ 6.],
         [15.]]))
Computing the softmax requires three steps: (i) exponentiation of each term; (ii) a sum over each row to compute the normalization constant for each example; (iii) division of each row by its normalization constant, ensuring that the result sums to 1:
英語のヒント
ソフトマックスの計算には三つの段階がある。(i)各項を指数関数に通す。(ii)各行で和をとり、事例ごとの正規化定数を計算する。(iii)各行をその正規化定数で割り、結果の和が1になるようにする。
softmax(𝐗)ij=exp⁡(𝐗ij)∑kexp⁡(𝐗ik).(4.4.1)
The (logarithm of the) denominator is called the (log) partition function. It was introduced in statistical physics to sum over all possible states in a thermodynamic ensemble. The implementation is straightforward:
英語のヒント
分母(の対数)は(対数)分配関数と呼ばれる。これは統計物理学で、熱力学的なアンサンブルのとりうるすべての状態にわたって和をとるために導入された。実装は素直である。
def softmax(X):
    X_exp = torch.exp(X)
    partition = X_exp.sum(1, keepdims=True)
    return X_exp / partition  # The broadcasting mechanism is applied here
For any input X, we turn each element into a nonnegative number. Each row sums up to 1, as is required for a probability. Caution: the code above is not robust against very large or very small arguments. While it is sufficient to illustrate what is happening, you should not use this code verbatim for any serious purpose. Deep learning frameworks have such protections built in and we will be using the built-in softmax going forward.
英語のヒント
どんな入力Xについても、各要素を非負の数に変える。各行の和は、確率に求められるとおり1になる。注意:上のコードは、非常に大きい引数や非常に小さい引数に対して頑健ではない。何が起きているかを示すには十分だが、本格的な目的にこのコードをそのまま使うべきではない。深層学習のフレームワークにはこうした保護が組み込まれており、以降は組み込みのソフトマックスを使っていく。
X = torch.rand((2, 5))
X_prob = softmax(X)
X_prob, X_prob.sum(1)
(tensor([[0.2511, 0.1417, 0.1158, 0.2529, 0.2385],
         [0.2004, 0.1419, 0.1957, 0.2504, 0.2117]]),
 tensor([1., 1.]))