其他分享
首页 > 其他分享> > Numpy 的广播机制高效计算矩阵之间两两距离

Numpy 的广播机制高效计算矩阵之间两两距离

作者:互联网

利用numpy可以很方便的计算两个二维数组之间的距离。二维数组之间的距离定义为:X的维度为(m, c),Y的维度为(m,c),Z为X到Y的距离数组,维度为(m,n)。且Z[0,0]是X[0]到Y[0]的距离。Z(a,b)为X[a]到Y[b]的距离。

例如: 计算 m*2 的矩阵 与  n * 2 的矩阵中,m*2 的每一行到  n*2 的两两之间欧氏距离。

'''
L2 = sqrt((x1-x2)^2 + (y1-y2)^2 + (z1-z2)^2)
'''

import numpy as np

# ============= 方法一:不用循环 ====================
def L2_dist_1(cloud1, cloud2):
    m, n = len(cloud1), len(cloud2)
    cloud1 = np.repeat(cloud1, n, axis=0)
    cloud1 = np.reshape(cloud1, (m, n, -1))
    dist = np.sqrt(np.sum((cloud1 - cloud2)**2, axis=2))
    return dist


# ============= 方法二:用一重循环 ==================
def L2_dist_2(cloud1, cloud2):
    m, n = len(cloud1), len(cloud2)
    dist = np.zeros((m, n), dtype=np.float)
    for i in range(m):
        dist[i, :] = np.sqrt(np.sum((cloud1[i, :] - cloud2)**2, axis=1)) 
    return dist


# ============= 方法二:用两重循环 ==================
def L2_dist_3(cloud1, cloud2):
    m, n = len(cloud1), len(cloud2)
    dist = np.zeros((m, n), dtype=np.float)
    for i in range(m):
        for j in range(n):
            dist[i, j] = np.sqrt(np.sum((cloud1[i, :] - cloud2[j, :])**2, axis=0)) 
    return dist


if __name__ == '__main__':
    a = np.array([[ 0, 0, 0],
                  [10,10,10],
                  [20,20,20],
                  [30,30,30]])

    b = np.array([[ 0, 0, 0],
                  [10,10,10]])

    print('不用循环:\n', L2_dist_1(a, b))
    print('用一重循环:\n', L2_dist_2(a, b))
    print('用两重循环:\n', L2_dist_3(a, b))

程序运行结果:

 

参考:Numpy 的广播机制高效计算矩阵之间两两距离

 

标签:10,dist,cloud2,cloud1,矩阵,广播,L2,np,Numpy
来源: https://www.cnblogs.com/picassooo/p/16655346.html