numpy-在两个数组匹配的维度上广播操作

时间:2019-05-06 23:44:58

标签: python arrays python-3.x numpy vectorization

我有两个数组,xy,其中x.shape == (n, d)y.shape == (k, d)

我想产生一个数组z,其中z.shape == (n, k)z[i][j] = np.linalg.norm(x[i] - y[j])

是否有任何合理的矢量化方法来执行此操作?

1 个答案:

答案 0 :(得分:1)

您可以使用np.linalg.norm(np.expand_dims(x, 1) - y, axis=-1)

例如,

In [15]: d = 2                                                                                

In [16]: n = 3                                                                                

In [17]: k = 5                                                                                

In [18]: x = np.random.randint(0, 10, size=(n, d))                                            

In [19]: y = np.random.randint(0, 10, size=(k, d))                                            

In [20]: np.linalg.norm(np.expand_dims(x, 1) - y, axis=-1)                                    
Out[20]: 
array([[2.82842712, 5.        , 6.70820393, 4.        , 7.07106781],
       [8.94427191, 6.70820393, 1.        , 2.82842712, 7.07106781],
       [4.12310563, 3.16227766, 7.07106781, 5.38516481, 5.38516481]])

分别检查[0,0]和[2,3]的值:

In [21]: np.linalg.norm(x[0,:] - y[0,:])                                                      
Out[21]: 2.8284271247461903

In [22]: np.linalg.norm(x[2,:] - y[3,:])                                                      
Out[22]: 5.385164807134504