数组具有以下维度: 距离:(500,5000) 火车:(5000,) 测试:(500,)
为什么前两个语句抛出错误而第三个语句正常?
dists += 训练 + 测试
错误:ValueError:操作数无法与形状 (5000,) (500,) 一起广播
dists += train.reshape(-1,1) + test.reshape(-1,1)
错误:ValueError:操作数无法与形状 (5000,1) (500,1) 一起广播
dists += train + test.reshape(-1,1)这很好用!
为什么会这样?
请您参考如下方法:
这与 NumPy 的广播规则有关。引用 NumPy 手册:
When operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing dimensions, and works its way forward. Two dimensions are compatible when
- they are equal, or
- one of them is 1
第一个语句抛出错误,因为 NumPy 只看维度,(5000,) 和 (500,) 不相等,不能一起广播。
在第二个语句中,train.reshape(-1,1) 的形状为 (5000,1) 和 test.reshape(-1, 1) 的形状为 (500,1)。尾部维度(长度一)相等,所以没关系,但是 NumPy 检查另一个维度并且 5000 != 500,所以广播在这里失败。
在第三种情况下,您的操作数是(5000,) 和(500,1)。在这种情况下,NumPy 确实 允许广播。一维数组沿着二维数组的尾部 length-1 维度延伸。
FWIW,形状和广播规则有时会有点棘手,我经常被类似的事情弄糊涂。
