Python NumPy广播公司没有';行不通
我试图广播两个向量之间的差异。这适用于以下简单情况: [1]中的Python NumPy广播公司没有';行不通,python,arrays,numpy,array-broadcasting,Python,Arrays,Numpy,Array Broadcasting,我试图广播两个向量之间的差异。这适用于以下简单情况: [1]中的:data=np.array([1,2]) 在[2]中:centers=np.array([[2,2],[3,3]]) 在[3]:数据中心 Out[3]:数组([-1,0], [-2, -1]]) 但当我尝试做同样的事情,但在更大的维度上,这是行不通的 [4]中的:data=np.array([1,2],[3,4],[6,7]) 在[5]中:数据 Out[5]:数组([[1,2], [3,4], [6,7]]) 在[6]中:cen
:data=np.array([1,2])
在[2]中:centers=np.array([[2,2],[3,3]])
在[3]:数据中心
Out[3]:数组([-1,0],
[-2, -1]])
但当我尝试做同样的事情,但在更大的维度上,这是行不通的
[4]中的:data=np.array([1,2],[3,4],[6,7])
在[5]中:数据
Out[5]:数组([[1,2],
[3,4],
[6,7]])
在[6]中:centers=np.array([[2,2],[3,3])
在[7]中:中心
Out[7]:数组([[2,2],
[3,3]])
我想执行数据中心
,这样我就可以得到输出:
数组([-1,0],
[-2,-1]],
[[1,2],
[0,1]],
[[4,5],
[3,4]]]
在这种情况下,您需要在数据中插入一个额外的轴
:
>>> data[:, None] - centers
array([[[-1, 0],
[-2, -1]],
[[ 1, 2],
[ 0, 1]],
[[ 4, 5],
[ 3, 4]]])
最初数据。shape
是(3,2)
和中心。shape
是(2,2)
。NumPy无法将这些形状的数组一起广播,因为第一个轴的长度不兼容(它们需要相同的长度,或者其中一个轴需要1
)
插入额外尺寸,数据[:,无]
具有形状(3,1,2)
,然后轴的长度正确对齐:
(3, 1, 2)
(2, 2)
# #
# # lengths are equal for this axis
#
# 1 is compatible with any length