プリンキピア

第2章準備

2.1.4. Broadcasting2.1.4 ブロードキャスト

By now, you know how to perform elementwise binary operations on two tensors of the same shape. Under certain conditions, even when shapes differ, we can still perform elementwise binary operations by invoking the broadcasting mechanism. Broadcasting works according to the following two-step procedure: (i) expand one or both arrays by copying elements along axes with length 1 so that after this transformation, the two tensors have the same shape; (ii) perform an elementwise operation on the resulting arrays.
英語のヒント
ここまでで、同じ形状の二つのテンソルに要素ごとの二項演算を行う方法がわかった。ある条件のもとでは、形状が違っていても、ブロードキャストの仕組みを使えば要素ごとの二項演算を行える。ブロードキャストは次の2段階の手順で働く。(i)長さ1の軸に沿って要素を複製して、一方または両方の配列を広げ、この変換の後で二つのテンソルが同じ形状になるようにする。(ii)得られた配列に要素ごとの演算を行う。
a = torch.arange(3).reshape((3, 1))
b = torch.arange(2).reshape((1, 2))
a, b
(tensor([[0],
         [1],
         [2]]),
 tensor([[0, 1]]))
Since a and b are 3×1 and 1×2 matrices, respectively, their shapes do not match up. Broadcasting produces a larger 3×2 matrix by replicating matrix a along the columns and matrix b along the rows before adding them elementwise.
英語のヒント
aとbはそれぞれ3×1と1×2の行列なので、形状が合わない。ブロードキャストは、行列aを列方向に、行列bを行方向に複製してから要素ごとに足し合わせることで、より大きな3×2の行列を作る。
a + b
tensor([[0, 1],
        [1, 2],
        [2, 3]])