k-Nearest Neighbors 简介

我在尝试按照一个关于k-Nearest Neighbors的例子进行学习,但我对numpy命令的语法不太确定。我应该进行矩阵级别的距离计算,提供的代码是

def classify(inputVector, trainingData,labels,k):     dataSetSize=trainingData.shape[0]     diffMat=tile(inputVector,(dataSetSize,1))-trainingData     sqDiffMat = diffMat**2     sqDistances = sqDiffMat.sum(axis=1)     distances = sqDistances**0.5     sortedDistIndicies = distances.argsort()     for i in range(k):    voteIlabel = labels[sortedDistIndicies[i]]    classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1    sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True)    return sortedClassCount[0][0]def createDataSet():     group = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])     labels = ['A','A','B','B']     return group, labels

我的问题是sqDistances**0.5如何等同于距离方程((A[0]-B[0])+(A[1]-B[1]))^1/2?我不明白tile是如何影响它的,特别是矩阵是如何从(datasetsize,1)-训练数据中生成的。


回答:

我希望下面的解释能帮助你理解其工作原理。

Numpy tile : https://docs.scipy.org/doc/numpy/reference/generated/numpy.tile.html

使用这个函数,你可以从输入向量创建一个与训练数据形状相同的矩阵。从这个矩阵中减去训练数据,你会得到你提到的部分,例如test[0]-train[0],即元素级别的差异。

然后,你通过使用diffMat**2对每个得到的元素进行平方运算,并沿axis = 1求和(https://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html)。这会产生类似(test[0] - train[0])^2 + (test[1] - train[1])^2的方程。

接下来,通过sqDistances**0.5,它将给出欧几里得距离。

要计算欧几里得距离,这可能会有帮助https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.euclidean.html#scipy.spatial.distance.euclidean

Related Posts

如何从数据集中移除EXIF数据?

我在尝试从数据集中的图像中移除EXIF数据(这些数据将…

用于Python中的“智能点”游戏的遗传算法不工作

过去几天我一直在尝试实现所谓的“智能点”游戏。我第一次…

哪个R平方得分更有帮助?

data.drop(‘Movie Title’, ax…

使用线性回归预测GRE分数对录取率的影响

我正在学习线性回归,并尝试在Jupyter笔记本中用P…

使用mlrMBO贝叶斯优化进行SVM超参数调优时出现错误

我试图针对一个分类任务优化SVM,这个方法在许多其他模…

Keras模型的二元交叉熵准确率未发生变化

我在网上看到了很多关于这个问题的提问,但没有找到明确的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注