机器学习实战之——KNN k-邻近算法

来源:互联网 发布:安全座椅品牌 知乎 编辑:程序博客网 时间:2024/04/30 06:14

主要内容

l  K-邻近分类算法——>使用距离测量的方法对物品分类

l  从文本文件中解析和导入数据

l  使用Matplotlib创建扩散图

l  归一化数值

 

1.    算法概述

这个算法非常有效,且易于掌握.

通过测量不同特征值之间的距离进行分类.

一个样本训练集,这个训练集中的每个数据都存在一个标签.(已知数据与数据所属分类).

输入新的数据后,新数据的每个特征与样本集中数据的特征进行比较,提取出新数据额标签值(即所属分类).

1.1      准备:Python导入数据

from numpy import * #导入NumPy数据包import operator     #导入运算符模块from os import listdirdef createDataSet(): #createDataSet函数,创建数据集和标签group =array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])labels=['A','A','B','B'] #labels包含每个数据点的标签信息return group,labels


1.2      实施KNN算法

 

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]]        classCount[voteIlabel]=classCount.get(voteIlabel,0)+1    sortedClassCount=sorted(classCount.iteritems(),                            key=operator.itemgetter(1),reverse=True)    return sortedClassCount[0][0]

1.3      如何测试分类器

不同算法在不同数据集上的表现可能完全不同。错误率用来评估分类器在某个数据集上的执行效果。

分类器的错误率=错误结果次数/测试执行的总数。

2.    算法在现实世界的应用

2.1准备数据:从文本文件中解析数据

#将文本记录仪转换为NumPy的解析程序#以此处理输入格式问题;        #输入文本为文件名 字符串        #输出为训练样本矩阵和类标签向量def file2matrix(filename):    fr=open(filename)    arrayOLines=fr.readlines()    numberOfLines=len(arrayOLines)    returnMat=zeros((numberOfLines,3))    classLabelVector=[]    index=0    for line in arrayOLines:        line=line.strip()#去除字符串首尾指定字符        listFormLine=line.split('\t')#按水平制表符对每行字符串进行切片        returnMat[index,:]=listFormLine[0:3]        classLabelVector.append(int(listFormLine[-1]))#python中可以使用索引值-1表示列表中的最后一列元素        index+=1    return returnMat,classLabelVector


2.2分析数据:使用Matplotlib创建散点图


 

如果只采用矩阵属性列1和2展示数据,产生的图像显示结果如下所示:


2.3准备数据:归一化数值

#归一化特征值def autoNorm(dataSet):    minVals=dataSet.min(0)    maxVals=dataSet.max(0)    ranges=maxVals-minVals    normDataSet=zeros(shape(dataSet))    m=dataSet.shape[0]    normDataSet=dataSet-tile(minVals,(m,1))    normDataSet=normDataSet/tile(ranges,(m,1))    return normDataSet,ranges,minVals

2.4测试算法:作为完整程序验证分类器

通常,我们将已有数据的90%作为训练样本来训练分类器,

10%数据去测试分类器,检测分类器的正确率。

程序中,定义一个计数器变量,每次分类器错误的分类数据,计数器加一。

程序完成后,计数器结果/数据点总数即错误率。

#测试分类器错误率def datingClassTest():    hoRatio=0.10    datingDataMzt,datingLabels=file2matrix('datingTestSet2.txt')    normMat,ranges,minVals=autoNorm(datingDataMat)    m=normMat.shape[0]    numTestVecs=int(m*hoRatio)    errorCount=0.0    for i in range(numTestVecs):        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))


结果输出:

>>>datingClassTest()

theclassifier came back with:3,the real answer is:3

theclassifier came back with:2,the real answer is:2

theclassifier came back with:1,the real answer is:1

the classifiercame back with:1,the real answer is:1

theclassifier came back with:1,the real answer is:1

theclassifier came back with:1,the real answer is:1

theclassifier came back with:3,the real answer is:3

theclassifier came back with:1,the real answer is:1

………………

theclassifier came back with:2,the real answer is:2

theclassifier came back with:1,the real answer is:1

theclassifier came back with:3,the real answer is:1

thetotal error rate is:0.050000

 

2.5使用算法:创建完整可用系统

#约会网站预测函数def classifyPerson():    resultList=['not at all','in small doses','in large doses']    percentTats=float(raw_input("percentage of time spent playing video games?"))    ffMiles=float(raw_input("frequent flier miles earned per year?"))    iceCream=float(raw_input("liters of ice creram consumed per year?"))    datingDataMat,datingLabels=file2matrix('datingTestSet2.txt')    normMat,ranges,minVals=autoNorm(datingDataMat)    inArr=array([ffMiles,percentTats,iceCream])    classifierResult=classify0((inArr-minVals)/ranges,normMat,datingLabels,3)    print "you will probably like this person: ",resultList[classifierResult -1]


控制台运行结果:

3.示例:手写识别系统

3.1准备数据:将图像转换为分类器可以识别的格式

两个文件:

trainingDigits(约2000个例子)训练分类器

testDigits(约900个例子)测试分类器

为了使用前面的kNN分类器,我们必须把每个图像的32*32矩阵转化为1*1024矩阵。

编写函数img2vector,将图像转化为向量:

①             先创建一个1*1024的NumPy数组

②             打开给定的文件,循环读出文件的前32行,同时将每行的前32个字符存储在NumPy数组中,

③             返回数组

代码示例:

#示例二:手写识别#将图像转换为测试向量def img2vector(filename):    returnVect=zeros((1,1024))    fr=open(filename)    for i in range(32):        lineStr=fr.readline()        for j in range(32):            returnVect[0,32*i+j]=int(lineStr[j])    return returnVect


3.2测试算法:使用knn算法识别手写数字

#手写数字识别系统的测试代码            def handwritingClassTest():    hwLabels = []    trainingFileList = listdir('trainingDigits')           #load the training set    m = len(trainingFileList)    trainingMat = zeros((m,1024))    for i in range(m):        fileNameStr = trainingFileList[i]        fileStr = fileNameStr.split('.')[0]     #take off .txt        classNumStr = int(fileStr.split('_')[0])        hwLabels.append(classNumStr)        trainingMat[i,:] = img2vector('trainingDigits/%s' % fileNameStr)    testFileList = listdir('testDigits')        #iterate through the test set    errorCount = 0.0    mTest = len(testFileList)    for i in range(mTest):        fileNameStr = testFileList[i]        fileStr = fileNameStr.split('.')[0]     #take off .txt        classNumStr = int(fileStr.split('_')[0])        vectorUnderTest = img2vector('testDigits/%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.0    print "\nthe total number of errors is: %d" % errorCount    print "\nthe total error rate is: %f" % (errorCount/float(mTest))  

测试结果:

…….

…….


但是,这个算法在这里的执行效率并不高,因为需要为每个测试向量做2000次距离计算,每次计算包含1024个维度浮点运算,总计要执行900次。此外,还需要为测试向量准备2MB的存储空间。

K决策树就是K邻近算法的优化版,可以大量节省计算开销。

4、小结

KNN是分类算法中最简单最有效算法。

缺点,空间、时间复杂度都非常大。需保存全部数据集,若训练数据集很大,需使用大量存储空间;必须对数据集中的每个数据计算距离值,实际使用时可能非常耗时。

使用该算法的前提是:必须要有接近实际数据的训练样本数据;足够大的存储空间(需保存全部数据集,若训练数据集很大,需使用大量存储空间)。

 

0 0