我正在尝试用python实现k-最近邻算法。最后,我得到了以下代码。但是,我很难找到最近的邻居的索引。下面的函数将返回距离矩阵。但是,我需要在features_train (算法的输入矩阵)中获取这些邻居的索引。
def find_kNN(k, feature_matrix, query_house):
alldistances = np.sort(compute_distances(feature_matrix, query_house))
dist2kNN = alldistances[0:k+1]
for i in range(k,len(feature_matrix)):
dist = alldistances[i]
j = 0
#if there is closer neighbor
if dist < dist2kNN[k]:
#insert this new neighbor
for d in range(0, k):
if dist > dist2kNN[d]:
j = d + 1
dist2kNN = np.insert(dist2kNN, j, dist)
dist2kNN = dist2kNN[0: len(dist2kNN) - 1]
return dist2kNN
print find_kNN(4, features_train, features_test[2])产出如下:
[ 0.0028605 0.00322584 0.00350216 0.00359315 0.00391858]有人能帮我识别features_train中这些最近的项目吗?
发布于 2016-10-18 08:58:54
我建议使用python库sklearn,该库有一个KNeighborsClassifier,一旦安装,您就可以检索要查找的最近的邻居:
试试这个:
# Import
from sklearn.neighbors import KNeighborsClassifier
# Instanciate your classifier
neigh = KNeighborsClassifier(n_neighbors=4) #k=4 or whatever you want
# Fit your classifier
neigh.fit(X, y) # Where X is your training set and y is the training_output
# Get the neighbors
neigh.kneighbors(X_test, return_distance=False) # Where X_test is the sample or array of samples from which you want to get the k-nearest neighborshttps://stackoverflow.com/questions/40103226
复制相似问题