从 scikit KNeighborsClassifier 打印最近邻居的标签?

Print labels of the nearest neighbours from scikit KNeighborsClassifier?

我正在使用 KNeighborsClassifier 算法训练我的数据,如下所示:

knn_clf = neighbors.KNeighborsClassifier(n_neighbors=3, 
algorithm="ball_tree", weights='distance')

我从以下位置获得了数据的最近 3 个邻居:

closest_distances = knn_clf.kneighbors(faces_encodings, n_neighbors=3)
print(closest_distances) #printouts: (array([[0.1123 , 0.29189484, 0.312]]

我想 link 这 3 个最近邻与标签的距离。有任何想法吗 ?

我的训练数据:X:[0.1,0.2,0.3,0.4,0.5] y:[一、二、三、四、五]。如果我给出预测(0.2),我如何 link 找到的距离的标签为二、三、四?

谢谢,

您不应该像您那样将 knn_clf.kneighbors 分配给单个变量 closest_distanceskneighbors 方法 returns two variables:

Returns:

dist : array

Array representing the lengths to points, only present if return_distance=True

ind : array

Indices of the nearest points in the population matrix.

所以,你应该给

closest_distances, indices = knn_clf.kneighbors(faces_encodings, n_neighbors=3)

并且 indices 变量将包含所需的索引。