其他分享
首页 > 其他分享> > 2021-09-09

2021-09-09

作者:互联网

经典k算法之识别数字:

这里不探讨怎么讲图片转换成为01代码的过程
建立在已经有32*32 = 1024的方形数据中
和一般的k近邻算法大致一样,但又几个地方需要注意
需要注意的是:
一是对于文件夹下文本文件的调用:
二是调用了新的包,即os库,用于实现listdir函数

import numpy as np
import operator
import os
def img2Vector(filename):
        returnVect = np.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

def classify0(inx,dataSet,lables,k):
        dataSetSize = dataSet.shape[0]
        diffMat = np.tile(inx,(dataSetSize,1)) - dataSet
        sqDiffMat = diffMat**2
        sqDistances  = sqDiffMat.sum(axis = 1)
        distances = sqDistances**0.5
        sortedDistIndicies = distances.argsort()
        classCount = {}
        for i in range(k):
                voteIlable = lables[sortedDistIndicies[i]]
                classCount[voteIlable] = classCount.get(voteIlable,0) + 1
        sortedClassCount = sorted(classCount.items(),
                                    key = operator.itemgetter(1),reverse = True)
        return sortedClassCount[0][0]

def handwritingClassTest():
        hwLables = []
        trainingFileList = os.listdir('trainingDigits')
        m = len(trainingFileList)
        trainingMat = np.zeros((m,1024))
        for i in range(m):
                fileNameStr = trainingFileList[i]
                fileStr = fileNameStr.split('.')[0]
                classNumStr = int(fileStr.split('_')[0])
                hwLables.append(classNumStr)
                trainingMat[i,:] = img2Vector('trainingDigits/%s' % fileNameStr)
        testFileList = os.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)
                classfierResult = classify0(vectorUnderTest,trainingMat,hwLables,3)
                #print("分类结果为:%s 真实结果为:%d\n" %(classfierResult,classNumStr))
                if(classfierResult != classNumStr):
                        errorCount+=1.0
        print("\n总共错了%d次",errorCount)
        print("\n错误率为 %.6f" % (errorCount/float(mTest)))
                















                

标签:09,fileStr,32,fileNameStr,range,2021,classNumStr,split
来源: https://blog.csdn.net/m0_46614914/article/details/120210389