KNN识别手写体数字
首先准备好数据集,可以在网上下载好,用到的是目录ch02里的testDigits和trainingDigits
其具体步骤和理论参考机器学习实战 Maching Learning in Action
一些语法:
正则匹配
# coding=utf-8
from numpy import *
from os import listdir
import operator # 运算符模块,执行排序操作时将用到
import matplotlib.pyplot as plt
import re,time# 图像数据处理得到分类器可识别的格式
def img2vector(filename):# 创建一个行向量1*1024的数组,而不是单个1*1024的向量returnVect = zeros((1,1024))fr=open(filename,'r')for i in range(32):lineStr = fr.readline()for j in range(32):returnVect[0,32*i+j] = int(lineStr[j])#print returnVect[0,32*i+j]fr.close()return returnVect# 分类,参考上一篇KNN简单实现
def classify0(inX, dataSet, labels, k):dataSetSize = dataSet.shape[0]diffMat = tile(inX, (dataSetSize,1)) - dataSetsqDiffMat = diffMat**2sqDistances = sqDiffMat.sum(axis=1)distances = sqDistances**0.5sortedDistIndicies = distances.argsort() classCount={} for i in range(k):voteIlabel = labels[sortedDistIndicies[i]]classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True)return sortedClassCount[0][0]# 测试分类器的识别效果
def handwritingClassTest():hwLabels = []# listdir可以列出给定目录下的文件名trainingFileList = listdir('trainingDigits')# 得到训练集的文件个数m = len(trainingFileList)print 'Number of training data sets:', m# 创建m行数组存放格式化后的训练数据print '..training set Processing......'trainingMat = zeros((m,1024))for i in range(m):# 数字图像的文件名,要提取出其代表的数字,即标签 fileNameStr = trainingFileList[i]# 正则匹配#tt=re.match(r'(\d*)\_(\d*)(.txt)',fileNameStr).group(1)fileStr = fileNameStr.split('.')[0] classNumStr = int(fileStr.split('_')[0])# 得到标签listhwLabels.append(classNumStr)#print hwLabels#得到训练集数组,又学习了一种新的方法trainingMat[i,:] = img2vector('trainingDigits\%s' % fileNameStr)print 'Number of trainingMat..',trainingMat.shape[0]print '..trainingset procesing end'# 列出测试集文件testFileList = listdir('testDigits') #iterate through the test seterrorCount = 0.0mTest = len(testFileList)print 'Number of testing data sets:',mTestprint '..testing set Processing......'for i in range(mTest):fileNameStr = testFileList[i]fileStr = fileNameStr.split('.')[0] #take off .txtclassNumStr = 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#换行注释\nprint "\nthe total number of errors is: %d" % errorCountprint "\nthe total error rate is: %f" % (errorCount/float(mTest))if __name__== "__main__": start=time.time()handwritingClassTest()end=time.time()print '\nRunning time:',end-start
结果:
Number of training data sets: 1934
..training set Processing......
Number of trainingMat.. 1934
..trainingset procesing end
Number of testing data sets: 946
..testing set Processing......
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: 0, the real answer is: 0
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: 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 classifier came back with: 9, the real answer is: 9
the classifier came back with: 9, the real answer is: 9
the classifier came back with: 9, the real answer is: 9
the classifier came back with: 9, the real answer is: 9the total number of errors is: 11the total error rate is: 0.011628Running time: 29.5639998913
错误率为1.16%,耗时29
在其中遇到了一个问题:
就是使用open()函数时报错:
TypeError: an integer is required
查资料后:
错误是由于从os模块引入了所有的函数导致的,即“from os import *”
os模块下也有一个open函数,接受整型的文件描述符和打开模式,from os import *引入os模块的open函数,覆盖了python内建的open函数,导致错误。
修改from os import listdir 这行,即根据需要,指定引入os模块下的函数,尽量不要使用from module import *方式引入模块函数。
KNN识别手写体数字相关推荐
- svm手写数字识别python_SVM算法识别手写体数字
sklearn内部集成了一些手写体数字图片数据集,现在我们使用这些数据,用SVM支持向量机算法进行训练识别的练习.笔者习惯用pycharm,今天手痒,用一下Spyder编辑,顺便对比一下哪一个好用.废 ...
- python手机代码识别数字_python实现kNN算法识别手写体数字的示例代码
1.总体概要 kNN算法已经在上一篇博客中说明.对于要处理手写体数字,需要处理的点主要包括: (1)图片的预处理:将png,jpg等格式的图片转换成文本数据,本博客的思想是,利用图片的rgb16进制编 ...
- Pytorch识别手写体数字的简单实现
前言 人工智能学习相关博客: BackPropagation神经网络的学习与浅析 数据可视化相关博客: Pyecharts的实例使用 一般机器学习框架都使用MNIST作为入门.就像"Hell ...
- 手写体数字识别的两种方法
基于贝叶斯模型和KNN模型分别对手写体数字进行识别 首先,我们准备了0~9的训练集和测试集,这些手写体全部经过像素转换,用0,1表示,有颜色的区域为0,没有颜色的区域为1.实现代码如下: # 图片处理 ...
- 基于matlab的手写体数字识别系统
摘要:随着科学技术的发展,机器学习成为一大学科热门领域,是一门专门研究计算机怎样模拟或实现人类的学习行为的交叉学科.文章在matlab软件的基础上,利用BP神经网络算法完成手写体数字的识别. 机器学习 ...
- tensorflow学习笔记——手写体数字识别
使用tensorflow框架搭建全连接神经网络,用于识别手写体数字,希望对大家有帮助. import tensorflow as tf from tensorflow.examples.tutoria ...
- 并行化实现基于BP神经网络的手写体数字识别
并行化实现基于BP神经网络的手写体数字识别 手写体数字识别可以堪称是神经网络学习的"Hello World" ,我今天要说的是如何实现BP神经网络算法的并行化,我们仍然是以手写体数 ...
- python机器学习手写字体识别_Python 3 利用机器学习模型 进行手写体数字检测
0.引言 介绍了如何生成手写体数字的数据,提取特征,借助 sklearn 机器学习模型建模,进行识别手写体数字 1-9 模型的建立和测试. 用到的几种模型: 1. LR,Logistic Regres ...
- Python 3 利用机器学习模型 进行手写体数字检测
0.引言 介绍了如何生成手写体数字的数据,提取特征,借助 sklearn 机器学习模型建模,进行识别手写体数字 1-9 模型的建立和测试. 用到的几种模型: 1. LR,Logistic Regres ...
最新文章
- linux平台关闭某个进程的脚本
- PMCAFF网站和App改版啦!
- ByteBuffer 类
- 数据库压测 oracle,sysbench压测Oracle
- 自定义报表预览控制工具条
- 由浅到深理解ROS URDF教程
- 网站图片全自动加密_11 个值得收藏的在线工具和资源网站
- 鸿蒙历程及路标没有适配手机,鸿蒙2.0来了?华为开发者大会时间确认:Mate40会不会首发?...
- 当程序员写不出代码了,该怎么办?
- java怎么调用python_如何在Java中调用Python代码
- 树莓派python开发教程_树莓派Raspberry开发从基础到进阶视频+设计资料超详细教程下载...
- 系统分析师真题__专项:计算机系统与配置 2
- 软考高级 真题 2010年下半年 信息系统项目管理师 综合知识
- 云端地球:让每个人都能在线生成大场景三维
- 日本外贸市场开发攻略
- 驱动开发:Win10内核枚举SSDT表基址
- ATF:Gicv源码解读系列-gicv2_spis_configure_defaults
- Hash破解神器-hashcat详细使用
- 测试工程师应具备的素质
- 大长今》及主题歌五种版本欣赏