第2章準備
2.3.7. Non-Reduction Sum2.3.7 縮約しない和
Sometimes it can be useful to keep the number of axes unchanged when invoking the function for calculating the sum or mean. This matters when we want to use the broadcast mechanism.
英語のヒント
和や平均を計算する関数を呼び出すとき、軸の数を変えずにおくと便利なことがある。これは、ブロードキャストの仕組みを使いたいときに大事になる。
sum_A = A.sum(axis=1, keepdims=True)
sum_A, sum_A.shape(tensor([[ 3.],
[12.]]),
torch.Size([2, 1]))For instance, since
sum_A keeps its two axes after summing each row, we can divide A by sum_A with broadcasting to create a matrix where each row sums up to .英語のヒント
たとえば、
sum_Aは各行の和をとった後も二つの軸を保っているので、ブロードキャストでAをsum_Aで割り、各行の和がになる行列を作れる。A / sum_Atensor([[0.0000, 0.3333, 0.6667],
[0.2500, 0.3333, 0.4167]])If we want to calculate the cumulative sum of elements of
A along some axis, say axis=0 (row by row), we can call the cumsum function. By design, this function does not reduce the input tensor along any axis.英語のヒント
ある軸、たとえば
axis=0(行ごと)に沿ってAの要素の累積和を計算したいなら、cumsum関数を呼び出せばよい。設計上、この関数はどの軸に沿っても入力テンソルを縮約しない。A.cumsum(axis=0)tensor([[0., 1., 2.],
[3., 5., 7.]])