鸢尾花数据集上的决策树

Machine LearningMachine LearningBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在本实验中,我们将使用鸢尾花数据集和决策树来对鸢尾花的类型进行分类。我们将首先可视化在鸢尾花数据集的特征对上训练的决策树的决策边界。接下来,我们将展示在鸢尾花数据集的所有特征上训练的单个决策树的结构。

虚拟机使用提示

虚拟机启动完成后,点击左上角切换到“笔记本”标签页,以访问 Jupyter Notebook 进行练习。

有时,你可能需要等待几秒钟让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。

如果你在学习过程中遇到问题,随时向 Labby 提问。课程结束后提供反馈,我们将立即为你解决问题。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL sklearn(("Sklearn")) -.-> sklearn/CoreModelsandAlgorithmsGroup(["Core Models and Algorithms"]) sklearn(("Sklearn")) -.-> sklearn/ModelSelectionandEvaluationGroup(["Model Selection and Evaluation"]) sklearn(("Sklearn")) -.-> sklearn/UtilitiesandDatasetsGroup(["Utilities and Datasets"]) ml(("Machine Learning")) -.-> ml/FrameworkandSoftwareGroup(["Framework and Software"]) sklearn/CoreModelsandAlgorithmsGroup -.-> sklearn/tree("Decision Trees") sklearn/ModelSelectionandEvaluationGroup -.-> sklearn/inspection("Inspection") sklearn/UtilitiesandDatasetsGroup -.-> sklearn/datasets("Datasets") ml/FrameworkandSoftwareGroup -.-> ml/sklearn("scikit-learn") subgraph Lab Skills sklearn/tree -.-> lab-49167{{"鸢尾花数据集上的决策树"}} sklearn/inspection -.-> lab-49167{{"鸢尾花数据集上的决策树"}} sklearn/datasets -.-> lab-49167{{"鸢尾花数据集上的决策树"}} ml/sklearn -.-> lab-49167{{"鸢尾花数据集上的决策树"}} end

加载鸢尾花数据集

第一步是使用 scikit-learn 加载鸢尾花数据集。

from sklearn.datasets import load_iris

iris = load_iris()

可视化决策边界

现在我们将可视化在鸢尾花数据集的特征对上训练的决策树的决策边界。

import numpy as np
import matplotlib.pyplot as plt

from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.inspection import DecisionBoundaryDisplay

## 参数
n_classes = 3
plot_colors = "ryb"
plot_step = 0.02

for pairidx, pair in enumerate([[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]]):
    ## 我们只取两个相应的特征
    X = iris.data[:, pair]
    y = iris.target

    ## 训练
    clf = DecisionTreeClassifier().fit(X, y)

    ## 绘制决策边界
    ax = plt.subplot(2, 3, pairidx + 1)
    plt.tight_layout(h_pad=0.5, w_pad=0.5, pad=2.5)
    DecisionBoundaryDisplay.from_estimator(
        clf,
        X,
        cmap=plt.cm.RdYlBu,
        response_method="predict",
        ax=ax,
        xlabel=iris.feature_names[pair[0]],
        ylabel=iris.feature_names[pair[1]],
    )

    ## 绘制训练点
    for i, color in zip(range(n_classes), plot_colors):
        idx = np.where(y == i)
        plt.scatter(
            X[idx, 0],
            X[idx, 1],
            c=color,
            label=iris.target_names[i],
            cmap=plt.cm.RdYlBu,
            edgecolor="black",
            s=15,
        )

plt.suptitle("Decision surface of decision trees trained on pairs of features")
plt.legend(loc="lower right", borderpad=0, handletextpad=0)
_ = plt.axis("tight")

展示决策树结构

接下来,我们将展示在鸢尾花数据集的所有特征上训练的单个决策树的结构。

from sklearn.tree import plot_tree

plt.figure()
clf = DecisionTreeClassifier().fit(iris.data, iris.target)
plot_tree(clf, filled=True)
plt.title("Decision tree trained on all the iris features")
plt.show()

总结

在本实验中,我们使用决策树对鸢尾花的类型进行分类。我们首先可视化了在鸢尾花数据集的特征对上训练的决策树的决策边界。接下来,我们展示了在鸢尾花数据集的所有特征上训练的单个决策树的结构。