使用k-近邻算法识别手写数字
def handwritingClassTest():
# 获取目录内容
hwLabels = []
trainingFileList = listdir('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 errors is: %d' %errorCount)
print('\nthe total error rate is: %f' %(errorCount/float(mTest)))
·Python格式化字符 %s %d %f
%s 字符串
%d 有符号整数(十进制)
%f 浮点数字(用小数点符号)
bug
NameError: name 'listdir' is not defined
需要from os import listdir 书里有提到
结果
。
。
。
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: 10
the total error rate is: 0.010571
·随机选取的test集会小小影响结果