k临近(k-Nearest Neighbor)学习,是一种常用的监督学习方法
特点
优点:精度高、对异常之不敏感、无数据输入假定
缺点:计算复杂度高、空间复杂度高
使用数据范围:数值型和标称型
说明
k-NN没有显示的学习过程,是一lazy learning的代表,因为它有了数据集后没有所谓的“训练阶段”,并不首先对数据集中的样本进行处理和学习。
原理
存在由许多样本构成的数据集,包括许多特征值及其向量还有标签和标签值:
样本数据集(training set):{features:x, labels:y}
这样样本空间的维度就是features的个数,然后每个training sample就在样本空间中有一个对应坐标(向量)和其对应的label
给定测试样本t,只包含features信息,我们用某种方法计算出测试t和所有training sample的距离,将距离按照远近排序,然后选择所有距离中离得最近的前k个“邻居”,用前k个邻居的标签进行投票,哪个标签票数最高就认为测试样本t就属于该标签。
def classify0(inX, dataSet, labels, k): #程序中数据集包括 {dataSet,labels}
dataSetSize = dataSet.shape[0] #the m of matrix dateSet = #training sample [1]
#将测试样本inX“铺”为和dataSet一样的mxn矩阵,然后将测试样本t和所有训练样本作差(以矩阵的方式)
diffMat = tile(inX, (dataSetSize,1)) - dataSet
sqDiffMat = diffMat**2 #determine Euclid distance - squared
sqDistances = sqDiffMat.sum(axis=1) #determine Euclid distance - summation along axis 1
distances = sqDistances**0.5 #root of summation
sortedDistIndicies = distances.argsort() #重排序,为了方便找最近的k个neighbor
classCount={} #字典方便统计k个neighbor的投票
for i in range(k): #投票
voteIlabel = labels[sortedDistIndicies[i]]
classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1 #[2]
sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True)#[3]
return sortedClassCount[0][0]
reference
[1] numpy.arrary.shape、tile全都是numpy包的元素
[2] dict字典的get 方法:
get(key,[default])
Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.
如果键值key没有值,那么返回给的[default]值
classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1
比如例子里面如果没有查询到voteIlabel的对应键值就返回给定的参考值0
[3] [python-sorted]
sorted(iterable, *, key=None, reverse=False)
Return a new sorted list from the items in iterable.
将classCount字典分解为元组列表,然后使用operator.itemgetter方法按照第二个元素的次序对元组进行排序,排序为逆序(从大到小),然后返回发生频率最高的元素标签
参考书籍:机器学习实战、西瓜书