为什么以下操作数不能一起广播?

Ben*_*ict 6 python numpy python-3.x array-broadcasting

数组具有以下维度: dists: (500,5000) train: (5000,) test:(500,)

为什么前两个语句会抛出错误而第三个语句正常?

  1. dists += train + test

错误: ValueError: operands could not be broadcast together with shapes (5000,) (500,)

  1. dists += train.reshape(-1,1) + test.reshape(-1,1)

错误: ValueError: operands could not be broadcast together with shapes (5000,1) (500,1)

  1. dists += train + test.reshape(-1,1) 这工作正常!

为什么会发生这种情况?

Dro*_*nir 6

这与 NumPy 的广播规则有关。引用 NumPy 手册:

在对两个数组进行操作时,NumPy 按元素比较它们的形状。它从尾随维度开始,然后继续前进。当两个维度兼容时

  1. 他们是平等的,或者
  2. 其中之一是 1

第一条语句抛出错误,因为 NumPy 只看维度,and(5000,)和 and(500,)不相等,不能一起广播。

在第二个语句中,train.reshape(-1,1)has the shape(5000,1)并且test.reshape(-1,1)has the shape (500,1)。尾随维度(长度为一)是相等的,所以没关系,但随后 NumPy 检查另一个维度 和5000 != 500,因此广播在这里失败。

在第三种情况下,您的操作数是(5000,)(500,1)。在这种情况下,NumPy确实允许广播。一维数组沿二维数组的尾随长度 1 维度扩展。

FWIW,形状和广播规则有时可能有点棘手,我经常对类似的问题感到困惑。