机器学习实战-读书笔记-k近邻算法

机器学习实战-读书笔记-k近邻算法
      前言 读研马上就半年了,终于把考试什么的事弄完了,可以静下心来学点东西了。最近才开始学习机器学习,刚刚买了一本《机器学习实战》和一本《统计学习方法》开始学习。刚刚看完了k近邻算法这一章,从原理和例子都弄了一遍,现把过程记录在这里,当做复习一遍,也可以供大家一起讨论学习。由于《机器学习实战》这本书是用python2.x版本写的,所以自己在运行的时候遇到很多小问题作为一个入门小白来说可以说被折腾的焦头烂额,现把3.x版本的代码贴出来供才开始学习的小伙伴交流学习。

1. k-近邻算法概述
       本书讲解的第一个机器学习算法是k-近邻算法(kNN),它的工作原理是:存在一个样本数
据集合,也称作训练样本集,并且样本集中每个数据都存在标签,即我们知道样本集中每一数据
与所属分类的对应关系。输入没有标签的新数据后,将新数据的每个特征与样本集中数据对应的
特征进行比较,然后算法提取样本集中特征最相似数据(最近邻)的分类标签。一般来说,我们
只选择样本数据集中前k个最相似的数据,这就是k-近邻算法中k的出处,通常k是不大于20的整数。
最后,选择k个最相似数据中出现次数最多的分类,作为新数据的分类。
        现在我们回到前面电影分类的例子,使用k-近邻算法分类爱情片和动作片。有人曾经统计过
很多电影的打斗镜头和接吻镜头,图2-1显示了6部电影的打斗和接吻镜头数。假如有一部未看过
的电影,如何确定它是爱情片还是动作片呢?我们可以使用kNN来解决这个问题。
    
    


       首先我们需要知道这个未知电影存在多少个打斗镜头和接吻镜头,图2-1中问号位置是该未
知电影出现的镜头数图形化展示,具体数字参见表2-1。
       即使不知道未知电影属于哪种类型,我们也可以通过某种方法计算出来。首先计算未知电影
与样本集中其他电影的距离,如表2-2所示。此处暂时不要关心如何计算得到这些距离值,使用
Python实现电影分类应用时,会提供具体的计算方法。
     现在我们得到了样本集中所有电影与未知电影的距离,按照距离递增排序,可以找到k个距
离最近的电影。假定k=3,则三个最靠近的电影依次是He’s Not Really into Dudes、Beautiful Woman
和California Man。k-近邻算法按照距离最近的三部电影的类型,决定未知电影的类型,而这三部
电影全是爱情片,因此我们判定未知电影是爱情片。
      
1.1 程序部分
 1.1.1 使用Python导入数据
import numpy as np   #导入mumpy模块,用于矩阵的计算
import operator      #导入operator模块,后面使用该模块的函数
def createDataSet():   #定义函数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):                       #定义名为classify0()的函数,计算测试集所属类别
    dataSetSize = dataSet.shape[0]                            #求矩阵dataSet的维度并把它赋值给dataSetSize
    diffMat = np.tile(inX, (dataSetSize,1)) - dataSet      #构造tile矩阵(为和dataSet形式相同的全零矩阵)减dataSet  
    sqDiffMat = diffMat**2                                 #把diffMat中的各个元素平方,赋值给sqDiffMat
    sqDistances = sqDiffMat.sum(axis=1)                 #把sqDiffMat每行的元素加起来作为一个元素,组成一行4列的矩阵
    distances = sqDistances**0.5                        #把矩阵的每个数开平方
    sortedDistIndicies = distances.argsort()            #把矩阵distances从小到大排列并提取对应的索引
    classCount={}                                       #占位
    for i in range(k):                                  #做一个循环k次的for循环
        voteIlabel = labels[sortedDistIndicies[i]]      #找出距离最近的k个数据对用的类别
        classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1  #
    sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)
    return sortedClassCount[0][0]
group,labels = createDataSet()               #把已知的数据载入
classify0([0,0],group,labels,3)              #输入测试数据,得出所属类别
'B'
1.2 示例:使用k—近邻算法改进约会网站的配对效果
import numpy as np          
import matplotlib.pyplot as plt     #导入matplotlib模块,用于绘图使用
import operator
def file(filename):                     #导入txt文件的数据
    fr = open(filename)
    numberOfLines = len(fr.readlines())         #get the number of lines in the file
    returnMat = np.zeros((numberOfLines,3))        #prepare matrix to return
    classLabelVector = []                       #prepare labels return   
    fr = open(filename)
    index = 0
    for line in fr.readlines():
        line = line.strip()
        listFromLine = line.split('\t')
        returnMat[index,:] = listFromLine[0:3]
        classLabelVector.append(int(listFromLine[-1]))
        index += 1
    return returnMat,classLabelVector               #输出两个矩阵
