如何找到数据中所有点到kthnearest邻居的距离

2024-04-26 09:31:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我们有一个形状为(10000, 1500)的矩阵X。 我们拿k = 9。 我们要找出从X的每个点到X的第9个最近点的距离

是否存在此任务的函数或库。你知道吗

def k_nearest_distances(X, k){
return d
} 

d应该是长度为10000的数组。其中,索引i处的每个值表示到k-最近点形式X[i]的距离。你知道吗


Tags: 函数距离returndef矩阵数组形式形状
1条回答
网友
1楼 · 发布于 2024-04-26 09:31:18

好的,我用sklearn库找到解决方案,最近邻使用下面的代码

k = 9
# importing NearestNeighbors class 
from sklearn.neighbors import NearestNeighbors
# initialize model
neigh = NearestNeighbors(n_neighbors=k, n_jobs=-1)
# train for getting nearest neighbour
neigh.fit(X)
dist, ind = neigh.kneighbors(X)
# We have no use of indices here
# dist is a 2 dimensional array of shape (10000, 9) in which each row is list of length 9. This row contain distances to all 9 nearest points. But we need distance to only 9th nearest point. So
distances = [dist[i][k - 1] for i in range(len(dist))]

相关问题 更多 >