我知道在用sklearn拟合KNN模型后,可以像这样预测标签:
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=3)
knn.fit([3,1,4,3], [1,0,1,1)]
In: knn.predict([3])
Out: array([0])
但是,是否可以让KNN显示最近的邻居实际上是什么?用伪代码看起来像:
In: knn.show_nearest_neighbors([3], n_neighbors = 3)
Out: array([3,3,4])
最佳答案
您可以使用knn.kneighbors([[3]], n_neighbors=3, return_distance=False)
来获取邻居的索引:
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=3)
X = np.array([[3],[1],[4],[3]])
knn.fit(X, [1,0,1,1])
l = knn.kneighbors([[3]], n_neighbors=3, return_distance=False)
X[l].ravel()
它输出:
array([3, 3, 4])
。关于python - 显示sklearn KNN最近的邻居,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58905466/