datingDataMat,datingLabels = file2matrix('datingTestSet2.txt')   #把datingTestSet2中的数据导入
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(datingDataMat[:,1],datingDataMat[:,2])
plt.show()                       #用使用Matplotlib创建散点图(使用datingDataMat矩阵的第二第三列)

def autoNorm(dataSet):      #归一化数据(使用newdata=(olddata-mindata)/(maxdata-mindata)把数据够归一化到0~1区域内)
    minVals = dataSet.min(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))   #element wise divide
    return normDataSet, ranges, minVals
normMat,ranges,minVals = autoNorm(datingDataMat)    #载入数据
def classify0(inX, dataSet, labels, k):
    dataSetSize = dataSet.shape[0]
    diffMat = np.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.items(), key=operator.itemgetter(1), reverse=True)
    return sortedClassCount[0][0]
def datingClassTest():
    hoRatio = 0.50      #hold out 10%
    datingDataMat,datingLabels = file2matrix('datingTestSet2.txt')       #load data setfrom file
    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)))
    print (errorCount)
datingClassTest()
the classifier came back with: 1, the real answer is: 1   #得出结果
the classifier came back with: 1, the real answer is: 1
the classifier came back with: 1, the real answer is: 1
the classifier came back with: 3, the real answer is: 3
the classifier came back with: 1, the real answer is: 1
the classifier came back with: 2, the real answer is: 1
the classifier came back with: 2, the real answer is: 2
the classifier came back with: 1, the real answer is: 1
the classifier came back with: 1, the real answer is: 1
the classifier came back with: 2, the real answer is: 2
the total error rate is: 0.064000
32.0



1.3 示例:手写识别系统
       本节我们一步步地构造使用k-近邻分类器的手写识别系统。为了简单起见,这里构造的系统只能识别数字0到9,参见图2-6。需要识别的数字已经使用图形处理软件,处理成具有相同的色彩和大小 :宽高是32像素×32像素的黑白图像。尽管采用文本格式存储图像不能有效地利用内存空间,但是为了方便理解,我们还是将图像转换为文本格式。
       手写识别系统设计步骤:
(1) 收集数据:提供文本文件。
(2) 准备数据:编写函数 classify0() ,将图像格式转换为分类器使用的list格式。
(3) 分析数据:在Python命令提示符中检查数据,确保它符合要求。
(4) 训练算法:此步骤不适用于k-近邻算法。
(5) 测试算法:编写函数使用提供的部分数据集作为测试样本,测试样本与非测试样本的区别在于测试样本是已经         完成分类的数据,如果预测分类与实际类别不同,则标记为一个错误。
(6) 使用算法:本例没有完成此步骤,若你感兴趣可以构建完整的应用程序,从图像中提取数字,并完成数字识别,美国的邮件分拣系统就是一个实际运行的类似系统。

程序部分
#导入几个模块
import numpy as np
import matplotlib.pyplot as plt
import operator
import os
def img2vector(filename):        #构造函数,把txt文件的数据转化成向量
    returnVect = np.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
def handwritingClassTest():
    hwLabels = []
    trainingFileList = os.listdir('trainingDigits')           #load the training set
    m = len(trainingFileList)
    trainingMat = np.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 = os.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)))
def classify0(inX, dataSet, labels, k):
    dataSetSize = dataSet.shape[0]
    diffMat = np.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.items(), key=operator.itemgetter(1), reverse=True)
    return sortedClassCount[0][0]
handwritingClassTest()

1.4 小结
       k-近邻算法是分类数据最简单最有效的算法,本章通过两个例子讲述了如何使用k-近邻算法
构造分类器。k-近邻算法是基于实例的学习,使用算法时我们必须有接近实际数据的训练样本数
据。k-近邻算法必须保存全部数据集,如果训练数据集的很大,必须使用大量的存储空间。此外,
由于必须对数据集中的每个数据计算距离值,实际使用时可能非常耗时。
       k-近邻算法的另一个缺陷是它无法给出任何数据的基础结构信息,因此我们也无法知晓平均
实例样本和典型实例样本具有什么特征。下一章我们将使用概率测量方法处理分类问题,该算法
可以解决这个问题。


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值