过程
K-近邻算法的具体思想如下:
(1)计算已知类别数据集中的点与当前点之间的距离
(2)按照距离递增次序排序
(3)选取与当前点距离最小的k个点
(4)确定前k个点所在类别的出现频率
(5)返回前k个点中出现频率最高的类别作为当前点的预测分类
1.创建数据集
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
2.k-近邻算法
def classify0(inX, dataSet, labels, k):
dataSetSize = dataSet.shape[0]
diffMat = tile(inX, (dataSetSize, 1)) - dataSet
sqDiffMar = diffMat**2
sqDistance = sqDiffMar.sum(axis=1)
distance = sqDistance**0.5
sortedDist = distance.argsort()
classCount={}
for i in range(k):
votelabel = labels[sortedDist[i]]
classCount[votelabel] = classCount.get(votelabel, 0)+1
sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)
return sortedClassCount[0][0]
来源:CSDN
作者:深夜喝牛奶
链接:https://blog.csdn.net/weixin_43495111/article/details/104630649