k近鄰優點:精度高、對異常值不敏感、無資料輸入假定;
k近鄰缺點:計算複雜度高、空間複雜度高
import numpy as np
import operator
from os import listdir
# k近鄰分類器
def classify0(inx, dataSet, labels, k):
dataSetSize = dataSet.shape[0] # 返回dataset第一維的長度,也就是行數
diffMat = np.tile(inx, (dataSetSize, 1))-dataSet # tile表示把inx行向量按列方向重複datasetsize次
sqDiffMat = diffMat**2
sqDistances = sqDiffMat.sum(axis=1) # 按列求和
distances = sqDistances**0.5
sortedDistIndicies = distances.argsort() # 返回的是陣列從小到大的索引值
classCount = {} # 定義一個空字典
for i in range(k):
voteLabel = labels[sortedDistIndicies[i]] # 返回前k個距離最小的樣本的標籤值
classCount[voteLabel] = classCount.get(voteLabel, 0)+1 # get 表示返回指定鍵的值
# lambda表示輸入classCount返回冒號右邊的值,reverse=True表示按照降序排列
sortedClassCount=sorted(classCount.items(), key=lambda classCount: classCount[1], reverse=True)
return sortedClassCount[0][0]
# 把.txt檔案轉換成矩陣形式
def file2matrix(file):
file = open(file) # 返回檔案物件
arr = file.readlines() # 返回全部行,是list形式,每一行為list的一個元素
number = len(arr) # 返回物件長度
returnMat = np.zeros((number,3))
index = 0
labelMat = []
for line in arr:
#line = line.strip(`
`)
#newline = line.split(` `)
newline = line.strip(`
`).split(` `) # 處理逐行資料,strip表示把頭尾的`
`去掉,split表示以空格來分割行資料
# 然後把處理後的行資料返回到newline列表中
returnMat[index,:] = newline[0:3] #表示列表的0,1,2列資料放到index行中
labelMat.append(int(newline[-1]))
index+=1
return returnMat,labelMat
# 歸一化
def autoNorm(dataSet):
minVals = dataSet.min(0)
maxVals = dataSet.max(0)
ranges = maxVals-minVals
normDataSet = np.zeros(np.shape(dataSet))
m = normDataSet.shape[0]
A = normDataSet
A = np.tile(minVals, (m,1))
normDataSet = dataSet-A
normDataSet = normDataSet/np.tile(ranges,(m,1))
return normDataSet
# 把影像轉化成向量的形式
def img2vector(filename):
returnVect = np.zeros((1,1024))
fr = open(filename)
for i in range(32):
lineStr = fr.readline() # readline()表示從首行開始,每次讀取一行
for j in range(32):
returnVect[0,32*i+j] = int(lineStr[j]) #int()函式用於將一個字串或數字轉換成整型
return returnVect # 一張圖片轉化成一行後的陣列
# 手寫數字識別系統的測試程式碼
def handwritingClassTest():
hwLabels = []
trainingFileList = listdir(`E:/workspace/digits/trainingDigits`)
m=len(trainingFileList)
trainingMat = np.zeros((m,1024))
for i in range(m):
fileNameStr = trainingFileList[i] # 例如9_45.txt
fileStr = fileNameStr.split(`.`)[0] # split(`.`)通過.分隔符對字串進行切片
classNumStr = int(fileStr.split(`_`)[0]) # split(`_`)通過_分隔符對字串進行切片
hwLabels.append(classNumStr)
trainingMat[i,:] =img2vector(`E:/workspace/digits/trainingDigits/%s` % fileNameStr)
testFileList = listdir(`E:/workspace/digits/testDigits`)
mTest = len(testFileList)
errorCount = 0
for i in range(mTest):
fileNameStr = testFileList[i]
fileStr = fileNameStr.split(`.`)[0]
classNumStr = int(fileStr.split(`_`)[0])
vectorUnderTest = img2vector(`E:/workspace/digits/testDigits/%s` % fileNameStr)
classResult = classify0(vectorUnderTest,trainingMat,hwLabels,3)
print(`the classifier came back with: %d, the real answer is: %d` % (classResult,classNumStr))
if (classResult != classNumStr):
errorCount += 1.0
print(`
the total number of errors is: %d` % (errorCount))
print(`
the total error rate is: %f` % (errorCount/float(mTest)))
handwritingClassTest()