def
traindata()
: traindata = np.array([[
0.1,
0.2],[
0.5,
0.1],[
1.8,
1.5],[
1.3,
1.6]])
label =
['a'
,'a'
,'b'
,'b'
]return traindata,label
#knn
#input----輸入資料、dataset----樣本資料、label----樣本資料對應的標籤、k----選取的k值
defknn
(input
,dataset,label,k)
: sample = dataset.shape[0]
#樣本數
distance =
for i in
range
(sample)
: diff = dataset[i]
-input
#計算測試樣本和每個樣本的差值
sdiff = diff **
2#對差值進行平方
sdiff_sum =
sum(sdiff)
#差值的平方求和
dis = sdiff **
0.5#歐氏距離
distance = np.array(diatance)
#list沒有agrsort屬性
index = distance.argsort(
)#對距離按從小到大排序並返回相對應的index
classcount =
for i in
range
(k):
vote_label = label[index[i]
]#選取距離最近的前k個label
classcount[vote_label]
= classcount.get(vote_label,0)
+1#對出現的每個label計數
maxclass =
0#k---類別名稱,這裡指a或者b v指的是每種類別的個數
for k, v in classcount.items():
if maxclass < v:
maxclass = v
label = k
return label
Python實現KNN演算法
from numpy import import operator def creatdataset group array 1.0,1.1 1.0,1.0 0,0 0,0.1 lables a a b b return group,lables def classify0 inx,dataset,...
python實現knn演算法
importnumpyasnp importoperator defcreatedataset group np.array 1.0 1.1 1.0 1.0 0.0 0.0 0.0 0.1 labels a a b b returngroup,labels 分類演算法 inx待分類的點 defcla...
python實現KNN演算法
具體 如下 import numpy as np import matplotlib.pyplot as plt class myknn def init self,k self.k k def compute self,x train,y train,x test dist i 0 計算歐式距離 ...