Python skicit-learn k-最近邻 - 3D 距离矩阵

时间:2021-03-02 09:53:58

标签: python scikit-learn distance nearest-neighbor

我正在研究 3D 环境中数千个球形物体的距离。我使用 numpy 在球体之间创建了一个距离矩阵,并且最初想挑选出某些距离,例如在使用 k-最近算法之前,3D 环境中所有对象中最近的 5 个。有没有像 kneighbors 输出那样使用索引和值而不使用 k-nearest 算法的包?输入是一个预先计算的距离矩阵,包含每个球体到所有其他对象的所有距离。

1 个答案:

答案 0 :(得分:1)

通过将指标参数设置为“预计算”,您可以使用预先计算的距离矩阵作为 sklearn 的 neighbours.NearestNeighbors 的输入

让我们在某个 3D 空间(或任何维度空间)中的 6 个点之间创建一个虚拟距离矩阵。

from sklearn.neighbors import NearestNeighbors

#Distance matrix from numpy (dummy)
precomputed_distances = np.random.random((6,6)) 

#Get top 5 neighbours from precomputed distance matrix
nn = NearestNeighbors(n_neighbors=5, metric='precomputed')
nn.fit(precomputed_distances)

#Fetch kneighbors
distances, indexes = nn.kneighbors()

print(indexes)
print('')
print(distances)
#neighbours indexes
[[2 5 3 1 4]
 [0 4 3 2 5]
 [5 3 0 1 4]
 [1 2 4 0 5]
 [3 1 2 5 0]
 [3 2 0 1 4]]

#distances
[[0.07355072 0.30327092 0.32645641 0.54227088 0.76145093]
 [0.06451358 0.13867276 0.7570105  0.84383876 0.92184049]
 [0.52953184 0.59474913 0.63211483 0.80958676 0.99361867]
 [0.10885239 0.31822021 0.39327313 0.47670755 0.6764581 ]
 [0.18309627 0.69483384 0.74029263 0.82705113 0.92923248]
 [0.28584336 0.42956108 0.43323451 0.64124948 0.90154176]]

阅读有关此 here 的更多信息。