python - kNN - 如何根据计算的距离在训练矩阵中定位最近的邻居

标签 python numpy machine-learning knn

我正在尝试使用 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 中这些最近的项目吗?

最佳答案

我建议使用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 neighbors

关于python - kNN - 如何根据计算的距离在训练矩阵中定位最近的邻居,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40103226/

相关文章:

python - 有没有办法自动检测 Django 模板中的链接?

python - 如何从列中删除浮点值 - pandas

Python jaeger-client 跟踪器不报告重用

python - 使用 Python 进行高效重采样

python - 使用 numpy.random.multinomial 时如何避免值错误?

从字符串中提取信息的 Java 算法

python - 如何分析sklearn-pipeline的中间步骤?

python - 元素的列表比较

python - NumPy 的 transpose() 方法如何置换数组的轴?

machine-learning - 如何训练纯文本段落并返回关键短语?这可能吗?