python使用KNN算法手写体识别

yipeiwu_com5年前Python基础

本文实例为大家分享了用KNN算法手写体识别的具体代码,供大家参考,具体内容如下

#!/usr/bin/python 
#coding:utf-8 
 
import numpy as np 
import operator 
import matplotlib 
import matplotlib.pyplot as plt 
import os 
 
''''' 
KNN算法 
1. 计算已知类别数据集中的每个点依次执行与当前点的距离。 
2. 按照距离递增排序。 
3. 选取与当前点距离最小的k个点 
4. 确定前k个点所在类别的出现频率 
5. 返回前k个点出现频率最高的类别作为当前点的预测分类 
''' 
 
''''' 
inX为要分类的向量 
dataSet为训练样本 
labels为标签向量 
k为最近邻的个数 
''' 
def classify0(inX , dataSet , labels , k): 
 dataSetSize = dataSet.shape[0]#dataSetSize为训练样本的个数 
 diffMat = np.tile(inX , (dataSetSize , 1)) - dataSet#将inX扩展为dataSetSize行,1列 
 sqDiffMat = diffMat**2 
 sqDistances = sqDiffMat.sum(axis=1) 
 distances = sqDistances**0.5 
 sortedDistIndicies = distances.argsort()#返回的是元素从小到大排序后,该元素原来的索引值的序列 
 classCount = {} 
 for i in range(k): 
  voteIlabel = labels[sortedDistIndicies[i]]#voteIlabel为类别 
  classCount[voteIlabel] = classCount.get(voteIlabel,0)+1#如果之前这个voteIlabel是有的,那么就返回字典里这个voteIlabel里的值,如果没有就返回0 
 sortedClassCount = sorted(classCount.iteritems(),key=operator.itemgetter(1),reverse=True)#key=operator.itemgetter(1)的意思是按照字典里的第一个排序,{A:1,B:2},要按照第1个(AB是第0个),即‘1'‘2'排序。reverse=True是降序排序 
 print sortedClassCount 
 return sortedClassCount[0][0] 
 
 
''''' 
将图像转换为1*1024的向量 
''' 
def img2vector(filename): 
 returnVect = np.zeros((1,1024)) 
 fr = open(filename) 
 for i in range(32): 
  line = fr.readline() 
  for j in range(32): 
   returnVect[0,i*32+j] = int(line[j] ) 
 return returnVect 
 
''''' 
手写体识别系统测试 
''' 
def handwritingClassTest(trainFilePath,testFilePath): 
 hwLabels = [] 
 trainingFileList = os.listdir(trainFilePath) 
 m=len(trainingFileList) 
 trainSet = np.zeros((m,1024)) 
 for i in range(m): 
  filename = trainingFileList[i] 
  classNum = filename.split('.')[0] 
  classNum = int(classNum.split('_')[0]) 
  hwLabels.append(classNum) 
  trainSet[i] = img2vector( os.path.join(trainFilePath,filename) ) 
 testFileList = os.listdir(testFilePath) 
 errorCount = 0 
 mTest = len(testFileList) 
 for i in range(mTest): 
  filename = trainingFileList[i] 
  classNum = filename.split('.')[0] 
  classNum = int(classNum.split('_')[0]) 
  vectorUnderTest = img2vector(os.path.join(trainFilePath, filename)) 
  classifyNum = classify0(vectorUnderTest,trainSet,hwLabels,10) 
  print "the classifier came back with : %d , the real answer is : %d"% (classifyNum , classNum) 
  if(classifyNum != classNum) : errorCount+=1 
 print ("\nthe total number of error is : %d"%errorCount) 
 print ("\nthe error rate is : %f"%(float(errorCount)/mTest)) 
handwritingClassTest()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python实现查找excel里某一列重复数据并且剔除后打印的方法

本文实例讲述了python实现查找excel里某一列重复数据并且剔除后打印的方法。分享给大家供大家参考。具体分析如下: 在python里面excel的简单读写操作我这里推荐使用xlrd(...

Python使用回溯法子集树模板解决迷宫问题示例

Python使用回溯法子集树模板解决迷宫问题示例

本文实例讲述了Python使用回溯法解决迷宫问题。分享给大家供大家参考,具体如下: 问题 给定一个迷宫,入口已知。问是否有路径从入口到出口,若有则输出一条这样的路径。注意移动可以从上、下...

用python给自己做一款小说阅读器过程详解

用python给自己做一款小说阅读器过程详解

前言 前一段时间书荒的时候,在喜马拉雅APP发现一个主播播讲的小说-大王饶命。听起来感觉很好笑,挺有意思的,但是只有前200张是免费的,后面就要收费。一章两毛钱,本来是想要买一下,发现说...

Python入门Anaconda和Pycharm的安装和配置详解

Python入门Anaconda和Pycharm的安装和配置详解

子曰:“工欲善其事,必先利其器。”学习Python就需要有编译Python程序的软件,一般情况下,我们选择在Python官网下载对应版本的Python然后用记事本编写,再在终端进行编译运...

django 多数据库配置教程

在django项目中, 一个工程中存在多个APP应用很常见. 有时候希望不同的APP连接不同的数据库,这个时候需要建立多个数据库连接。 1. 修改项目的 settings 配置 在 s...