机器学习鸢尾花案例

数据集介绍

鸢尾花(Iris)数据集是机器学习领域的经典分类数据集,包含三类鸢尾花的测量数据:山鸢尾(Iris-setosa)、变色鸢尾(Iris-versicolor)和维吉尼亚鸢尾(Iris-virginica)。每类样本50条,共150条数据,每条数据包含4个特征:萼片长度(sepal length)、萼片宽度(sepal width)、花瓣长度(petal length)、花瓣宽度(petal width),目标变量为花的类别。


数据加载与探索

通过Python的scikit-learn库可直接加载数据集:

复制代码
from sklearn.datasets import load_iris
import pandas as pd

iris = load_iris()
data = pd.DataFrame(iris.data, columns=iris.feature_names)
data['target'] = iris.target
print(data.head())

关键操作:

  • 检查数据分布(data.describe()
  • 可视化特征分布(如箱线图或散点矩阵)
  • 观察类别是否均衡(三类样本数量均为50)

数据预处理

  1. 划分训练集与测试集

    from sklearn.model_selection import train_test_split
    X_train, X_test, y_train, y_test = train_test_split(
    data[iris.feature_names], data['target'], test_size=0.2, random_state=42
    )

  2. 特征标准化(可选)

    from sklearn.preprocessing import StandardScaler
    scaler = StandardScaler()
    X_train = scaler.fit_transform(X_train)
    X_test = scaler.transform(X_test)


模型训练与评估

方法1:逻辑回归
复制代码
from sklearn.linear_model import LogisticRegression
model = LogisticRegression(max_iter=200)
model.fit(X_train, y_train)
print("Accuracy:", model.score(X_test, y_test))
方法2:决策树
复制代码
from sklearn.tree import DecisionTreeClassifier
model = DecisionTreeClassifier(max_depth=3)
model.fit(X_train, y_train)
print("Accuracy:", model.score(X_test, y_test))
方法3:支持向量机(SVM)
复制代码
from sklearn.svm import SVC
model = SVC(kernel='linear')
model.fit(X_train, y_train)
print("Accuracy:", model.score(X_test, y_test))

可视化与解释

  1. 决策树可视化

    from sklearn.tree import plot_tree
    import matplotlib.pyplot as plt
    plt.figure(figsize=(12, 8))
    plot_tree(model, feature_names=iris.feature_names, class_names=iris.target_names, filled=True)
    plt.show()

  2. 混淆矩阵

    from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
    cm = confusion_matrix(y_test, model.predict(X_test))
    ConfusionMatrixDisplay(cm, display_labels=iris.target_names).plot()
    plt.show()


关键注意事项

  • 模型选择:线性模型(如逻辑回归)适合线性可分数据,决策树适合捕捉非线性关系。
  • 过拟合 :通过调整参数(如决策树的max_depth)避免过拟合。
  • 特征重要性:决策树可输出特征重要性,帮助理解哪些特征对分类贡献最大。

通过上述流程,可快速实现鸢尾花分类任务并验证模型性能。

相关推荐
技术与健康21 分钟前
LLM实践系列:利用LLM重构数据科学流程07 - 工程化实践与挑战
人工智能·机器学习·重构·大模型工程化实践
MobotStone31 分钟前
AI Agent工程师≠Prompt工程师:能力断层在哪
人工智能
深瞳智检35 分钟前
目标检测数据集 第007期-基于yolo标注格式的茶叶病害检测数据集(含免费分享)
人工智能·深度学习·yolo·目标检测·计算机视觉
区块链蓝海35 分钟前
UPCX与日本电信公司NTT就新一代去中心化支付系统签署合作协议
人工智能·web3·区块链
berling001 小时前
【论文阅读 | arXiv 2025 | WaveMamba:面向RGB-红外目标检测的小波驱动Mamba融合方法】
论文阅读·人工智能·目标检测
CHEN5_021 小时前
时序数据库选型“下半场”:从性能竞赛到生态博弈,四大主流架构深度横评
数据库·人工智能·ai·架构·时序数据库
top_designer1 小时前
作品集PDF又大又卡?我用InDesign+Acrobat AI构建轻量化交互式文档工作流
人工智能·pdf·自动化·设计规范·acrobat·indesign·交互式pdf
涡能增压发动积1 小时前
MySQL数据库为何逐渐黯淡,PostgreSQL为何能新王登基
人工智能·后端
瓦力wow1 小时前
Pytorch安装详细步骤
人工智能·pytorch·python
Java中文社群1 小时前
重磅!Ollama发布UI界面,告别命令窗口!
java·人工智能·后端