算法思想:
1. 计算所求向量距离已知向量的距离;
思想和二维思想一样。
2. 对所有距离进行排序,取前k个,统计各个标签出现的次数(总数为k) ; // {'A': 1, 'B': 2}
3. 统计后,对其进行排序; // [('B', 2), ('A', 1)
4. 返回第一个也就是距离最近的点的分类。// B
python实现:
#kNN.py
from numpy import *
import operator
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
def classify0(intX, dataSet, labels, k):
dataSetSize = dataSet.shape[0]
diffMat = tile(intX, (dataSetSize,1)) - dataSet
sqDiffMat = diffMat ** 2
sqDistances = sqDiffMat.sum(axis=1)
distances = sqDistances ** 0.5
sortedDistIndicies = distances.argsort()
classCount = {}
for i in range(k):
voteIlabel = labels[sortedDistIndicies[i]]
print voteIlabel
classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1
print classCount
sortedClassCount = sorted(classCount.iteritems(), key = operator.itemgetter(1),reverse=True)
print sortedClassCount
return sortedClassCount[0][0]
进入kNN.py的目录,执行python命令:
mac和linux系统直接cd到kNN.py的目录,执行python即可;
如果是windows则需要先进入到python.exe的目录,然后执行python,或者执行:c:\Python2.6\python.exe
import kNN
group,labels = kNN.createDataSet()
group 验证
## dataSetSize,diffMat = kNN.classify0([0,0], group, labels, 3)
a = kNN.classify0([0,0], group, labels, 3)
输出:
B
{'B': 1}
B
{'B': 2}
A
{'A': 1, 'B': 2}
[('B', 2), ('A', 1)]
代码及测试数据可见:https://github.com/zhongsb/machineLearning/tree/master
参考:《机器学习实战》[Peter Harrington]
关注博主微信号,获取更及时消息。