KNN(K近邻)水仙花的分类(含答案)

题目

以下采用K-NN算法来解决水仙花的分类问题,每个样本有两个特征,第一个为水仙花的花萼长度,第二个为水仙花 的花萼宽度,具体数据见表,

1)设置k=3, 采用欧式距离,分析分类精度为多少?

2)使用网格搜索方式找到最佳参数,并预测

3)可视化

我的数据集合就是这个

excel数据展示

代码

复制代码
import numpy as np
import pandas as pd
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import GridSearchCV
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap

def model_selection(x_train, y_train):
    params = {'n_neighbors': [3,5,7,8,10], 'p': [1,2]}
    model = KNeighborsClassifier()
    gs = GridSearchCV(model, params, verbose=2, cv=5)
    gs.fit(x_train, y_train)
    print("Best Model:", gs.best_params_, "Accuracy:", gs.best_score_)
    return gs.best_estimator_

def read():
    filename = r"data/shuixianhua.xlsx"
    data = pd.read_excel(filename, header=None)
    x1 = data.iloc[1:, [0, 1]].values
    x2 = data.iloc[1:, [3, 4]].values
    # print(x2)
    y1 = data.iloc[1:, 2].values
    y2 = data.iloc[1:, 5].values
    x = np.vstack((x1, x2))  # 竖向合并
    y = np.hstack((y1, y2))  # 横向合并

    y = y.astype(int)
    return x, y

def plot_decision_boundary(x, y, model):
    h = 0.02  # Step size in the mesh

    # Create color maps
    cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA'])
    cmap_bold = ListedColormap(['#FF0000', '#00FF00'])

    x_min, x_max = x[:, 0].min() - 1, x[:, 0].max() + 1
    y_min, y_max = x[:, 1].min() - 1, x[:, 1].max() + 1
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))

    Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)

    plt.figure()
    plt.pcolormesh(xx, yy, Z, cmap=cmap_light)
    plt.scatter(x[:, 0], x[:, 1], c=y, cmap=cmap_bold, edgecolor='k', s=20)
    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())
    plt.title("KNN Decision Boundaries")
    plt.show()

if __name__ == '__main__':
    x, y = read()
    best_model = model_selection(x, y)
    plot_decision_boundary(x, y, best_model)
相关推荐
2401_841495642 小时前
【计算机视觉】基于数学形态学的保留边缘图像去噪
人工智能·python·算法·计算机视觉·图像去噪·数学形态学·边缘保留
三天哥2 小时前
Sora 2为什么会火?
人工智能·gpt·ai·aigc·agi·ai视频·sora
逻辑留白陈2 小时前
2025年实用大模型工具清单
人工智能·学习方法
许泽宇的技术分享2 小时前
AI驱动的视频生成革命:MoneyPrinterTurbo技术架构深度解析
人工智能·内容创作·ai视频生成
飞哥数智坊3 小时前
“成章”写作助手开源:中秋赏不成月,那就开源一个 AI 实战项目吧
人工智能·ai编程·trae
colus_SEU3 小时前
【循环神经网络6】LSTM实战——基于LSTM的IMDb电影评论情感分析
人工智能·rnn·深度学习·神经网络·lstm
zezexihaha3 小时前
AI + 制造:从技术试点到产业刚需的 2025 实践图鉴
人工智能·制造
文火冰糖的硅基工坊3 小时前
[人工智能-综述-21]:学习人工智能的路径
大数据·人工智能·学习·系统架构·制造
爱喝白开水a4 小时前
2025时序数据库选型,从架构基因到AI赋能来解析
开发语言·数据库·人工智能·架构·langchain·transformer·时序数据库
小关会打代码5 小时前
计算机视觉进阶教学之Mediapipe库(一)
人工智能·计算机视觉