蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行决策树不纯度公式、缩放不变性、CV 剪枝与 plot_tree/DOT 导出实验

PYTHONWindows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。explore-decision-tree.py
explore-decision-tree.py273 行
"""Independent scikit-learn 1.9.1 lab for Decision Trees (Entropy, Gini, MSE, Pruning, DOT & plot_tree)."""
import argparse
import hashlib
import json
import math
import platform
from pathlib import Path

import numpy as np
from sklearn.datasets import load_iris, make_moons
from sklearn.metrics import accuracy_score, mean_squared_error, r2_score
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor, export_graphviz, plot_tree


def sha(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


def shannon_entropy(labels: np.ndarray) -> float:
    _, counts = np.unique(labels, return_counts=True)
    probs = counts / len(labels)
    return float(-np.sum(probs * np.log2(probs)))


def gini_impurity(labels: np.ndarray) -> float:
    _, counts = np.unique(labels, return_counts=True)
    probs = counts / len(labels)
    return float(1.0 - np.sum(probs ** 2))


def run_cases(fig_dir: Path | None):
    cases = []
    figures = {}

    # 1. Impurity criteria math: Entropy / Information Gain, Gini Index, and Regression MSE reduction
    parent = np.array([0, 0, 0, 0, 1, 1, 1, 1])
    left_pure = np.array([0, 0, 0, 0])
    right_pure = np.array([1, 1, 1, 1])
    h_parent = shannon_entropy(parent)
    g_parent = gini_impurity(parent)
    ig_perfect = h_parent - 0.5 * shannon_entropy(left_pure) - 0.5 * shannon_entropy(right_pure)
    g_pure = gini_impurity(left_pure)

    y_reg_parent = np.array([2.0, 2.0, 2.0, 10.0, 10.0, 10.0])
    mse_parent = float(np.var(y_reg_parent))
    mse_after_split = 0.5 * float(np.var(y_reg_parent[:3])) + 0.5 * float(np.var(y_reg_parent[3:]))

    c1_ok = (
        abs(h_parent - 1.0) < 1e-12
        and abs(g_parent - 0.5) < 1e-12
        and abs(ig_perfect - 1.0) < 1e-12
        and abs(g_pure) < 1e-12
        and abs(mse_parent - 16.0) < 1e-12
        and abs(mse_after_split) < 1e-12
    )
    cases.append(dict(
        name="impurity_criteria_entropy_gini_mse",
        inputs=dict(binary_balanced=[4, 4], reg_values=[2, 2, 2, 10, 10, 10]),
        prerequisites="直接以解析公式核对平衡二分类节点的熵、基尼指数、完全纯净分裂的信息增益及回归 MSE 降幅。",
        action="验证平衡二分类 Entropy=1.0、Gini=0.5、纯子集 Gini=0.0、信息增益=1.0,以及回归分裂使 MSE 由 16.0 降至 0.0。",
        expected=dict(entropy_balanced=1.0, gini_balanced=0.5, ig_pure_split=1.0, mse_dropped_to_zero=True),
        actual=dict(
            entropy_balanced=round(h_parent, 6),
            gini_balanced=round(g_parent, 6),
            ig_pure_split=round(ig_perfect, 6),
            mse_dropped_to_zero=(abs(mse_parent - 16.0) < 1e-12 and abs(mse_after_split) < 1e-12),
        ),
        measurements=dict(parent_mse=mse_parent, split_mse=mse_after_split),
        passed=c1_ok,
    ))

    # 2. Iris DecisionTreeClassifier: Gini vs Entropy + Scale Invariance verification
    iris = load_iris()
    x_tr, x_te, y_tr, y_te = train_test_split(iris.data, iris.target, test_size=0.3, random_state=42)
    clf_gini = DecisionTreeClassifier(criterion="gini", random_state=42).fit(x_tr, y_tr)
    clf_ent = DecisionTreeClassifier(criterion="entropy", random_state=42).fit(x_tr, y_tr)
    clf_scaled = make_pipeline(StandardScaler(), DecisionTreeClassifier(criterion="gini", random_state=42)).fit(x_tr, y_tr)

    pred_gini = clf_gini.predict(x_te)
    pred_ent = clf_ent.predict(x_te)
    pred_scaled = clf_scaled.predict(x_te)
    acc_gini = float(accuracy_score(y_te, pred_gini))
    acc_ent = float(accuracy_score(y_te, pred_ent))
    scale_invariant = bool(np.array_equal(pred_gini, pred_scaled))
    imp_sum = float(np.sum(clf_gini.feature_importances_))

    c2_ok = acc_gini >= 0.95 and acc_ent >= 0.95 and scale_invariant and abs(imp_sum - 1.0) < 1e-12
    cases.append(dict(
        name="iris_classifier_gini_vs_entropy",
        inputs=dict(dataset="load_iris", test_size=0.3, random_state=42),
        prerequisites="在 Iris 70/30 划分上对比基尼指数、信息熵及带 StandardScaler 的决策树分类器。",
        action="验证 Gini 与 Entropy 均达高准确率、特征重要性之和为 1.0,且单调缩放不改变决策树预测结果。",
        expected=dict(gini_acc_ge_095=True, entropy_acc_ge_095=True, scale_invariant=True, importance_sum_1=True),
        actual=dict(
            gini_acc_ge_095=acc_gini >= 0.95,
            entropy_acc_ge_095=acc_ent >= 0.95,
            scale_invariant=scale_invariant,
            importance_sum_1=abs(imp_sum - 1.0) < 1e-12,
        ),
        measurements=dict(
            gini_test_acc=round(acc_gini, 4),
            entropy_test_acc=round(acc_ent, 4),
            gini_depth=int(clf_gini.get_depth()),
            gini_leaves=int(clf_gini.get_n_leaves()),
            top_feature=iris.feature_names[int(np.argmax(clf_gini.feature_importances_))],
        ),
        passed=c2_ok,
    ))

    # 3. Overfitting, CV-based depth pruning, and tree instability on noisy moons
    xm, ym = make_moons(n_samples=260, noise=0.32, random_state=42)
    xm_tr, xm_te, ym_tr, ym_te = train_test_split(xm, ym, test_size=0.3, random_state=42, stratify=ym)

    tree_full = DecisionTreeClassifier(random_state=42).fit(xm_tr, ym_tr)
    full_tr_acc = float(accuracy_score(ym_tr, tree_full.predict(xm_tr)))
    full_te_acc = float(accuracy_score(ym_te, tree_full.predict(xm_te)))

    # Select max_depth via 5-fold CV strictly on training set
    depths = [1, 2, 3, 4, 5, 6, 8, 12]
    cv_means = {}
    tr_curve = {}
    for d in depths:
        cv_sc = cross_val_score(DecisionTreeClassifier(max_depth=d, random_state=42), xm_tr, ym_tr, cv=5)
        cv_means[d] = round(float(cv_sc.mean()), 4)
        t_tmp = DecisionTreeClassifier(max_depth=d, random_state=42).fit(xm_tr, ym_tr)
        tr_curve[d] = round(float(accuracy_score(ym_tr, t_tmp.predict(xm_tr))), 4)
    best_depth = max(cv_means, key=cv_means.get)
    tree_pruned = DecisionTreeClassifier(max_depth=best_depth, random_state=42).fit(xm_tr, ym_tr)
    pruned_te_acc = float(accuracy_score(ym_te, tree_pruned.predict(xm_te)))

    # Instability check: removing 5% of training samples alters tree structure
    keep_n = int(len(xm_tr) * 0.95)
    tree_sub = DecisionTreeClassifier(random_state=42).fit(xm_tr[:keep_n], ym_tr[:keep_n])
    structure_changed = (
        tree_full.tree_.node_count != tree_sub.tree_.node_count
        or abs(float(tree_full.tree_.threshold[0]) - float(tree_sub.tree_.threshold[0])) > 1e-6
    )

    c3_ok = (
        full_tr_acc == 1.0
        and tree_pruned.get_n_leaves() < tree_full.get_n_leaves()
        and pruned_te_acc >= full_te_acc
        and structure_changed
    )
    cases.append(dict(
        name="overfitting_pruning_and_instability",
        inputs=dict(dataset="make_moons(noise=0.32)", candidate_depths=depths, cv=5),
        prerequisites="在含噪声双月数据上仅用训练集 5 折交叉验证筛选 max_depth,对比无剪枝树与剪枝树并检验微小样本扰动。",
        action="验证无剪枝树训练准确率 1.00 存在过拟合、CV 剪枝显著缩减叶节点且泛化不降反升,删去 5% 样本即改变树结构。",
        expected=dict(unpruned_memorizes_train=True, pruned_fewer_leaves_better_or_eq=True, perturbed_tree_changes=True),
        actual=dict(
            unpruned_memorizes_train=(full_tr_acc == 1.0),
            pruned_fewer_leaves_better_or_eq=(tree_pruned.get_n_leaves() < tree_full.get_n_leaves() and pruned_te_acc >= full_te_acc),
            perturbed_tree_changes=structure_changed,
        ),
        measurements=dict(
            full_leaves=int(tree_full.get_n_leaves()),
            full_train_acc=full_tr_acc,
            full_test_acc=round(full_te_acc, 4),
            cv_best_depth=best_depth,
            cv_best_score=cv_means[best_depth],
            pruned_leaves=int(tree_pruned.get_n_leaves()),
            pruned_test_acc=round(pruned_te_acc, 4),
            sub_node_count=int(tree_sub.tree_.node_count),
            full_node_count=int(tree_full.tree_.node_count),
        ),
        passed=c3_ok,
    ))

    # 4. Regression tree (MSE criterion) + offline export_graphviz DOT string verification
    rng = np.random.default_rng(42)
    xr = np.sort(rng.uniform(0.0, 6.0, size=(160, 1)), axis=0)
    yr = np.sin(xr[:, 0]) + rng.normal(0.0, 0.12, size=160)
    xr_tr, xr_te, yr_tr, yr_te = train_test_split(xr, yr, test_size=0.25, random_state=42)
    reg_tree = DecisionTreeRegressor(criterion="squared_error", max_depth=4, random_state=42).fit(xr_tr, yr_tr)
    reg_pred = reg_tree.predict(xr_te)
    reg_mse = float(mean_squared_error(yr_te, reg_pred))
    reg_r2 = float(r2_score(yr_te, reg_pred))

    dot_text = export_graphviz(
        clf_gini,
        out_file=None,
        feature_names=iris.feature_names,
        class_names=list(iris.target_names),
        filled=True,
        rounded=True,
        special_characters=True,
    )
    dot_ok = dot_text.startswith("digraph Tree {") and "gini" in dot_text and "petal" in dot_text

    c4_ok = reg_r2 > 0.85 and reg_mse < 0.08 and dot_ok
    cases.append(dict(
        name="regression_tree_and_dot_export",
        inputs=dict(reg_max_depth=4, reg_criterion="squared_error"),
        prerequisites="训练基于 MSE 准则的回归树,并调用 sklearn.tree.export_graphviz 离线导出 DOT 图描述文本。",
        action="验证回归树测试 R² >0.85 且 export_graphviz 无需外部 graphviz 可执行文件即可生成完整 DOT 字符串。",
        expected=dict(reg_tree_r2_gt_085=True, dot_string_valid=True),
        actual=dict(reg_tree_r2_gt_085=reg_r2 > 0.85, dot_string_valid=dot_ok),
        measurements=dict(
            reg_test_mse=round(reg_mse, 4),
            reg_test_r2=round(reg_r2, 4),
            dot_char_length=len(dot_text),
            dot_line_count=len(dot_text.splitlines()),
        ),
        passed=c4_ok,
    ))

    # 5. Pure Matplotlib PNG chart via sklearn.tree.plot_tree + depth CV curve
    mpl_ver = None
    if fig_dir is not None:
        import matplotlib
        matplotlib.use("Agg")
        import matplotlib.pyplot as plt

        fig_dir.mkdir(parents=True, exist_ok=True)
        fig, axes = plt.subplots(1, 2, figsize=(11.2, 4.4), dpi=140, gridspec_kw={"width_ratios": [1.45, 1.0]})

        clf_vis = DecisionTreeClassifier(max_depth=3, random_state=42).fit(x_tr, y_tr)
        plot_tree(
            clf_vis,
            ax=axes[0],
            feature_names=["sepal L", "sepal W", "petal L", "petal W"],
            class_names=list(iris.target_names),
            filled=True,
            rounded=True,
            fontsize=7,
        )
        axes[0].set_title("Iris Decision Tree (max_depth=3 via plot_tree)", fontsize=10)

        axes[1].plot(depths, [tr_curve[d] for d in depths], "o-", color="#174d79", lw=1.8, label="Train Accuracy")
        axes[1].plot(depths, [cv_means[d] for d in depths], "s--", color="#ae511d", lw=1.8, label="5-Fold CV Accuracy")
        axes[1].axvline(best_depth, color="#2a8c55", ls=":", lw=1.4, label=f"CV Best depth={best_depth}")
        axes[1].set_title("Moons Tree Depth vs Generalization", fontsize=10)
        axes[1].set_xlabel("max_depth")
        axes[1].set_ylabel("Accuracy")
        axes[1].set_ylim(0.65, 1.03)
        axes[1].grid(True, alpha=0.3)
        axes[1].legend(fontsize=8)

        fig.tight_layout()
        out_png = fig_dir / "decision-tree-iris.png"
        fig.savefig(out_png)
        plt.close(fig)
        figures["decision-tree-iris.png"] = sha(out_png)
        mpl_ver = matplotlib.__version__

    cases.append(dict(
        name="observed_decision_tree_plot",
        inputs=dict(vis_max_depth=3, cv_depths_count=len(depths)),
        prerequisites="使用 sklearn.tree.plot_tree 与 Matplotlib 离线绘制 Iris 决策树结构与剪枝深度验证曲线。",
        action="输出决策树可视化与深度泛化双联 PNG 图,无需安装系统级 Graphviz。",
        expected=dict(depths_plotted=len(depths)),
        actual=dict(depths_plotted=len(cv_means)),
        measurements=dict(figure_generated="decision-tree-iris.png" in figures),
        passed=(len(cv_means) == len(depths)),
    ))

    payload = dict(version=platform.python_version(), system=platform.system(), cases=cases)
    if mpl_ver:
        payload["matplotlib"] = mpl_ver
        payload["figures"] = figures
    print(json.dumps(payload, ensure_ascii=False))


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--figures", type=Path, default=None)
    args = parser.parse_args()
    run_cases(args.figures)
本例需在 Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。

入口文件:projects/ml-decision-tree-lab/explore-decision-tree.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-decision-tree.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:机器学习

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a463.zip

下载课程关联工程包:机器学习

课程关联工程包(登记关联58章) · 含当前章节或实例 · mbskycom202612a449.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习