kNN算法python代碼學習2-手寫識別系統

構造的系統能識別數字0到9,已經將圖像轉換爲文本格式。

爲了使用之前構造的分類器,要將圖像格式化處理爲一個向量。

def img2vector(filename):
    returnVect = zeros((1,1024))
    fr = open(filename)
    for i in range(32): #圖片大小爲32*32
        lineStr = fr.readline()
        for j in range(32):
            returnVect[0,32*i+j] = int(lineStr[j])
    return returnVect

我們得到了分類器可以識別的數據格式,接下來就要將數據輸入到分類器,對分類器的準確率進行測試:

def handwritingClassTest():
    hwLabels = []
    trainingFileList = listdir('trainingDigits')#使用此函數之前要將from os import listdir寫在文件開頭
    m = len(trainingFileList)
    trainingMat = zeros((m,1024))#每一行代表一個圖片數據
    for i in range(m):
        fileNameStr = trainingFileList[i]
        fileStr = fileNameStr.split('.')[0]
        classNumStr = int(fileStr.split('_')[0]) #通過兩次split獲得分類數字(label)
        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)#由於文件中的值都在0和1之間,所以不再需要歸一化
        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))

命令行中輸入:

>>> reload(kNN)
<module 'kNN' from 'C:\Users\mrzhang\Desktop\prac\python\kNN.py'>
>>> kNN.handwritingClassTest()

測試結果爲:

the classifier came back with: 0, the real answer is: 0
the classifier came back with: 0, the real answer is: 0
.....省略一些
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: 11

the total error rate is: 0.011628

得到的錯誤率爲1.16%。

提高計算效率?KD樹


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章