机器学习鸢尾花案例

数据集介绍

鸢尾花(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)避免过拟合。
  • 特征重要性:决策树可输出特征重要性,帮助理解哪些特征对分类贡献最大。

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

相关推荐
m0_564876843 分钟前
LoRA 大模型微调是怎么回事
人工智能·深度学习
Data 实验室3 分钟前
TaskPyro “小龙虾版本”专业爬虫管理平台来了:AI+分布式+IM 机器人,一套搞定企业级爬虫调度
人工智能·分布式·爬虫
飞哥数智坊4 分钟前
openclaw 安装后第一个 skill——tavily
人工智能
莫叫石榴姐4 分钟前
本体论:企业智能化转型的核心引擎
大数据·数据仓库·人工智能·面试·职场和发展
Agent产品评测局6 分钟前
企业超自动化落地,如何打通全业务流程的数据孤岛?技术路径全景盘点与选型指南
运维·人工智能·ai·chatgpt·自动化
志栋智能6 分钟前
安全自动化不烧钱:低成本实战策略
运维·网络·人工智能·安全·自动化
数据皮皮侠11 分钟前
2285 上市公司组织衰退程度【Dec】2010-2024
大数据·人工智能·算法·制造
俊哥V11 分钟前
每日 AI 研究简报 · 2026-03-30
人工智能·ai
汉堡大王952714 分钟前
AI 终于有了"插件系统"——MCP 完全指南
人工智能·aigc
renhongxia114 分钟前
TrustTrade:人类启发的选择性共识降低大型语言模型交易代理的决策不确定性
人工智能·微服务·语言模型·自然语言处理·架构·机器人·知识图谱