生成数据点的“K”近邻

2024-04-19 03:41:39 发布

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

给定一个数据点,我需要生成K个最近邻居。我读取了sklearn.neighbours module of sklearn,但它在两组数据之间生成了邻居。我想要的可能是一个100个最接近所传递数据点的数据点的列表。你知道吗

任何KNN算法都应该在引擎盖下找到这K个数据点。有没有办法把这些K点作为输出返回?你知道吗

这是我的sample notebook。你知道吗


Tags: of数据sample算法列表sklearnmodulenotebook
2条回答

你不需要看引擎盖下面。你知道吗

使用kd-tree for nearest-neighbor lookup。一旦索引准备好,就可以为k-NNs query索引。你知道吗

参考示例:

>>> from scipy import spatial
>>> x, y = np.mgrid[0:5, 2:8]
>>> tree = spatial.KDTree(list(zip(x.ravel(), y.ravel())))
>>> pts = np.array([[0, 0], [2.1, 2.9]])
>>> tree.query(pts)
(array([ 2.        ,  0.14142136]), array([ 0, 13]))
>>> tree.query(pts[0])
(2.0, 0)
from sklearn.neighbors import NearestNeighbors 

这可以提供数据集中k个最近邻居的索引。使用kneighbors,第一个值是距离,第二个值是邻居的索引。根据文件:

>>> samples = [[0., 0., 0.], [0., .5, 0.], [1., 1., .5]]
>>> from sklearn.neighbors import NearestNeighbors
>>> neigh = NearestNeighbors(n_neighbors=1)
>>> neigh.fit(samples) 
NearestNeighbors(algorithm='auto', leaf_size=30, ...)
>>> print(neigh.kneighbors([[1., 1., 1.]])) 
(array([[0.5]]), array([[2]]))

相关问题 更多 >