kNN算法python代码学习2-手写识别系统
2015-09-21 16:16
411 查看
构造的系统能识别数字0到9,已经将图像转换为文本格式。
为了使用之前构造的分类器,要将图像格式化处理为一个向量。
我们得到了分类器可以识别的数据格式,接下来就要将数据输入到分类器,对分类器的准确率进行测试:
命令行中输入:
测试结果为:
得到的错误率为1.16%。
提高计算效率?KD树
为了使用之前构造的分类器,要将图像格式化处理为一个向量。
def img2vector(filename): returnVect = zeros((1,1024)) fr = open(filename) for i in range(32): #图片大小为32*32 lineStr = fr.readline() for j in range(32): returnVect[0,32*i+j] = int(lineStr[j]) return returnVect
我们得到了分类器可以识别的数据格式,接下来就要将数据输入到分类器,对分类器的准确率进行测试:
def handwritingClassTest(): hwLabels = [] trainingFileList = listdir('trainingDigits')#使用此函数之前要将from os import listdir写在文件开头 m = len(trainingFileList) trainingMat = zeros((m,1024))#每一行代表一个图片数据 for i in range(m): fileNameStr = trainingFileList[i] fileStr = fileNameStr.split('.')[0] classNumStr = int(fileStr.split('_')[0]) #通过两次split获得分类数字(label) 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('testDigits/%s' % fileNameStr) classifierResult = classify0(vectorUnderTest, trainingMat, hwLabels, 3)#由于文件中的值都在0和1之间,所以不再需要归一化 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) <module 'kNN' from 'C:\Users\mrzhang\Desktop\prac\python\kNN.py'> >>> kNN.handwritingClassTest()
测试结果为:
the classifier came back with: 0, the real answer is: 0 the classifier came back with: 0, the real answer is: 0 .....省略一些 the classifier came back with: 9, the real answer is: 9 the classifier came back with: 9, the real answer is: 9 the total number of errors is: 11 the total error rate is: 0.011628
得到的错误率为1.16%。
提高计算效率?KD树
相关文章推荐
- python启动浏览器崩溃
- 【干货】前方高能!如何保障Python应用的高性能
- Python list(列表)实践
- Autorun a python script after reboot using rc.local
- 小甲鱼Python笔记(类)
- 【干货】前方高能!如何保障Python应用的高性能
- 【干货】前方高能!如何保障Python应用的高性能
- Python 3.5发布:新增模块,性能优化,对开发者更友好
- Ubuntu下安装python的torndb开发环境
- python例子-抓取网站IP列表
- Python博客
- python 字符串编程技巧
- wxpython核心部件wx.treectrl
- Selenium Python Safari for Mac 环境搭建
- python第三方库系列之二十五--pip库
- python socket编程详细介绍
- 2015/9/20 Python基础(16):类和实例
- 某Python群的入群题目
- 2015/9/19 Python基础(15):变量作用域及生成器
- 2015/9/18 Python基础(14):函数式编程