Python 学习笔记(Machine Learning In Action)K-近邻算法识别手写数字



1
from numpy import * 2 import matplotlib 3 from os import listdir 4 import kNN 5 def img2vector(filename): 6 returnVect = zeros((1,1024)) 7 fr = open(filename) 8 for i in range(32): 9 lineStr = fr.readline() 10 for j in range(32): 11 returnVect[0,32*i+j] = int(lineStr[j]) 12 return returnVect 13 def handwritingClassTest(): 14 hwLabels = [] 15 trainingFileList = listdir('trainingDigits') #load the training set 16 m = len(trainingFileList) 17 trainingMat = zeros((m,1024)) 18 for i in range(m): 19 fileNameStr = trainingFileList[i] 20 fileStr = fileNameStr.split('.')[0] #take off .txt 0_0.txt 将整个文件名以 . 分开 取第一部分也就是0_0 21 classNumStr = int(fileStr.split('_')[0]) #0_0 以 _ 分开 取第一部分也就是0 22 hwLabels.append(classNumStr) 23 trainingMat[i,:] = img2vector('trainingDigits/%s' % fileNameStr) 24 testFileList = listdir('testDigits') #iterate through the test set 25 errorCount = 0.0 26 mTest = len(testFileList) 27 for i in range(mTest): 28 fileNameStr = testFileList[i] 29 fileStr = fileNameStr.split('.')[0] #take off .txt 30 classNumStr = int(fileStr.split('_')[0]) 31 vectorUnderTest = img2vector('testDigits/%s' % fileNameStr) 32 classifierResult = kNN.classify0(vectorUnderTest, trainingMat, hwLabels, 3) 33 print "the classifier came back with: %d, the real answer is: %d" % (classifierResult, classNumStr) 34 if (classifierResult != classNumStr): errorCount += 1.0 35 print "\nthe total number of errors is: %d" % errorCount 36 print "\nthe total error rate is: %f" % (errorCount/float(mTest)) 37 handwritingClassTest()

转载于:https://www.cnblogs.com/wlc297984368/p/5766191.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值