我试图减去任意维度的ndarray的最小值。它似乎适用于3维,但不是4
3维案例:
mat1 = np.random.rand(10,5,2,1)
# mat1 is (10,5,2,1)
mat2 = mat1.min(axis = (1,2,3))
# mat2 is (10,)
(mat1 - mat2).shape == mat1.shape
# Should be True, but
#Output: False
4 Dimnesional Case:
{{1}}
答案 0 :(得分:2)
您的第一个示例具有误导性,因为所有尺寸都相同。这隐藏了你在第二次看到的那种错误。具有不同尺寸尺寸的示例可以更好地发现错误:
In [530]: x1 = np.arange(2*3*4).reshape(2,3,4)
In [531]: x2 = x1.min(axis=(1,2))
In [532]: x2.shape
Out[532]: (2,)
In [533]: x1-x2
...
ValueError: operands could not be broadcast together with shapes (2,3,4) (2,)
将其与我告诉它保持尺寸的情况相比较:
In [534]: x2 = x1.min(axis=(1,2),keepdims=True)
In [535]: x2.shape
Out[535]: (2, 1, 1)
In [536]: x1-x2
Out[536]:
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]]])
广播的基本规则:如果需要,a(2,)数组可以扩展为(1,1,2),但不能扩展到(2,1,1)。
但为什么第二种情况不会产生错误?
In [539]: mat1.shape
Out[539]: (10, 5, 2, 1)
In [540]: mat2.shape
Out[540]: (10,)
In [541]: (mat1-mat2).shape
Out[541]: (10, 5, 2, 10)
它的尾随大小为1,可以使用(10,):
进行广播(10,5,2,1) (10,) => (10,5,2,1)(1,1,1,10) => (10,5,2,10)
好像您已将newaxis
添加到3d数组中:
mat1 = np.random.rand(10,5,2)
mat1[...,None] - mat2