Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python NumPy广播公司没有';行不通_Python_Arrays_Numpy_Array Broadcasting - Fatal编程技术网

Python NumPy广播公司没有';行不通

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

我试图广播两个向量之间的差异。这适用于以下简单情况:

[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]中: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