使用numpy数组计算两类点中两两之间的L2距离
程序员文章站
2022-03-20 12:25:45
...
使用numpy数组计算两类点中两两之间的L2距离
def array_distance(arr1, arr2):
'''
计算两个数组里,每任意两个点之间的L2距离
arr1 和 arr2 都必须是numpy数组
且维度分别为 m x 2, n x 2
输出数组的维度为 m x n
'''
m, _ = arr1.shape
n, _ = arr2.shape
arr1_power = np.power(arr1, 2)
arr1_power_sum = arr1_power[:, 0] + arr1_power[:, 1]
arr1_power_sum = np.tile(arr1_power_sum, (n, 1))
arr1_power_sum = arr1_power_sum.T
arr2_power = np.power(arr2, 2)
arr2_power_sum = arr2_power[:, 0] + arr2_power[:, 1]
arr2_power_sum = np.tile(arr2_power_sum, (m, 1))
dis = arr1_power_sum + arr2_power_sum - (2 * np.dot(arr1, arr2.T))
return dis