运行环境:Python 3.6.0 |Anaconda 4.3.1 (64-bit)
手写识别系统
需要识别的数字已经处理成宽高均为32的黑白图像了。通过下面的函数将图形处理成一个向量去使用前面的分类器。
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
运行结果:
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.])
手写数字识别系统测试代码:
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] #去掉文件名字后缀
classNumStr = int(fileStr.split('_')[0]) #取文件名对应的数字
hwLabels.append(classNumStr)
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.0
print("\nthe total number of error is: %d" % errorCount)
print("\nthe total error rate is: %f" % (errorCount/float(mTest)))
运行结果:
The classifier came back with: 6, the real answer is: 6
The classifier came back with: 6, the real answer is: 6
.
.
The classifier came back with: 8, the real answer is: 8
The classifier came back with: 1, the real answer is: 8
the total number of error is: 13
the total error rate is: 0.013742
最后:
kNN算法优化:
如图所示,如果k取5,通过计算计算距离比较,将绿球划分为蓝色分组,但是实际情况是绿球和红球之间更紧凑,将其划分到红色更准确一些,所以可以通过对得到的欧氏距离进行加权,是算法更加准确。
更多优化:http://blog.csdn.net/lxj1229022827/article/details/45557349