机器学习鸢尾花案例

数据集介绍

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

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

相关推荐
风象南17 小时前
Claude Code这个隐藏技能,让我告别PPT焦虑
人工智能·后端
Mintopia18 小时前
OpenClaw 对软件行业产生的影响
人工智能
陈广亮19 小时前
构建具有长期记忆的 AI Agent:从设计模式到生产实践
人工智能
会写代码的柯基犬19 小时前
DeepSeek vs Kimi vs Qwen —— AI 生成俄罗斯方块代码效果横评
人工智能·llm
Mintopia19 小时前
OpenClaw 是什么?为什么节后热度如此之高?
人工智能
爱可生开源社区19 小时前
DBA 的未来?八位行业先锋的年度圆桌讨论
人工智能·dba
叁两1 天前
用opencode打造全自动公众号写作流水线,AI 代笔太香了!
前端·人工智能·agent
前端付豪1 天前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
strayCat232551 天前
Clawdbot 源码解读 7: 扩展机制
人工智能·开源