初识机器学习——k-近邻算法(3)

运行环境: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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值