通過KNN查詢離樣本最近的鄰居

2021-10-01 13:53:42 字數 3499 閱讀 3722

# 尋找離樣本最近的鄰居

from sklearn import datasets

from sklearn.neighbors import nearestneighbors

from sklearn.preprocessing import standardscaler

# 載入資料

iris = datasets.load_iris(

)features = iris.data

# 標準化資料

standardizer = standardscaler(

)# features 特徵標準化

features_standardized = standardizer.fit_transform(features)

​nearest_neighbors = nearestneighbors(n_neighbors=2)

.fit(features_standardized)

#nearest_neighbors_euclidian = nearestneighbors(n_neighbors=2, metric='euclidian').fit(features_standardized)

# 建立測試資料

new_observation =[1

,1,1

,1]​

# 獲取最近兩個點的索引,距離

distances, indices = nearest_neighbors.kneighbors(

[new_observation])​

# features_standardized[indices] 距離最近的兩個值

indices

# 距離

distances

features_standardized[indices]

array([[

[1.03800476

,0.55861082

,1.10378283

,1.18556721],

[0.79566902

,0.32841405

,0.76275827

,1.05393502]]

])# metric 設定距離指標

nearestneighbors_euclidean = nearestneighbors(

n_neighbors=

2, metric=

'euclidean'

).fit(features_standardized)

# 檢視距離

distances

array([[

0.49140089

,0.74294782]]

)# 尋找最近的3個點

nearestneighbors_euclidean = nearestneighbors(

n_neighbors=

3, metric=

"euclidean"

).fit(features_standardized)

​nearestneighbors_euclidean

# kneighbors_graph 建立乙個矩陣,表示離每個觀察值最近的點

# 包含每個觀察值和離他最近的3個鄰居

nearest_neighbors_with_self = nearestneighbors_euclidean.kneighbors_graph(

features_standardized)

.toarray()​

# type(nearest_neighbors_with_self)

​nearest_neighbors_with_self

list

(enumerate

(nearest_neighbors_with_self)

)# 從最近鄰居的列表移自己

for i, x in

enumerate

(nearest_neighbors_with_self)

: x[i]=0

​nearest_neighbors_with_self

# 檢視裡第乙個樣本最近的兩個鄰居

nearest_neighbors_with_self[0]

array([0

.,0.

,0.,

0.,0

.,0.

,0.,

0.,0

.,0.

,0.,

0.,0

.,0.

,0.,

0.,0

.,1.

,0.,

0.,0

.,0.

,0.,

0.,0

.,0.

,0.,

1.,0

.,0.

,0.,

0.,0

.,0.

,0.,

0.,0

.,0.

,0.,

0.,0

.,0.

,0.,

0.,0

.,0.

,0.,

0.,0

.,0.

,0.,

0.,0

.,0.

,0.,

0.,0

.,0.

,0.,

0.,0

.,0.

,0.,

0.,0

.,0.

,0.,

0.,0

.,0.

,0.,

0.,0

.,0.

,0.,

0.,0

.,0.

,0.,

0.,0

.,0.

,0.,

0.,0

.,0.

,0.,

0.,0

.,0.

,0.,

0.,0

.,0.

,0.,

0.,0

.,0.

,0.,

0.,0

.,0.

,0.,

0.,0

.,0.

,0.,

0.,0

.,0.

,0.,

0.,0

.,0.

,0.,

0.,0

.,0.

,0.,

0.,0

.,0.

,0.,

0.,0

.,0.

,0.,

0.,0

.,0.

,0.,

0.,0

.,0.

,0.,

0.,0

.,0.

,0.,

0.,0

.,0.

,0.,

0.,0

.,0.

,0.,

0.,0

.,0.

])

通過KNN例子,實現Sklearn入門

pip 安裝 安裝 scikit learn sklearn 最簡單的方法就是使用 pip 安裝它.首先確認自己電腦中有安裝 python 2.6 或 3.3 版本 numpy 1.6.1 scipy 0.9 然後開啟cmd視窗,使用如下命令安裝 pip3 install u scikit lear...

通過TCODE查詢User Exit

report zfind userexit no standard page heading.tables tstc,tadir,modsapt,modact,trdir,tfdir,enlfdir.tables tstct.data jtab like tadir occurs 0 with he...

通過TCODE查詢User Exit

z find user exit report z find user exit no standard page heading.tables tstc,tadir,modsapt,modact,trdir,tfdir,enlfdir.tables tstct.data jtab like tad...