Python鳶尾花分類實現

來源:互聯網
上載者:User

標籤:...   knn   test   預測   展示   for   core   and   模型   

#coding:utf-8

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
import numpy as np
import matplotlib.pyplot as plt

iris_dataset = load_iris() # 擷取資料
# print("keys of iris_dataset:\n{}".format(iris_dataset.keys()))
# print(iris_dataset["DESCR"][:193]+"\n...")
# print("target names:{}".format(iris_dataset["target_names"]))
# print("feature names:{}".format(iris_dataset["feature_names"]))
# print(iris_dataset["data"][:5])
# print(iris_dataset["data"], iris_dataset["target"])
# 對資料進行拆分,分為訓練資料和測試資料
x_train, x_test, y_train, y_test = train_test_split(iris_dataset["data"], iris_dataset["target"], random_state=0)
# print(x_train, x_test, y_train, y_test)

knn = KNeighborsClassifier(n_neighbors=1) # 擷取KNN對象
knn.fit(x_train, y_train) # 訓練模型

# 評估模型
y_pre = knn.predict(x_test)
score = knn.score(x_test, y_test) # 調用打分函數
print("test set predictions:\n{}".format(y_test))
print("test set score:{:.2f}".format(score))
if score > 0.9:
x_new = np.array([[5, 2.9, 1, 0.3]])
print("x_new.shape:{}".format(x_new.shape))
prediction = knn.predict(x_new) # 預測
print("prediction:{}".format(prediction))
print("predicted target name:{}".format(iris_dataset["target_names"][prediction]))

# 可視化展示
plt.title("KNN Classification")
plt.plot(x_train, y_train, "b.") # 訓練資料打點
plt.plot(x_test, y_test, "y.") # 測試資料打點
plt.plot(x_new, prediction, "ro") # 預測資料打點
plt.show()
else:
print("used train or test data is not available !")

 

 



Python鳶尾花分類實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.