700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > KNN识别手写体数字

KNN识别手写体数字

时间:2021-08-20 21:53:11

相关推荐

KNN识别手写体数字

首先准备好数据集,可以在网上下载好,用到的是目录ch02里的testDigits和trainingDigits

其具体步骤和理论参考机器学习实战 Maching Learning in Action

一些语法:

正则匹配

# coding=utf-8from numpy import *from os import listdirimport operator # 运算符模块,执行排序操作时将用到import matplotlib.pyplot as pltimport 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 endNumber of testing data sets: 946..testing set Processing......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: 0the 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 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: 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 *方式引入模块函数。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。