机器学习实战 笔记 debug kNN (三)

使用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集会小小影响结果


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值