龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > python编程 >

kNN算法python实现和简单数字识别的方法(2)

时间:2014-11-19 02:46来源:网络整理 作者:网络 点击:
分享到:
def img2vec(filename): returnVec = zeros((1,1024)) fr = open(filename) for i in range(32): lineStr = fr.readline() for j in range(32): returnVec[0,32*i+j] = int(lineStr[j]) return returnVec def handwr

def img2vec(filename):
    returnVec = zeros((1,1024))
    fr = open(filename)
    for i in range(32):
        lineStr = fr.readline()
        for j in range(32):
            returnVec[0,32*i+j] = int(lineStr[j])
    return returnVec
   
def handwritingClassTest(trainingFloder,testFloder,K):
    hwLabels = []
    trainingFileList = os.listdir(trainingFloder)
    m = len(trainingFileList)
    trainingMat = zeros((m,1024))
    for i in range(m):
        fileName = trainingFileList[i]
        fileStr = fileName.split('.')[0]
        classNumStr = int(fileStr.split('_')[0])
        hwLabels.append(classNumStr)
        trainingMat[i,:] = img2vec(trainingFloder+'/'+fileName)
    testFileList = os.listdir(testFloder)
    errorCount = 0.0
    mTest = len(testFileList)
    for i in range(mTest):
        fileName = testFileList[i]
        fileStr = fileName.split('.')[0]
        classNumStr = int(fileStr.split('_')[0])
        vectorUnderTest = img2vec(testFloder+'/'+fileName)
        classifierResult = kNNclassify(vectorUnderTest, trainingMat, hwLabels, K)
        #print classifierResult,' ',classNumStr
        if classifierResult != classNumStr:
            errorCount +=1
    print 'tatal error ',errorCount
    print 'error rate',errorCount/mTest
       
def main():
    t1 = time.clock()
    handwritingClassTest('trainingDigits','testDigits',3)
    t2 = time.clock()
    print 'execute ',t2-t1
if __name__=='__main__':
    main()

希望本文所述对大家的Python程序设计有所帮助。

精彩图集

赞助商链接