KNN实现鸢尾花分类过程与结果可视化

python(KNN)实现鸢尾花数据集分类

本文主要做的工作是:使用KNN算法实现鸢尾花数据集分类,KNN中的k值分别使用绘图和网格搜索两种方式获取,并且将分类结果可视化。

主要程序如下:

import sklearn.datasets as datasets
from matplotlib import pyplot as plt
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import GridSearchCV
from sklearn.datasets import load_iris
plt.rcParams['font.sans-serif'] = ['SimHei']  # 显示中文标签
plt.rcParams['axes.unicode_minus'] = False

程序1主要绘制准确率随k值变化曲线:

def knn_iris():

    # 1)加载鸢尾花数据集
    iris = datasets.load_iris()
    # 打印出鸢尾花数据集
    print(iris)

    # 2)划分数据集
    x_train, x_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.3, random_state=2021)

    # 3)标准化
    transfer = StandardScaler()
    x_train = transfer.fit_transform(x_train)
    x_test = transfer.transform(x_test)

    # 4)找knn的k值与准确率的关系,从而确定k值
    k_plot(x_train, y_train)

    # 5)KNN算法预估器
    estimator = KNeighborsClassifier(n_neighbors=3)
    estimator.fit(x_train, y_train)

    # 6)模型评估
    # 方法1:直接比对真实值和预测值
    y_predict = estimator.predict(x_test)
    print("y_predict:\n", y_predict)
    print("直接比对真实值和预测值:\n", y_test == y_predict)

    # 方法2:计算准确率
    score = estimator.score(x_test, y_test)
    print("准确率为:\n", score)
    return x_test,y_test,y_predict,score

程序2主要实现网格搜索寻优:

def knn_iris_gscv():
    """
    用KNN算法对鸢尾花进行分类,添加网格搜索和交叉验证
    :return:
    """
    # 1)获取数据
    iris = load_iris()

    # 2)划分数据集
    x_train, x_test, y_train, y_test = train_test_split(iris.data, iris.target, random_state=22)

    # 3)标准化
    transfer = StandardScaler()
    x_train = transfer.fit_transform(x_train)
    x_test = transfer.transform(x_test)

    # 4)KNN算法预估器
    estimator = KNeighborsClassifier()

    # 加入网格搜索与交叉验证
    # 参数准备
    param_dict = {"n_neighbors": [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29]}
    estimator = GridSearchCV(estimator, param_grid=param_dict, cv=10)
    estimator.fit(x_train, y_train)

    # 5)模型评估
    # 方法1:比对真实值和预测值
    y_predict = estimator.predict(x_test)
    print("y_predict:\n", y_predict)
    print("比对真实值和预测值:\n", y_test == y_predict)

    # 方法2:计算准确率
    score = estimator.score(x_test, y_test)
    print("准确率为:\n", score)

    # 最佳参数:best_params_
    print("最佳参数:\n", estimator.best_params_)
    # 最佳结果:best_score_
    print("最佳准确率:\n", estimator.best_score_)

准确率随k值变化曲线为:
KNN实现鸢尾花分类过程与结果可视化_第1张图片
鸢尾花数据集分类结果可视化:
KNN实现鸢尾花分类过程与结果可视化_第2张图片
网格搜索结果为:
KNN实现鸢尾花分类过程与结果可视化_第3张图片
文章中可能存在多处不足,还请各位大佬批评指正。

完整代码下载请点击:https://download.csdn.net/download/weixin_44525542/86234440

你可能感兴趣的:(数据集分类,分类,机器学习,python)