1.计算矩阵每个点与点之间的距离,返回距离矩阵
def cal_pairwise_dist(x):
'''计算pairwise 距离, x是matrix
(a-b)^2 + (c-d)^2= a^2 + b^2 - 2*a*b + c^2 + d^2 - 2*c*d
'''
x = np.array(x)
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
a = [[1,2],[3,4],[5,6]]
print(cal_pairwise_dist(a))
[[ 0 8 32]
[ 8 0 8]
[32 8 0]]
2.计算矩阵中n个邻近的点
def get_n_neighbors(data, n_neighbors=10):
'''
:param data: (n_samples, n_features)
:param n_neighbors: n nearest neighbors
:return: neighbors indexs
'''
dist = cal_pairwise_dist(data)
dist[dist < 0] = 0
dist = dist ** 0.5
n = dist.shape[0]
N = np.zeros((n, n_neighbors))
print("sdf")
for i in range(n):
index_ = np.argsort(dist[i])[1:n_neighbors + 1]
N[i] = N[i] + index_
return N.astype(np.int32)