1、导入需要的包
# 导入鸢尾花数据集
from sklearn.datasets import load_iris
# 数据可视化包
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler, StandardScaler
from sklearn.neighbors import KNeighborsClassifier
2、获取鸢尾花数据集
iris = load_iris()
3、数据可视化
iris_data1 = pd.DataFrame(data=iris['data'], columns=['Sepal_Length', 'Sepal_Width', 'Petal_Length', 'Petal_Width'])
4、填充目标值
iris_data1['target'] = iris['target']
5、 数据集的划分
x_train, x_test, y_train, y_test = train_test_split(iris['data'], iris['target'], test_size=0.2, random_state=42)
6、特征工程 - 特征预处理
transfer = StandardScaler()
ret_train_data = transfer.fit_transform(x_train)
ret_test_data = transfer.fit_transform(x_test)
7、构建KNN并实例化
n_neighbors_num = 5
knn_model = KNeighborsClassifier(n_neighbors=n_neighbors_num)
# 7.2 训练模型 输入训练集和训练集标签
knn_model.fit(ret_train_data, y_train)
8、 评估模型
y_pre = knn_model.predict(ret_test_data)
print("预测结果:", y_pre)
print("真实值:", y_test)
print("预测值和真实值对比:\n", y_pre == y_test)
# 8.2 准确率计算,注意如果是归一化后的数据就得用归一化后的数据进行预测计算准确率,不然效果很差
score = knn_model.score(ret_test_data, y_test)
print("准确率:", score)