机器学习实战(第一章)---KNN算法
一.k-近邻算法函数分析
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): //取前k项
voteIlabel = labels[sortedDistIndicies[i]] //获取索引下标签(a/b)
classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1 //统计标签数量
sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True)
return sortedClassCount[0][0]
其中inX给出用于分类的输入向量,dataSet为输入样本集(列向量),labels标记处输入样本集对应的标签(列向量),k表示用于选择最近邻居的数目
1.shape函数用于产生矩阵或数组、元组。列表的维度的,shape[0]表行,shape[1]表列
2.sum(axis=1)函数表示按行求和,一般默认axis=0即默认列求和
3.argsort(a,axis,kind,order)函数为numpy包中排序函数,该函数返回排序后的元素索引值,其中的kind参数可选用quicksort、mergesort、heapsort排序方法,a为待排序表.tips:可采用argsort(-a)排序原表,所得到的也为原表的逆序----见
argsort说明
4.
operator模块提供的itemgetter函数用于获取对象的哪些维的数据,参数为一些序号,
operator.itemgetter函数获取的不是值,而是定义了一个函数
5.sorted() 函数返回列表,该应用中sortedClassCount为元组项列表
6.tile(A,reps)函数用于以reps指定维度重复元素A创建新数组,详细过程暂引用---
numpy包tile函数