机器学习鸢尾花案例

数据集介绍

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

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

相关推荐
tech-share3 分钟前
基于pytorch 自建AI大模型
人工智能·深度学习·机器学习·gpu算力
夏洛克信徒25 分钟前
从 “工具” 到 “代理”:Gemini 3.0 重构 AI 能力边界,开启智能协作新纪元
大数据·人工智能·神经网络
AI浩32 分钟前
回归基础:让去噪生成模型真正去噪
人工智能·数据挖掘·回归
ekprada1 小时前
DAY 16 数组的常见操作和形状
人工智能·python·机器学习
用户5191495848451 小时前
C#扩展成员全面解析:从方法到属性的演进
人工智能·aigc
柳鲲鹏1 小时前
OpenCV: 光流法python代码
人工智能·python·opencv
金融小师妹1 小时前
基于LSTM-GARCH模型:三轮黄金周期特征提取与多因子定价机制解构
人工智能·深度学习·1024程序员节
小蜜蜂爱编程1 小时前
深度学习实践 - 使用卷积神经网络的手写数字识别
人工智能·深度学习·cnn
leiming61 小时前
深度学习日记2025.11.20
人工智能·深度学习
速易达网络2 小时前
tensorflow+yolo图片训练和图片识别系统
人工智能·python·tensorflow