使用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=[...]))
相关推荐
wyg_0311132 小时前
用deepseek学大模型04-模型可视化与数据可视化
人工智能·机器学习·信息可视化
陈敬雷-充电了么-CEO兼CTO3 小时前
DeepSeek核心算法解析:如何打造比肩ChatGPT的国产大模型
人工智能·神经网络·自然语言处理·chatgpt·大模型·aigc·deepseek
盼小辉丶3 小时前
TensorFlow深度学习实战(8)——卷积神经网络
深度学习·cnn·tensorflow
南风过闲庭4 小时前
人工智能泡沫效应
大数据·人工智能·科技·搜索引擎·百度·ai
我是一个对称矩阵4 小时前
YOLOv5-Seg 深度解析:与 YOLOv5 检测模型的区别
人工智能·yolo·目标跟踪
AomanHao4 小时前
图像质量评价指标-UCIQE-UIQM
图像处理·人工智能·计算机视觉·评价指标
MYT_flyflyfly4 小时前
计算机视觉-尺度不变区域
人工智能·计算机视觉
何小Ai同学4 小时前
Deepseek赚钱密码:小场景闭环如何让你快速盈利?
人工智能·架构·deepseek
AI服务老曹4 小时前
通过感知、分析、预测、控制,最大限度发挥效率的智慧油站开源了
人工智能·开源·自动化·音视频
Donvink4 小时前
【复现DeepSeek-R1之Open R1实战】系列5:SFT源码逐行深度解析
人工智能·深度学习·语言模型·transformer