《机器学习实战》学习笔记——kNN近邻算法+注释详解

一、算法实现代码

import numpy as np
import operator
from os import listdir

#创建一个数据集例子
def createDataSet():
	group = np.array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])
	labels = ['A','A','B','B']
	return group,labels

#向量预测分类(构建分类器)
def classify0(inX,dataSet,labels,k):
    dataSetSize = dataSet.shape[0] #取出训练集矩阵的行数,即样本个数
    diffMat = np.tile(inX,(dataSetSize,1))-dataSet #1.将inX扩展成dataSetSize行1列的矩阵2.将扩展后的矩阵与dataSet相减,得到坐标之间的差值
    sqDiffMat = diffMat**2 #求diffMat中每个元素的平方
    sqDistances = sqDiffMat.sum(axis=1) #因为axis为1,所以求的是每个行中所有元素的和(axis=1:行运算;axis=0:列运算)
    distances = sqDistances**0.5#开根号,求inX与样本中每个元素的距离
    sortedDistIndicies = distances.argsort()#将距离由小到大排序,返回在已经排好序的矩阵中各元素在原来矩阵中的原始位置
    classCount = {}
    for i in range(k):
        voteIlabel = labels[sortedDistIndicies[i]] #获取与inX相对最小距离的元素在其原序列中的位置,并取出其对应的标签
        #get是取字典里的元素,如果之前这个voteIlabel是有的,那么就返回字典里这个voteIlabel键里的值,如果没有就返回0
        #算出离目标点距离最近的k个点的类别,这个点是哪个类别哪个类别就加1
        classCount[voteIlabel] = classCount.get(voteIlabel,0)+1
    #key=operator.itemgetter(1)的意思是按照字典里的‘值’进行排序,classCount字典里的数据样式类似于“{A:1,B:3}”。reverse=True是降序排序。
    #key=operator.itemgetter(0)表示按照字典里的键进行排序。
    sortedClassCount = sorted(classCount.items(),key=operator.itemgetter(1),reverse=True) 
    return sortedClassCount[0][0] #返回类别最多的类别

#从文本文件中提取训练数据
def file2matrix(filename):
    love_dictionary = {'largeDoses':3, 'smallDoses':2, 'didntLike':1}   #datingTestSet的标签
    fr = open(filename)
    arrayOLines = fr.readlines() #读取文件所有行
    numberOfLines = len(arrayOLines) #get the number of lines in the file 此长度即为样本个数
    returnMat = np.zeros((numberOfLines, 3)) #prepare matrix to return 构建样本集
    classLabelVector = [] #prepare labels return 构建样本标签
    index = 0
    for line in arrayOLines:
        line = line.strip() #去除样本的前后空格
        listFromLine = line.split('\t') #解析样本的特征值
        returnMat[index, :] = listFromLine[0:3] #存储样本
        #datingTestSet.txt is different datingTestSet2.txt in listFromLine[-1]
        #此处是为了区分datingTestSet.txt与datingTestSet2.txt
        if(listFromLine[-1].isdigit()):
            classLabelVector.append(int(listFromLine[-1]))
        else:
            classLabelVector.append(love_dictionary.get(listFromLine[-1]))
       # classLabelVector.append(int(listFromLine[-1]))
        index += 1
    return returnMat, classLabelVector #返回样本集与样本标签

#归一化特征(特征缩放)
def autoNorm(dataSet):	
	minVals = dataSet.min(0) #axis=0,列操作。获取每个特征的最小值
	maxVals = dataSet.max(0) #获取每个特征的最大值
	ranges  = maxVals-minVals #获取每个特征的数值区间
	normDataSet = np.zeros(np.shape(dataSet)) #构建和训练集同样大小的零矩阵
	m = dataSet.shape[0] #矩阵数据集的行数(样本的个数)
	normDataSet = dataSet - np.tile(minVals,(m,1)) #构建最小值矩阵,每一列为该特征的最小值。与训练集相减得到差值矩阵
	normDataSet = normDataSet / np.tile(ranges,(m,1)) #构建每个特征的区间矩阵,做除法得到归一化的矩阵
	return normDataSet,ranges,minVals #返回归一化样本训练集、每个特征的数值区间、每个特征的最小值

#分类器针对约会网站的测试代码
def datingClassTest():
    hoRatio = 0.1 #表示数据集的10%
    datingDataMat,datingLabels = file2matrix('datingTestSet.txt') #从文件中提取出数据集
    normMat,ranges,minVals = autoNorm(datingDataMat) #归一化数据集
    m = normMat.shape[0] #取出样本数量
    numTestVecs = int(m*hoRatio) #需要取出的样本个数
    errorCount = 0 #判断错误次数
    for i in range(numTestVecs):
        #0~numTestVecs为测试集 numTestVecs~m为训练集个数
        classifierResult = classify0(normMat[i,:],normMat[numTestVecs:m,:],datingLabels[numTestVecs:m],3)
    #打印预测结果
        print("The classifier came back with :%d,the real answer is :%d"%(classifierResult,datingLabels[i]))
        #判断是否错误
        if (classifierResult != datingLabels[i]):
            errorCount +=1.0
    print("the total error rate is: %f"%(errorCount/float(numTestVecs))) #打印错误率
