機器學習實戰讀書筆記 二 k 近鄰演算法

2022-05-07 16:03:18 字數 4302 閱讀 6802

knn演算法:

1.優點:精度高、對異常值不敏感、無資料輸入假定

2.缺點:計算複雜度高、空間複雜度高。

3.適用資料範圍:數值型和標稱型。

一般流程:

1.收集資料

2.準備資料

3.分析資料

4.訓練演算法:不適用

5.測試演算法:計算正確率

6.使用演算法:需要輸入樣本和結構化的輸出結果,然後執行k-近鄰演算法判定輸入資料分別屬於哪個分類,最後應用對計算出的分類執行後續的處理。

2.1.1 匯入資料

operator是排序時要用的

from numpy import *

import

operator

defcreatedataset():

group=array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])

labels=['

a','

a','

b','b'

]

return group,labels

儲存到knn.py檔案

更改當前工作目錄,匯入knn

os.chdir('

g:\\學習\\機器學習實戰')

import knn

呼叫knn,建立資料集

group,labels=knn.createdataset()
2.1.2 實施knn演算法

1.計算己知類別資料集中的點與當前點之間的距離

2.按照距離遞增次數序排序

3.選取與當前點距離最小的k個點

4.確定前k個點所在類別的出現頻率

5.返回前k個點出現頻率最高的類別作為當前點的**分類

4個引數:

a.inx:用於分類的輸入向量

b.dataset:訓練樣本

c.標籤向量:labels

d.k:用於選擇最近鄰居的數目

def

classify0(inx, dataset, labels, k):

datasetsize =dataset.shape[0]

diffmat = tile(inx, (datasetsize,1)) -dataset

sqdiffmat = diffmat**2sqdistances = sqdiffmat.sum(axis=1)

distances = sqdistances**0.5sorteddistindicies =distances.argsort()

classcount={}

for i in

range(k):

voteilabel =labels[sorteddistindicies[i]]

classcount[voteilabel] = classcount.get(voteilabel,0) + 1sortedclasscount = sorted(classcount.iteritems(), key=operator.itemgetter(1), reverse=true)

return sortedclasscount[0][0]

1~5行計算歐氏距離

6行按從小到大排序distances.argsort(),排完序後是下標

2.2 使用knn演算法改進約會**的配對效果

在knn.py中新增函式

strip是去掉前後的\n,[-1]竟然是指最後一列

def

file2matrix(filename):

fr =open(filename)

numberoflines = len(fr.readlines()) #

get the number of lines in the file

returnmat = zeros((numberoflines,3)) #

prepare matrix to return

classlabelvector = #

prepare labels return

fr =open(filename)

index =0

for line in

fr.readlines():

line =line.strip()

listfromline = line.split('\t'

) returnmat[index,:] = listfromline[0:3]

index += 1

return returnmat,classlabelvector

reload(knn)

datingdatamat,datinglabels=knn.file2matrix('

datingtestset.txt

')

2.2.2 分析資料:使用matplotlib建立散點圖

import

matplotlib

import

matplotlib.pyplot as plt

fig=plt.figure()

ax=fig.add_subplot(111)

ax.scatter(datingdatamat[:,1],datingdatamat[:,2])

plt.show()

換一下,用顏色顯示不同類別

import

matplotlib

import

matplotlib.pyplot as plt

fig=plt.figure()

ax=fig.add_subplot(111)

ax.scatter(datingdatamat[:,1],datingdatamat[:,2],15.0*numpy.array(datinglabels),15.0*numpy.array(datinglabels))

plt.show()

2.2.3 準備資料:歸一化數值

def

autonorm(dataset):

minvals =dataset.min(0)

maxvals =dataset.max(0)

ranges = maxvals -minvals

normdataset =zeros(shape(dataset))

m =dataset.shape[0]

normdataset = dataset - tile(minvals, (m,1))

normdataset = normdataset/tile(ranges, (m,1)) #

element wise divide

return normdataset, ranges, minvals

2.2.4 作為完整程式驗證分類器

def

datingclasstest():

horatio = 0.50 #

hold out 10%

datingdatamat,datinglabels = file2matrix('

datingtestset2.txt

') #

load data setfrom file

normmat, ranges, minvals =autonorm(datingdatamat)

m =normmat.shape[0]

numtestvecs = int(m*horatio)

errorcount = 0.0

for i in

range(numtestvecs):

classifierresult = classify0(normmat[i,:],normmat[numtestvecs:m,:],datinglabels[numtestvecs:m],3)

print

"the classifier came back with: %d, the real answer is: %d

" %(classifierresult, datinglabels[i])

if (classifierresult != datinglabels[i]): errorcount += 1.0

print

"the total error rate is: %f

" % (errorcount/float(numtestvecs))

print errorcount

機器學習實戰讀書筆記(一) K近鄰演算法

from numpy import import operator def createdataset 建立資料集 group array 1.0,1.1 1.0,1.1 0,0 0,0.1 labels a a b b return group,labels def classify0 inx,d...

k 近鄰演算法 機器學習讀書筆記

優點 精度高 對異常值不敏感 無資料輸入假定。缺點 計算複雜度高 空間複雜度高。適用資料範圍 數值型和標稱型。步驟 1.獲取原始資料集 資料向量和標籤 2.輸入待分類資料向量,計算該向量與每個原始資料集向量的距離 3.對所有距離排序 從近到遠 取前k個最近的原始資料集,檢視其標籤 4.前k個最近資料...

《機器學習實戰》讀書筆記

監督學習使用兩種型別的目標變數 之所以稱監督學習,是因為這類演算法必須知道 什麼,即目標變數的分類資訊 在無監督學習中,將資料集合分成由類似的物件組成的多個類的過程被稱為聚類 將尋找描述資料統計值的過程稱之為密度估計 是 否要 預測目標 變數的值 是 監督學習 目標變數型別 begin離散型 分類演...