k-近邻法用于手写识别系统
2016-05-14 18:59
323 查看
在上上篇”k-近邻分类算法“添加如下代码
测试
结果
错误率约1.2%
#将32*32图像矩阵转换为1*1024向量 def img2vector(filename): returnVect = zeros((1, 1024)) fr = open(filename) for i in range(32): lineStr = fr.readline() for j in range(32): returnVect[0, 32*i+j] = int(lineStr[j]) return returnVect #手写数字识别系统的测试代码 def handwritingClassTest(): hwLabels = [] trainingFileList = os.listdir('trainingDigits') #获取文件夹目录 m = len(trainingFileList) #文件夹下文件数 traingMat = zeros((m, 1024)) for i in range(m): #从文件名解析分类数字 fileNameStr = trainingFileList[i] fileStr = fileNameStr.split('.')[0] classNumStr = int(fileStr.split('_')[0]) hwLabels.append(classNumStr) traingMat[i,:] = img2vector('trainingDigits/%s' %fileNameStr) testFileList = os.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, traingMat, 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))
测试
>>> import KNN >>> handwritingClassTest()
结果
... ... 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: 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.2%
相关文章推荐
- DEDECMS之四 栏目调用
- 对象学习(一)
- RadioGroup控件与radioBtton控件
- PHP之——在WAMPSERVER下增加多版本的PHP(PHP5.3,PHP5.4,PHP5.5)支持。
- hdu 1262 寻找素数对(素数的判断,快速筛选素数)
- 消息摘要算法-SHA
- 笔试题55. LeetCode OJ (42)
- Leetcode:87. Scramble String
- 关于json对象和数组的访问的一些问题
- 快速查找注入点(转)
- 2016"百度之星" - 资格赛(Astar Round1)Problem B (大整数+组合数)
- <Spring>Spring MVC之@RequestBody, @ResponseBody 详解
- 钱咖助手-好玩的手机平台-免费开发尝试1
- 字典树
- 商业研究(17):以小见大,看互联网经济(4个股权众筹平台,4个领域,10个项目,8个图)
- 商业研究(17):以小见大,看互联网经济(4个股权众筹平台,4个领域,10个项目,8个图)
- 部分A+B
- input的checkbox多选框,全选、反选、不选的功能实现
- 商业研究(17):以小见大,看互联网经济(4个股权众筹平台,4个领域,10个项目,8个图)
- 二叉树的几种遍历递归与非递归java实现