使用scikit-learn中的KNN包实现对鸢尾花数据集的预测

1. 导入必要的库

首先,需要导入所需的库:

python 复制代码
import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score, classification_report
复制代码

2. 加载鸢尾花数据集

scikit-learn提供了方便的函数来加载鸢尾花数据集:

python 复制代码
# 加载鸢尾花数据集
iris = load_iris()
X = iris.data
y = iris.target

# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

3. 数据预处理

对数据进行标准化处理,以提高KNN算法的性能:

python 复制代码
# 标准化数据
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

4. 训练KNN模型

使用KNeighborsClassifier来训练KNN模型:

python 复制代码
# 创建KNN分类器
knn = KNeighborsClassifier(n_neighbors=3)

# 训练模型
knn.fit(X_train, y_train)

5. 进行预测并评估模型

使用测试集进行预测,并评估模型的性能:

python 复制代码
# 进行预测
y_pred = knn.predict(X_test)

# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print(f'Accuracy: {accuracy:.2f}')

# 打印分类报告
print(classification_report(y_test, y_pred, target_names=iris.target_names))

6. 使用自定义数据集

如果有一个自定义的数据集,可以按照以下步骤进行操作。假设有一个CSV文件custom_dataset.csv,其中包含特征和标签。

python 复制代码
# 加载自定义数据集
custom_data = pd.read_csv('custom_dataset.csv')

# 假设特征列为前n-1列,标签列为最后一列
X_custom = custom_data.iloc[:, :-1].values
y_custom = custom_data.iloc[:, -1].values

# 将数据集分为训练集和测试集
X_custom_train, X_custom_test, y_custom_train, y_custom_test = train_test_split(X_custom, y_custom, test_size=0.2, random_state=42)

# 标准化数据
scaler_custom = StandardScaler()
X_custom_train = scaler_custom.fit_transform(X_custom_train)
X_custom_test = scaler_custom.transform(X_custom_test)

# 创建KNN分类器并训练
knn_custom = KNeighborsClassifier(n_neighbors=3)
knn_custom.fit(X_custom_train, y_custom_train)

# 进行预测
y_custom_pred = knn_custom.predict(X_custom_test)

# 计算准确率
accuracy_custom = accuracy_score(y_custom_test, y_custom_pred)
print(f'Custom Dataset Accuracy: {accuracy_custom:.2f}')

# 如果有标签名称,可以打印分类报告
# print(classification_report(y_custom_test, y_custom_pred, target_names=[...]))
相关推荐
徐健峰11 分钟前
GPT-image-2 热门玩法实战(三):AI 手办/Action Figure — 把自己变成盒装玩具
人工智能
扑兔AI16 分钟前
B2B销售线索挖掘效率提升的技术实践:基于工商公开数据的客源筛选与竞品分析架构
大数据·人工智能·架构
亚鲁鲁21 分钟前
00-目录
人工智能
罗西的思考25 分钟前
【GUI-Agent】阿里通义MAI-UI 代码阅读(2)--- 实现
人工智能·算法·机器学习
墨染天姬1 小时前
【AI】cursor提示词小技巧
前端·数据库·人工智能
Raink老师1 小时前
【AI面试临阵磨枪-40】文本切块(Chunking)策略:固定长度、语义切块、递归切块、重叠设计
人工智能·ai 面试
techdashen1 小时前
p99 延迟从 9.5 毫秒降到 18 微秒:Cloudflare 机器学习基础设施重构全记录
人工智能·机器学习·重构
AI服务老曹1 小时前
架构师视角:如何构建支持GB28181/RTSP的异构AI视频平台?从Docker部署到源码交付的深度实践
人工智能·docker·音视频
IT_陈寒2 小时前
Vite热更新失效?你可能漏了这个小细节
前端·人工智能·后端
机器之心2 小时前
今天起,Claude正式接入Office全家桶,跨应用还能共享记忆
人工智能·openai