kNN算法python实现和简单数字识别的方法(2)
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程序设计有所帮助。
- 上一篇:用python读写excel的方法
- 下一篇:决策树的python实现方法