代码如下:
def classify0(inX, dataSet, labels, k):
dataSetSize = dataSet.shape[0]
diffMat = tile(inX, (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]]
classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1
sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True) return sortedClassCount[0][0]
代码注解:
【1】shape[0] 计算矩阵的行数,shape[1]计算矩阵的列数
【2】tile 数组inX以dataSetSize行1列重复,例如:intX 为[0, 0],则tile计算后
[0, 0]
[0, 0]
[0, 0]
[0, 0]
..... dataSetSize行
【3】** 是指次方, diffMat**2 为diffMat的平方, 比如[1, 2]**2 = [1, 4]
【4】sqDiffMat.sum(axis=1) 指array中每行元素的和,这些和再组成一个array:
例如: >>>a = array([[1, 2], [2, 4]])
>>>s = a.sum(axis=1)
>>>s
array([3, 6])
>>>a = array([[1, 2, 3], [2, 3, 4]])
>>>s = a.sum(axis=1)
>>>s
array([6, 9])
但是如果array只有一行,例如array([1, 2]), 则不能用sum(axis=1),只能用sum()
【5】classCount = {}新建一个dict, dict提供的get方法,如果key不存在,可以返回None,或者自己指定的value,这里classCount.get(voteIlabel, 0)是指不存在相对应key值的value则返回0
例如: >>> d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
>>> d['Michael']
95
>>> d['Thomas']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'Thomas'
要避免key不存在的错误,有两种办法,一是通过in判断key是否存在:
>>> 'Thomas' in d
False
二是通过dict提供的get方法,如果key不存在,可以返回None,或者自己指定的value:
>>> d.get('Thomas')
>>> d.get('Thomas', -1)
-1
【6】sorted() 按classCount字典的第2个元素(即类别出现的次数)从大到小排序
测试代码运行效果:
kNN.py文件:
from numpy import *import operatordef classify0(inX, dataSet, labels, k): dataSetSize = dataSet.shape[0] diffMat = tile(inX, (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]] 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
---------------------
作者:Jay_Xio
来源:CSDN
转载自http://blog.csdn.net/jay_xio https://blog.csdn.net/Jay_Xio/article/details/44340913