Python Iris鳶尾花資料Knn分類

2021-10-10 03:35:05 字數 1312 閱讀 2234

首先匯入sklearn庫中自帶iris資料(三類:0:山鳶尾花、1:變色鳶尾花、2:維吉尼亞鳶尾花),訓練集112個,測試集38個。

# 匯入iris資料,x資料,y標籤

iris = datasets.load_iris()

x = iris.data

y = iris.target

x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=2003)

計算待分類樣本與其餘樣本之間的歐式距離

#計算兩個樣本的距離

def distance(test1, test2):

dist = np.sqrt(sum((test1-test2)**2))

return dist

**樣本的標籤:利用counter統計出前k個樣本中每一類的數目(從大到小), count.most_common()可以將字典轉換為list方便返回。

#乙個樣本knn分類結果標籤

def knn(x, y, test, k):

d = [distance(x, test) for x in x]

knext = np.argsort(d)[:k] #返回前k個最小的樣本位置

count = counter(y[knext])

return count.most_common()[0][0] #返回最多的標籤

最後,就是呼叫上面的兩個函式**iris資料

pred = [knn(x_train, y_train, x, 3) for x in x_test]

print("測試集**標籤")

count=0

for i in range(len(pred)):

print(pred[i],end="")

count=count+1

if count%10==0:

print(end="\n")

correct = np.count_nonzero((pred == y_test) == true)

print("\n")

print("accuracy is: %.3f" % (correct / len(x_test)))

測試結果:38個測試集結果全部列印出來

鳶尾花資料集

from sklearn import datasets iris datasets.load iris iris是乙個字典集keys iris.keys dict keys data target target names descr feature names data iris.data.sh...

鳶尾花分類python演算法 BP演算法鳶尾花分類

bp演算法鳶尾花分類 網上很多鳶尾花例子,學習其他人後仿寫,我在執行其他人的時候會有溢位和錯誤。下述 準確率95 提取碼 y07d 如果有什麼不對的或者有什麼不懂iamzhubaoliang yeah.net 工程位址 import math import random import pandas ...

鳶尾花資料分類實戰

資料集大概是這樣子的 將資料預處理一下 def get data loc iris.csv with open loc,r as fr lines csv.reader fr data file np.array list lines data data file 1 0 1 astype floa...