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

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

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