#约会网站预测函数
def classifyPerson():
	resultList = ['not at all','in small doses','in large doses'] #约会情况分类
	percenTats = float(input("percentage of time spent playing video games:")) #游戏时间占比
	ffMiles = float(input("percentage of time flier miles earned per year:")) #每年飞行时间
	iceCream = float(input("liters of ice cream consumed per year:")) #冰淇淋公升数
	datingDataMat,datingLabels = file2matrix('datingTestSet2.txt') #获取数据集
	normMat,ranges,minVals = autoNorm(datingDataMat) #归一化数据
	inArr = np.array([ffMiles,percenTats,iceCream]) #建立样本向量
	classifierResult = classify0((inArr-minVals)/ranges,datingDataMat,datingLabels,3) #分类器分类
	print("You will probably like this person:",resultList[classifierResult-1]) #打印最终结果

#图像数据转化为向量
def img2vector(filename):
    returnVector = np.zeros((1,1024)) #建立存储图片的空矩阵
    fr = open(filename)
    #将图片矩阵数据转化为样本向量
    for i in range(32): #共有32行
        linestr = fr.readline() #readline()一次只读取一行
        for j in range(32): #读取一行中的每个元素
            returnVector[0,32*i+j] = int(linestr[j]) #将一个图片像素存储于图片向量
    return returnVector #返回图片向量

#手写数字识别系统的测试代码
def handwritingClassTest():
    hwLabels = [] #样本标签向量
    '''从训练集中获取训练数据'''
    trainingFileList = listdir('trainingDigits') #训练集文件夹名称
    m = len(trainingFileList) #训练的文件个数
    trainingMat = np.zeros((m,1024)) #图片向量
    for i in range(m):
        fileNameStr = trainingFileList[i] #获取第i个文件的名字
        fileStr = fileNameStr.split('.')[0]
        classNumStr = int(fileStr.split('_')[0]) #获取当前分类的数字
        hwLabels.append(classNumStr) #获取样本标签
        trainingMat[i,:] = img2vector('trainingDigits/%s'%fileNameStr) #获取样本向量
    '''获取测试集数据'''
    testFileList = listdir('testDigits')  # 测试集文件夹名称
    errorCount = 0.0 # 错误预测个数
    mTest = len(testFileList)  # 测试的文件个数
    testMat = np.zeros((mTest, 1024))  # 图片向量
    for i in range(mTest):
        fileNameStr = testFileList[i]
        fileStr = fileNameStr.split('.')[0]
        classNumStr = int(fileStr.split('_')[0])  # 获取当前分类的数字
        vectorUnderTest = img2vector('trainingDigits/%s' % fileNameStr)
        classifierResult = classify0(vectorUnderTest,trainingMat,hwLabels,3)
        print("the classifier came back with:%d,the real answer is:%d"%(classifierResult,classNumStr))
        if (classifierResult != classNumStr):
            errorCount += 1
    print("the total number of error is:%f"%errorCount) #错误次数
    print("the total error rate is:%f"%(errorCount/float(mTest))) #错误率

print("kNNTest import OK")

二、算法理解

1、def classify0(inX,dataSet,labels,k)

    这段代码实现功能的是对一个样本实例进行判断。具体流程如下:

(1)取出训练集(样本集)中所含样本的个数,即样本集的大小dataSetSize。

(2)将预测样本向量重复复制为一个矩阵,行数为dataSetSize,列为1,然后与dataSet做矩阵的减法。这样通过两个矩阵相减就可以得到预测向量inX与样本集中的每个样本的差值,并得到一个差值矩阵diffMat。

(3)对diffMat中的每个元素取平方,然后在对矩阵的行做加法运算,最后再对每个元素取根号。这样就可以求出预测样本向量与样本集中的每个样本的距离,并得到距离列表distance。

(4)对distance进行正向排序(不改变distance中的内容),返回在排好序的列表中每个元素其所在原始列表(distance)中的位置,得到一个索引列表sortedDistIndicies。

(5)依次取出索引列表中的每个索引值,找出该索引在标签列表labels中对应的标签。此标签即为预测向量inX的预测值。这是为什么呢?因为训练集中,样本矩阵中的每个样本与其标签列表中的值一一对应,换句话说,其索引值是相等的。而在距离列表distance中,每个元素又与样本矩阵和标签列表的顺序一一对应,距离列表中的第i个元素,恰好为预测向量与样本集中第i个样本之间的距离,对应标签列表中的第i个分类。

(6)将标签与匹配的个数存储于字典中,遍历整个距离列表,从小到大取出每个距离对应的标签,标签重复则+1,没有响应标签则0后再+1,这样最终就得到预测向量与样本集中每个元素之间的距离数(总共有k个)。

(7)将字典按照值进行逆序排序,取出第一个元素,因为是字典,所以是sortedClassCount[0][0]。

4、注意条目

    在最后排序中书中用classCount.iteritems()……此为Python2版本,在Python3中应改为classCount.items()。

  • 2
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值