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)
相关推荐
我有满天星辰3 小时前
第一次使用 Milvus:给我的 AI 知识库装上“记忆”
人工智能·milvus
YOLO数据集集合4 小时前
天空反无人机检测数据集 | 无人机检测 多旋翼识别 固定翼识别 低空安防 目标检测9063期
人工智能·yolo·目标检测·计算机视觉·无人机·反无人机
一木 之林4 小时前
插件、MCP、Skill 的区别?
java·c++·人工智能
JiMoKuangXiangQu4 小时前
在 AllWinner T507 上部署 Qwen2.5-0.5B 大语言模型
人工智能·llama.cpp·推理引擎
szarron4 小时前
RF Demo Kit|NanoVNA 射频演示测试板完整上手教程,滤波器、衰减器、SOLT 校准学习板
开发语言·人工智能·学习·php·射频工程·频谱仪
IT·陈寒4 小时前
JavaScript性能优化完全指南
人工智能·大模型·api·创业·变现·简历优化
tedcloud1234 小时前
Wand-Enhancer:如何搭建一套远程开发与测试环境
前端·人工智能·macos·开源·流程图
薛定谔的猫-菜鸟程序员4 小时前
端侧免费大模型实测:MiniCPM5-2B-Q4_K_M 架构拆解与 4GB 显卡实测
人工智能·大模型·agent·hermes·minicpm5-2b
小海豚儿4 小时前
没有反馈的 Loop,只是更贵的重试
人工智能·ai编程
用户302822530684 小时前
Agent Skill工程:如何把一次成功运行提炼成可测试的方法
人工智能