プリンキピア

第2章準備

2.3.6. Reduction2.3.6 縮約

Often, we wish to calculate the sum of a tensor’s elements. To express the sum of the elements in a vector 𝐱 of length n, we write ∑i=1nxi. There is a simple function for it:
英語のヒント
テンソルの要素の和を計算したいことはよくある。長さnのベクトル𝐱の要素の和を表すには、∑i=1nxiと書く。そのための簡単な関数がある。
x = torch.arange(3, dtype=torch.float32)
x, x.sum()
(tensor([0., 1., 2.]), tensor(3.))
To express sums over the elements of tensors of arbitrary shape, we simply sum over all its axes. For example, the sum of the elements of an m×n matrix 𝐀 could be written ∑i=1m∑j=1naij.
英語のヒント
任意の形状のテンソルの要素の和を表すには、すべての軸について和をとればよい。たとえば、m×nの行列𝐀の要素の和は∑i=1m∑j=1naijと書ける。
A.shape, A.sum()
(torch.Size([2, 3]), tensor(15.))
By default, invoking the sum function reduces a tensor along all of its axes, eventually producing a scalar. Our libraries also allow us to specify the axes along which the tensor should be reduced. To sum over all elements along the rows (axis 0), we specify axis=0 in sum. Since the input matrix reduces along axis 0 to generate the output vector, this axis is missing from the shape of the output.
英語のヒント
既定では、和を求める関数を呼び出すと、テンソルはすべての軸に沿って縮約され、最終的にスカラーになる。私たちのライブラリでは、テンソルを縮約する軸を指定することもできる。行(軸0)に沿ってすべての要素の和をとるには、sumでaxis=0を指定する。入力の行列は軸0に沿って縮約されて出力のベクトルになるので、この軸は出力の形状から消える。
A.shape, A.sum(axis=0).shape
(torch.Size([2, 3]), torch.Size([3]))
Specifying axis=1 will reduce the column dimension (axis 1) by summing up elements of all the columns.
英語のヒント
axis=1を指定すると、すべての列の要素を足し合わせて、列の次元(軸1)を縮約する。
A.shape, A.sum(axis=1).shape
(torch.Size([2, 3]), torch.Size([2]))
Reducing a matrix along both rows and columns via summation is equivalent to summing up all the elements of the matrix.
英語のヒント
行と列の両方に沿って和で縮約することは、行列のすべての要素を足し合わせることと同じである。
A.sum(axis=[0, 1]) == A.sum()  # Same as A.sum()
tensor(True)
A related quantity is the mean, also called the average. We calculate the mean by dividing the sum by the total number of elements. Because computing the mean is so common, it gets a dedicated library function that works analogously to sum.
英語のヒント
関連する量に平均がある。平均は、和を要素の総数で割って求める。平均の計算はとてもよく使うので、sumと同じように働く専用のライブラリ関数がある。
A.mean(), A.sum() / A.numel()
(tensor(2.5000), tensor(2.5000))
Likewise, the function for calculating the mean can also reduce a tensor along specific axes.
英語のヒント
同様に、平均を計算する関数も、特定の軸に沿ってテンソルを縮約できる。
A.mean(axis=0), A.sum(axis=0) / A.shape[0]
(tensor([1.5000, 2.5000, 3.5000]), tensor([1.5000, 2.5000, 3.5000]))