1. 程式人生 > >機器學習_K近鄰代碼詳解

機器學習_K近鄰代碼詳解

under () als test readlines 通過 swe port range

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(‘\n‘)
#newline = line.split(‘ ‘)
newline = line.strip(‘\n‘).split(‘ ‘) # 處理逐行數據,strip表示把頭尾的‘\n‘去掉,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(‘\n the total number of errors is: %d‘ % (errorCount))
print(‘\n the total error rate is: %f‘ % (errorCount/float(mTest)))

handwritingClassTest()



機器學習_K近鄰代碼詳解