机器学习鸢尾花案例

数据集介绍

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

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

相关推荐
金井PRATHAMA1 小时前
描述逻辑(Description Logic)对自然语言处理深层语义分析的影响与启示
人工智能·自然语言处理·知识图谱
Rock_yzh1 小时前
AI学习日记——参数的初始化
人工智能·python·深度学习·学习·机器学习
CiLerLinux3 小时前
第四十九章 ESP32S3 WiFi 路由实验
网络·人工智能·单片机·嵌入式硬件
七芒星20234 小时前
多目标识别YOLO :YOLOV3 原理
图像处理·人工智能·yolo·计算机视觉·目标跟踪·分类·聚类
Learn Beyond Limits5 小时前
Mean Normalization|均值归一化
人工智能·神经网络·算法·机器学习·均值算法·ai·吴恩达
ACERT3335 小时前
5.吴恩达机器学习—神经网络的基本使用
人工智能·python·神经网络·机器学习
C嘎嘎嵌入式开发5 小时前
(一) 机器学习之深度神经网络
人工智能·神经网络·dnn
Aaplloo5 小时前
【无标题】
人工智能·算法·机器学习
大模型任我行5 小时前
复旦:LLM隐式推理SIM-CoT
人工智能·语言模型·自然语言处理·论文笔记
tomlone6 小时前
AI大模型核心概念
人工智能