import numpy as np
def cal_pairwise_dist(x):
"""
计算pairwise距离
:param x: 矩阵matrix
:return: 距离
"""
sum_x = np.sum(np.square(x), 1)
dist = np.add(np.add(-2 * np.dot(x, x.T), sum_x).T, sum_x)
return dist
比如有5个样本,每个样本有3个属性,那么就能组成5*3的矩阵X:
示例:
X = np.array([[1, 3, 6], [34, 21, 9], [13, 7, 24], [6, 31, 5], [33, 16, 32]])
dist = cal_pairwise_dist(X)
print(dist)
>>>[[ 0 1422 484 810 1869]
[1422 0 862 900 555]
[ 484 862 0 986 545]
[ 810 900 986 0 1683]
[1869 555 545 1683 0]]