Python3:《机器学习实战》之k近邻算法(3)识别手写数字

来源:互联网 发布:数据字典怎么用 编辑:程序博客网 时间:2024/05/16 09:50

Python3:《机器学习实战》之k近邻算法(3)识别手写数字


  • 转载请注明作者和出处:http://blog.csdn.net/u011475210
  • 代码地址:https://github.com/WordZzzz/ML/tree/master/Ch02
  • 操作系统:WINDOWS 10
  • 软件版本:python-3.6.2-amd64
  • 编  者:WordZzzz

  • Python3机器学习实战之k近邻算法3识别手写数字
    • 前言
    • 一准备数据
    • 二测试算法
    • 三k-近邻算法总结

前言:

  在这篇博文里,本渣渣将带领大家一步一步构造出使用k-近邻分类器的手写识别系统。书中提供了数据集,从0到9,如图所示:

  这些数字已经经过处理,统一变成32像素*32像素的黑白图像(文本格式)。

  下面我们列出算法流程:

  • (1)收集数据:提供文本文件。
  • (2)准备数据:编写函数img2vector(),将图像格式装还未分类器实用的向量格式。
  • (3)分析数据:在Python命令提示符中检擦数据,确保它符合要求。
  • (4)训练算法:此步骤不适用于k-近邻算法。
  • (5)测试算法:编写函数使用提供的部分数据集作为测试样本,测试样本与非测试样本的区别在于测试样本是已经完成分类的数据,如果预测分类与实际类别不同,则标记为一个错误。
  • (6)使用算法:没有精力写应用程序了,爱折腾的大神们可以试试,自己以后复习的时候再写写这块。主要就是从图像中提取数字,并完成数字识别。

一、准备数据:

  世纪图像存储在源代码的两个子目录里:目录trainingDigits中包含了大约2000个例子,每个例子的内容如下图所示,每个数字大约有200个样本;目录testDigits中包含了大约900个测试数据。两组数据没有重叠。

  我们首先需要将图像转换成测试向量:即用一个1 * 1024的NumPy数组存储32 * 32的图像信息。

代码实现:

# -*- coding: UTF-8 -*-"""Created on Aug 18, 2017kNN: k Nearest NeighborsInput:      inX: vector to compare to existing dataset (1xN)            dataSet: size m data set of known vectors (NxM)            labels: data set labels (1xM vector)            k: number of neighbors to use for comparison (should be an odd number)Output:     the most popular class label@author: wordzzzz"""from numpy import *import operatorfrom os import listdir
def img2vector(filename):    """    Function:   32*32图像转换为1*1024向量    Args:       filename:文件名称字符串    Returns:    returnVect:转换之后的1*1024向量    """     #初始化要返回的1*1024向量    returnVect = zeros((1, 1024))    #打开文件    fr = open(filename)    #读取文件信息    for i in range(32):        #循环读取文件的前32行        lineStr = fr.readline()        for j in range(32):            #将每行的头32个字符存储到要返回的向量中            returnVect[0, 32*i+j] = int(lineStr[j])    #返回要输出的1*1024向量    return returnVect

输出结果:

>>> reload(kNN)>>> testVector = kNN.img2vector('testDigits/0_13.txt')>>> testVector[0,0:31]array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,        0.,  1.,  1.,  1.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,        0.,  0.,  0.,  0.,  0.])>>> testVector[0,32:63]array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,        1.,  1.,  1.,  1.,  1.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,        0.,  0.,  0.,  0.,  0.])

二、测试算法:

  在之前的kNN.py代码中加入from os import listdir,然后编写下列测试程序即可测试算法。

def handwritingClassTest():    """    Function:   手写数字测试程序    Args:       无    Returns:    returnVect:转换之后的1*1024向量    """     #初始化手写数字标签列表    hwLabels = []    #获取训练目录信息    trainingFileList = listdir('trainingDigits')    #获取训练文件数目    m = len(trainingFileList)    #初始化训练矩阵    trainingMat = zeros((m,1024))    #开始提取训练集    for i in range(m):        #从文件名解析出分类数字        fileNameStr = trainingFileList[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)    #开始测试    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.0    #输出错误技术    print("\nthe total number of errors is: %d" % errorCount)    #输出错误率    print("\nthe total error rate is: %f" % (errorCount/float(mTest)))

输出结果:

>>> reload(kNN)>>> kNN.handwritingClassTest()the classifier came back with: 0, the real answer is: 0the classifier came back with: 0, the real answer is: 0the classifier came back with: 0, the real answer is: 0······the classifier came back with: 9, the real answer is: 9the classifier came back with: 9, the real answer is: 9the classifier came back with: 9, the real answer is: 9the total number of errors is: 13the total error rate is: 0.013742

  k-近邻算法识别手写数字数据集,错误率为1.2%。依赖于分类算法、数据集和程序设置,分类器的输出结果可能有很大的不同。大家可以自行修改变量hoRatio和变量k的数值,看看检测错误率是否会发生变化。

  实际使用这个算法时,算法的执行效率并不高。因为算法需要为每个测试向量做2000次距离计算,而每个距离计算包括了1024个维度浮点运算,总计执行900次,此外,还需要为测试向量准备2MB的存储空间。以后要讲的k决策树科一节省大量的计算开销。

三、k-近邻算法总结:

优点:

  • k-近邻算法是分类数据最简单有效的算法,是基于实例的学习,使用算法时我们必须有接近实际数据的训练样本数据。

缺点:

  • k-近邻算法必须保存全部数据集,并对数据集中的每个数据计算距离值,实际使用时耗时耗存储。
  • 而且,它无法给出任何数据的基础结构信息,所以我们不知道平均实例样本与典型实例样本具有什么特征(概率测量方法处理分类问题时可以解决这个问题)。

系列教程持续发布中,欢迎订阅、关注、收藏、评论、点赞哦~~( ̄▽ ̄~)~

完的汪(∪。∪)。。。zzz

阅读全文
0 0
原创粉丝点击