原文轉(zhuǎn)載自我的博客benym.cn
<center>示例 :使用k-近鄰算法的手寫(xiě)識(shí)別系統(tǒng)</center>
(1) 收集數(shù)據(jù):提供文本文件。
(2) 準(zhǔn)備數(shù)據(jù):編寫(xiě)函數(shù)classify0(), 將圖像格式轉(zhuǎn)換為分類器使用的list格式。
(3) 分析數(shù)據(jù):檢查數(shù)據(jù)馍盟,確保它符合要求铡恕。
(4) 訓(xùn)練算法:此步驟不適用于k-近鄰算法铁材。
(5) 測(cè)試算法:編寫(xiě)函數(shù)使用提供的部分?jǐn)?shù)據(jù)集作為測(cè)試樣本驯用,測(cè)試樣本與非測(cè)試樣本的區(qū)別在于測(cè)試樣本是已經(jīng)完成分類的數(shù)據(jù),如果預(yù)測(cè)分類與實(shí)際類別不同骂删,則標(biāo)記為一個(gè)錯(cuò)誤掌动。
(6) 使用算法:本例沒(méi)有完成此步驟,若你感興趣可以構(gòu)建完整的應(yīng)用程序宁玫,從圖像中提取數(shù)字粗恢,并完成數(shù)字識(shí)別,美國(guó)的郵件分揀系統(tǒng)就是一個(gè)實(shí)際運(yùn)行的類似系統(tǒng)欧瘪。
注:由于原本數(shù)據(jù)集已經(jīng)在0和1之間眷射,所以不需要轉(zhuǎn)化數(shù)字特征值。
代碼
from numpy import *
from os import listdir
import operator
def classify0(inX, dataSet, labels, k):
dataSetSize = dataSet.shape[0]
# 距離計(jì)算
'''
tile(A,rep)
功能:重復(fù)A的各個(gè)維度
參數(shù)類型:
A: Array類的都可以
rep:A沿著各個(gè)維度重復(fù)的次數(shù)
'''
diffMat = tile(inX, (dataSetSize, 1)) - dataSet
sqDiffMat = diffMat ** 2
# numpy中的 axis=0表示列,向下妖碉,axis=1表示行涌庭,向右
# 在平時(shí)使用的sun默認(rèn)的是axis=0就是普通的相加,當(dāng)加入axis=1以后就是將一個(gè)矩陣的每一行向量相加
sqDistances = sqDiffMat.sum(axis=1)
distances = sqDistances ** 0.5
# argsort函數(shù)返回的是數(shù)組值從小到大的索引值
sortedDistIndicies = distances.argsort()
classCount = {}
# 選擇距離最小的k個(gè)點(diǎn)
for i in range(k):
votellabel = labels[sortedDistIndicies[i]]
classCount[votellabel] = classCount.get(votellabel, 0) + 1
# 排序
sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)
return sortedClassCount[0][0]
def img2vector(filename):
# 將圖像矩陣轉(zhuǎn)化為1x1024的向量
returnVect = zeros((1, 1024))
fr = open(filename)
# 循環(huán)讀出文件的前32行
for i in range(32):
lineStr = fr.readline()
# 將每行的頭32個(gè)字符值存儲(chǔ)在Numpy數(shù)組中
for j in range(32):
returnVect[0, 32 * i + j] = int(lineStr[j])
# 返回?cái)?shù)組
return returnVect
def handwritingClassTest():
hwLabels = []
# 獲取訓(xùn)練數(shù)據(jù)集下目錄的所有文件名的列表
trainingFileList = listdir('trainingDigits')
# 得到文件數(shù)量
m = len(trainingFileList)
# 創(chuàng)建m行1024列的訓(xùn)練矩陣
trainingMat = zeros((m, 1024))
for i in range(m):
# 從文件名解析分類數(shù)字
# 解析出0_10.txt
fileNameStr = trainingFileList[i]
# 獲得0_10
fileStr = fileNameStr.split('.')[0]
# 獲得0
classNumStr = int(fileStr.split('_')[0])
hwLabels.append(classNumStr)
trainingMat[i, :] = img2vector('trainingDigits/%s' % fileNameStr)
# 獲得測(cè)試數(shù)據(jù)集下目錄的所有文件名的列表
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 errors is:%d" % errorCount)
print("\nthe total error rate is :%f" % (errorCount / float(mTest)))
testVector = img2vector('testDigits/0_13.txt')
# X[:, m:n]欧宜,即取二維數(shù)組中的第m到n-1列的所有數(shù)據(jù)
print("測(cè)試輸出:\n", testVector[0, 0:31])
handwritingClassTest()
運(yùn)行結(jié)果
the classifier came back with:1,the real answer is:1
the classifier came back with:1,the real answer is:1
.....
the classifier came back with:5,the real answer is:5
the classifier came back with:5,the real answer is:5
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:9,the real answer is:9
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
# 錯(cuò)誤率為1.2%
the total error rate is :0.011628