用knn演算法對鳶尾花資料集進行分類

2021-10-12 19:12:27 字數 3113 閱讀 2463

from sklearn.datasets import load_iris

from sklearn.model_selection import train_test_split

from sklearn.preprocessing import standardscaler

from sklearn.neighbors import kneighborsclassifier

def knn_selector():

iris = load_iris()

x_train,x_test,y_train,y_test = train_test_split(iris.data, iris.target, test_size=0.3)

transfer = standardscaler()

x_train = transfer.fit_transform(x_train)

x_test = transfer.transform(x_test)

estimator = kneighborsclassifier(n_neighbors = 3)

estimator.fit(x_train, y_train)

# estimator.predict(x_test)

score = estimator.score(x_test, y_test)

print("score: ", score)

if __name__ == "__main__":

knn_selector()

import matplotlib.pyplot as plt

from sklearn.datasets import load_iris

from sklearn.model_selection import train_test_split

from sklearn.neighbors import kneighborsclassifier

from sklearn.preprocessing import standardscaler

# 獲取資料集

# 劃分資料集

# 標準化

# 建立模型

# 模型訓練

# 模型**與評估

def knn_selector():

iris = load_iris()

x_train, x_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size= 0.3)

# print(x_train)

# plt.plot(x_train[:,0])

# plt.show()

transfer = standardscaler()

x_train = transfer.fit_transform(x_train)

x_test = transfer.transform(x_test)

# print(x_train[:,0])

# plt.plot(x_train[:,0])

# plt.show()

estimator = kneighborsclassifier(n_neighbors = 3)

estimator.fit(x_train, y_train)

score = estimator.score(x_test, y_test)

print("準確率: ", score)

if __name__ == "__main__":

knn_selector()

from sklearn import datasets 

from sklearn.model_selection import train_test_split

from sklearn.neighbors import kneighborsclassifier

#------------------------------引入資料------------------------------

iris = datasets.load_iris() # 引入 iris 鳶尾花資料集

# 鳶尾花資料集 包含 4個 特徵變數

iris_x = iris.data # 特徵變數

iris_y = iris.target # 目標值

# iris['data']

# iris['target']

x_train, x_test, y_train, y_test = train_test_split(iris_x, iris_y, test_size=0.3)

#---------------------------訓練資料

knn = kneighborsclassifier() # 引入訓練方法

knn.fit(x_train,y_train) # 進行填充測試資料進行訓練

knn.predict(x_test) # ** 特徵值

'''array([2, 1, 2, 0, 0, 1, 1, 2, 0, 1, 0, 2, 0, 1, 0, 2, 1, 2, 2, 2, 2, 2, 1,

1, 1, 1, 0, 2, 1, 2, 0, 1, 1, 0, 0, 2, 0, 0, 1, 0, 2, 1, 1, 2, 2])

'''y_test # 真實的 特徵值

KNN演算法進行鳶尾花分類

import numpy as np import matplotlib.pylab as pyb matplotlib inline from sklearn.neighbors import kneighborsclassifier from sklearn import datasets fr...

knn演算法 鳶尾花

knn分類演算法實現鳶尾花 對鳶尾花利用knn演算法進行分類,利用python的sklean庫極大方便了python的使用,減少了大量 的書寫。knn演算法的 是通過計算歐氏距離來確定 鳶尾花的結果,遍歷所有樣本集,計算待分類樣本與每個樣本的距離,計算並儲存後排序,尋找k個近鄰,最後輸出最小結果即為...

使用KNN對鳶尾花資料集進行分類處理

author tao contact 1281538933 qq.com file knn.py time 2020 12 21 software vscode from sklearn.datasets import load iris 匯入資料集iris import matplotlib.py...