使用k-近邻算法的手写识别系统
这里构造的系统只能识别数字0~9。
需要识别的数字已经使用图形处理软件,处理成具有相同的色彩和大小:宽高是32像素×32像素的黑白图像。
示例:使用k-近邻算法的手写识别系统步骤
(1)收集数据:提供文本文件。
(2)准备数据:编写函数classify0(),将图像格式转换为分类器使用的list格式。
(3)分析数据:在Python命令提示符中检查数据,确保它符合要求。
(4)训练数据:此步骤不适用于k-近邻算法。
(5)测试算法:编写函数使用提供的部分数据集作为测试样本,测试样本与非测试样本的区别在于测试样本是已经完成分类的数据,如果预测分类与实际类别不同,则标记为一个错误。
(6)使用算法:本例没有完成此步骤,若感兴趣可自己构建完整的应用程序,从图像中提取数字,并完成数字识别,美国的邮件分拣系统就是一个实际运行的类似系统。
准备数据:将图像转换为测试向量
为使用前面两个例子的分类器,需要将图像格式化处理为一个向量。我们将把一个32×32的二进制图像矩阵转换为1*1024的向量,这样前面使用的分类器就可以处理数字图像信息了。
首先,编写一个函数img2vector,将图像转换为向量,该函数创建一个1×1024的Numpy数组,然后打开给定的文件,循环读出文件的前32行,并将每行的头32个字符值存储在Numpy数组中,最后返回数组。
将以下添加到KNN.py文件中:
#将图像转换为向量
def img2vector(filename):
returnVector = zeros((1,1024))
fr = open(filename)
for i in range(32):
lineStr = fr.readline()
for j in range(32):
returnVector[0,32*i+j] = int(lineStr[j])
return returnVector
在Python命令行中输入下列命令测试img2vector函数:
In[2]: import kNN
Backend TkAgg is interactive backend. Turning interactive mode on.
In[3]: testVector = kNN.img2vector('testDigits/0_13.txt')
In[4]: testVector[0,0:31]
Out[4]:
array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 1., 1., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0.])
In[5]: testVector[0,32:63]
Out[5]:
array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.,
1., 1., 1., 1., 1., 1., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0.])
测试算法:使用k-近邻算法识别手写数字
将下面自包含函数handwritingClassTest()是测试测试分类器的代码,在此之前,文件的起始部分一定要加入from os import listdir,其主要功能是从os模块导入函数listdir,它可以列出给定目录的文件名。
#手写数字识别系统的测试代码
def handwritingClassTest():
hwLabels = []
#获取目录内容
trainingFileList = listdir('trainingDigits') #列出文件夹'trainingDigits'中所有文件的文件名
m = len(trainingFileList)
trainingMat = zeros((m,1024))
for i in range(m):
#从文件名解析分析数字
fileNameStr = trainingFileList[i]
fileStr = fileNameStr.split('.')[0] #将文件名用split('.')按照.分割,取第一部分
classNumStr = int(fileStr.split('_')[0])
hwLabels.append(classNumStr) #将标签数据存放在hwLabels向量中
trainingMat[i,:] = img2vector('trainingDigits/%s' %fileNameStr)
testFileList = 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,trainingMat,hwLabels,3)
print "the classifier came back with:%d, the real answer is: %d" %(classifierResult,classNumStr)
if (classifierResult != classNumStr): errorCount +=1
print "\nthe total number of errors is: %d" %errorCount
print "\nthe total error rate is: %f" %(errorCount/float(mTest))
结果输出:
In[20]: reload(kNN)
Out[20]:
<module 'kNN' from '/home/vickyleexy/PycharmProjects/handwriting_KNN/kNN.py'>
In[21]: kNN.handwritingClassTest()
the classifier came back with:6, the real answer is: 6
the classifier came back with:4, the real answer is: 4
the classifier came back with:6, the real answer is: 6
the classifier came back with:2, the real answer is: 2
the classifier came back with:5, the real answer is: 5
the classifier came back with:1, the real answer is: 1
the classifier came back with:3, the real answer is: 3
the classifier came back with:1, the real answer is: 1
the classifier came back with:2, the real answer is: 2
the classifier came back with:1, the real answer is: 1
the classifier came back with:1, the real answer is: 1
the classifier came back with:7, the real answer is: 7
the classifier came back with:0, the real answer is: 0
………………
the classifier came back with:5, the real answer is: 5
the classifier came back with:7, the real answer is: 7
the classifier came back with:9, the real answer is: 9
the classifier came back with:0, the real answer is: 0
the classifier came back with:8, the real answer is: 8
the classifier came back with:3, the real answer is: 3
the classifier came back with:7, the real answer is: 7
the total number of errors is: 11
the total error rate is: 0.011628
错误率为1.2%,改变变量k的值、修改函数handwritingClassTest()随机选取训练样本、改变训练样本的数目,都会对k-近邻算法的错误率产生影响。
调用手写识别系统
#手写字体识别的调用代码
def handwritingClass():
file = 'testDigits/0_2.txt' #mark 不知道怎么打开新的
Vector = img2vector(file)
trainingMat,hwLabels = handwritingClassTest()
classifierResult = classify0(Vector,trainingMat,hwLabels,3)
print "the handwriting number is :%d" %classifierResult