Pytorch / Numpy 维度数学:为什么 [n] + [n, 1] = [n, n]

Pytorch / Numpy dimensions math: Why [n] + [n, 1] = [n, n]

我试图理解在 numpy/torch 中推断加法语义的逻辑。这是一个在我的程序中导致错误的示例:

import numpy as np

x = np.arange(2)     # shape (2,)
y = x.reshape(-1, 1) # shape (2, 1)
z = y + x            # expected (2,) or (2, 1)
print(z.shape)       # (2, 2)

所以基本上重塑发生在不相关的操作中,但是 xy 仍然具有相同数量的元素,我希望得到结果形状 [2,] 或 [2, 1] 因为加法发生在所有元素所在的轴上。

我的问题:

  1. 为什么我得到 [2,2] 形状?
  2. 它背后有什么更大的图景可以帮助在类似但不同的情况下预期这一结果?

这是由broadcasting引起的,这里给出下面的例子:

x  = np.arange(4)   # shape (4,)
xx = x.reshape(4,1) # shape (4,1)
y  = np.ones(5)     # shape (5,)   

x + y  # ValueError: operands could not be broadcast together with shapes (4,) (5,)
xx + y  # shape (4, 5)

”当比较的维度之一为1时,使用另一个。换句话说,尺寸为1的维度被拉伸或“复制”以匹配另一个。