蓝色天空.知识 · 实践 · 创造
我的收藏
机器学习 教程目录 58章
机器学习 / LEARN BY DOING

可解释性问题

系统解析全局与局部可解释性、模型透明度光谱、准确性-可解释性权衡及合规实践,并在本地实测决策树规则、测试集置换重要性、纯 Python 精确博弈论 Shapley 值与 LIME 局部线性代理。

学完这一章,你能够

  • 系统解析全局与局部可解释性、模型透明度光谱、准确性-可解释性权衡及合规实践,并在本地实测决策树规则、测试集置换重要性、纯 Python 精确博弈论 Shapley 值与 LIME 局部线性代理。

可解释性定义、两个层面与核心价值

深度神经网络等复杂模型常像黑箱,只呈现输入与输出却难以说清推理依据。机器学习可解释性指人类能够理解、信任并有效治理模型决策的能力,可拆分为两个层面:全局可解释性关注模型整体规律、关键驱动特征与决策边界形态;局部可解释性聚焦单条具体样本为何被判为 A 类而非 B 类,以及微调单个特征如何改写该样本预测。

可解释性在五大维度不可或缺:(1)高风险领域信任建立(医疗诊断、信贷拒批、自动驾驶均需说明理由);(2)满足 GDPR 等法规对决策逻辑透明度的合规要求;(3)辅助调试模型,快速暴露群体偏见与虚假相关性并指导特征工程;(4)支持科学探索与知识发现;(5)识别脆弱特征以加固对抗样本防御。

模型透明度光谱与现实挑战

不同算法族分布在由白盒到黑箱的透明度光谱上:线性/逻辑回归与浅层决策树可直接查看权重或从根到叶的判断路径;随机森林与梯度提升树处于中等区间;深层神经网络因海量非线性连接难以直观解析。本站在鸢尾花分层留出集上横向对比四类模型:LogisticRegression(15 参数,准确率 0.9211)、3 层 DecisionTree(export_text 仅 13 行可读花瓣规则,花瓣特征重要性占 1.0000,准确率 0.8947)、RandomForest(花瓣占比 0.8609,准确率 0.9211)与两层 MLP(739 参数,达逻辑回归 49 倍,准确率 0.9211)。

落地可解释性面临四重客观挑战:准确度与透明度往往存在权衡;深度模型参数量庞大且存在高阶非线性交互;即使输出上千维归因数字也超出人类认知带宽;此外业界仍缺乏跨方法完全统一客观的解释质量评分标准。

主流可解释性技术实测:置换重要性、精确 Shapley、LIME 代理与可视化

事后模型无关解释技术可在不牺牲复杂模型精度的前提下剖析特征贡献。其一,测试集置换重要性(permutation_importance)通过随机打乱单列特征测量留出指标跌幅,比树内置不纯度(MDI)更能识别无用噪声特征:本站在 3 真实驱动 + 2 纯噪声特征的 400 条信贷模拟数据上实测,25 次重复置换重要性精准将 3 个真实特征排在前三([0.2537, 0.1750, 0.0763]),而 2 个纯噪声列接近零(-0.0017、-0.0147),对比 MDI 仍给两列噪声分去 0.0598 与 0.0714 的虚高份额。其二,SHAP 基于博弈论 Shapley 值公平分配各特征对单次预测的边际贡献:本站用纯 Python 遍历全部 2^4 = 16 个特征联盟,在含交互项 x0·x2 与无用哑特征 x3 的非线性函数上严格验证了效率公理(基准值 -0.0800 加上四维 Shapley 值 [5.9250, 1.5096, 1.4454, 0.0000] 精确等于预测值 8.8000,误差 1.78e-15)与哑特征零贡献公理(phi_3 = 0.0),同时在线性函数上与解析解 w_i(x_i - E[X_i]) 最大误差仅 8.88e-16。

其三,LIME 在目标样本局部邻域采样扰动并用距离核加权拟合简单线性代理模型:本站围绕随机森林单条测试样本(黑箱正类概率 0.7097)生成 500 个高斯扰动点拟合加权 Ridge 代理,局部加权 R² 达 0.8315,代理系数符号 [+0.3529, +0.2079, -0.0129] 准确还原收入、信用正向推动与负债负向拉低的方向。其四,注意力权重热图与低维决策边界可视化直观呈现模型聚焦点:本站核对示例句注意力分布严格归一(和为 1.0),最高焦点对应「机器学习」(0.40);并在 200 条二维线性数据上实测逻辑回归决策边界(系数 [3.2085, 2.9844]),留出准确率 0.9800,2,601 个网格点正类覆盖比 0.4817 均衡合理。

工程实践流程、上线清单与研究展望

实际项目中应按业务风险分级选型(详见下方场景表),并将全局重要性、抽样局部归因与公平性检查封装入标准化验证管线。模型上线前建议逐项核对三层检查清单:技术层面确认能否解释全局与单次预测并排除虚假相关;伦理与合规层面排查群体偏见、法规遵循、用户知情解释权与误判申诉纠偏机制;实用层面确保领域专家读得懂、能指导迭代并留存关键决策解释日志。

前沿研究正沿着内在可解释架构(神经符号系统、透明网络、胶囊网络)、客观评测指标体系、人机交互式解释与低延迟自动化归因四大方向演进。初学者应从线性模型与决策树筑基,先理解透明模型机制,再逐步运用置换重要性、Shapley 值与局部代理剖析黑箱,始终保持「模型为何如此判断」的批判性追问。文末两项对比与回归归因练习均已融入本站离线实验脚本,便于无网一键复现。

模型透明度光谱对比

模型类型可解释性典型代表适用场景
高可解释性模型高线性回归、逻辑回归、浅层决策树强审计与强合规场景(如金融信贷审批)
中等可解释性模型中随机森林、梯度提升树(GBDT)需兼顾表格预测精度与特征归因的业务
低可解释性模型低深层神经网络、多层异构复杂集成视觉、语音、NLP 等精度优先并配事后解释的场景

不同应用场景的可解释性需求与推荐方法

应用场景可解释性需求推荐方法
医疗诊断非常高优先高可解释白盒模型,或为复杂模型配套严格事后局部归因与临床审核
金融风控高置换特征重要性、Shapley 单样本归因与显式决策规则提取
推荐系统中等注意力权重可视化、召回/排序理由生成
图像识别较低局部扰动掩码(LIME)、梯度显著图与特征激活可视化
研究探索可变围绕假设检验灵活组合全局重要性、交互归因与决策边界分析

运行透明度光谱、测试集置换重要性、精确 Shapley 与局部代理实测

含完整源码 · 228 行
展开查看收起
python
"""Independent scikit-learn + pure-Python CPU lab for interpretability: tree rules, linear coefs, permutation_importance, exact Shapley values, local surrogate (LIME-style), attention, and 2D decision boundary."""
import itertools
import json
import math
import platform

import numpy as np
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.inspection import permutation_importance
from sklearn.linear_model import LogisticRegression, Ridge
from sklearn.metrics import accuracy_score, r2_score
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.tree import DecisionTreeClassifier, export_text


def exact_shapley_values(model_fn, x: np.ndarray, background: np.ndarray) -> tuple[float, np.ndarray]:
    """Pure-Python exact coalition Shapley values over all 2^M feature subsets (small M)."""
    m = len(x)
    base_value = float(np.mean(model_fn(background)))
    cache: dict[tuple[int, ...], float] = {}

    def coalition_value(subset: tuple[int, ...]) -> float:
        if subset not in cache:
            arr = background.copy()
            for idx in subset:
                arr[:, idx] = x[idx]
            cache[subset] = float(np.mean(model_fn(arr)))
        return cache[subset]

    phi = np.zeros(m, dtype=np.float64)
    fact_m = math.factorial(m)
    features = list(range(m))
    for i in features:
        others = [j for j in features if j != i]
        total = 0.0
        for r in range(len(others) + 1):
            weight = math.factorial(r) * math.factorial(m - r - 1) / fact_m
            for comb in itertools.combinations(others, r):
                s = tuple(sorted(comb))
                s_with_i = tuple(sorted(comb + (i,)))
                total += weight * (coalition_value(s_with_i) - coalition_value(s))
        phi[i] = total
    return base_value, phi


def run_cases():
    rng = np.random.default_rng(42)
    cases = []

    # 1. Transparency spectrum on Iris: LogisticRegression, DecisionTree (rules), RandomForest, MLP
    iris = load_iris()
    X_tr, X_te, y_tr, y_te = train_test_split(
        iris.data, iris.target, test_size=0.25, random_state=42, stratify=iris.target
    )
    lr = Pipeline([("scaler", StandardScaler()), ("clf", LogisticRegression(max_iter=1000))]).fit(X_tr, y_tr)
    dt = DecisionTreeClassifier(max_depth=3, random_state=42).fit(X_tr, y_tr)
    rf = RandomForestClassifier(n_estimators=100, random_state=42).fit(X_tr, y_tr)
    mlp = Pipeline([("scaler", StandardScaler()), ("clf", MLPClassifier(hidden_layer_sizes=(32, 16), max_iter=500, random_state=42))]).fit(X_tr, y_tr)

    accs = {
        "LogisticRegression": round(float(accuracy_score(y_te, lr.predict(X_te))), 4),
        "DecisionTree": round(float(accuracy_score(y_te, dt.predict(X_te))), 4),
        "RandomForest": round(float(accuracy_score(y_te, rf.predict(X_te))), 4),
        "MLP": round(float(accuracy_score(y_te, mlp.predict(X_te))), 4),
    }
    tree_rules = export_text(dt, feature_names=list(iris.feature_names))
    lr_params = int(lr.named_steps["clf"].coef_.size + lr.named_steps["clf"].intercept_.size)
    mlp_inner = mlp.named_steps["clf"]
    mlp_params = int(sum(w.size for w in mlp_inner.coefs_) + sum(b.size for b in mlp_inner.intercepts_))
    petal_share_dt = round(float(dt.feature_importances_[2] + dt.feature_importances_[3]), 4)
    petal_share_rf = round(float(rf.feature_importances_[2] + rf.feature_importances_[3]), 4)

    c1_ok = (
        all(v >= 0.89 for v in accs.values())
        and "petal" in tree_rules
        and petal_share_dt >= 0.90
        and petal_share_rf >= 0.80
        and mlp_params > lr_params * 30
    )
    cases.append(dict(
        name="transparency_spectrum_and_tree_rules",
        inputs=dict(dataset="iris", models=["LogisticRegression", "DecisionTree", "RandomForest", "MLP"]),
        prerequisites="在鸢尾花数据集上对比高/中/低可解释性模型的留出准确率、参数量与显式规则",
        action="验证四类模型准确率均 >=0.89,决策树可导出可读花瓣规则且花瓣重要性 >=0.90,而 MLP 参数量达逻辑回归 30 倍以上。",
        expected=dict(all_acc_ge_89=True, tree_rules_readable=True, petal_dominant=True, mlp_params_gt_30x_lr=True),
        actual=dict(
            all_acc_ge_89=all(v >= 0.89 for v in accs.values()),
            tree_rules_readable=("petal" in tree_rules),
            petal_dominant=(petal_share_dt >= 0.90 and petal_share_rf >= 0.80),
            mlp_params_gt_30x_lr=(mlp_params > lr_params * 30),
        ),
        measurements=dict(test_accs=accs, lr_params=lr_params, mlp_params=mlp_params, dt_petal_share=petal_share_dt, rf_petal_share=petal_share_rf, dt_rule_lines=len(tree_rules.splitlines())),
        passed=c1_ok,
    ))

    # 2. Held-out permutation_importance vs impurity importance on 3 true drivers + 2 noise features
    n_loan = 400
    X_loan = rng.normal(0.0, 1.0, size=(n_loan, 5))
    # Features 0 (income), 1 (credit_score), 2 (debt_ratio) drive approval; 3 & 4 are pure noise
    logit_loan = 1.8 * X_loan[:, 0] + 1.4 * X_loan[:, 1] - 1.1 * X_loan[:, 2] + rng.normal(0.0, 0.5, size=n_loan)
    y_loan = (logit_loan > 0.0).astype(int)
    Xl_tr, Xl_te, yl_tr, yl_te = train_test_split(X_loan, y_loan, test_size=0.3, random_state=42, stratify=y_loan)
    rf_loan = RandomForestClassifier(n_estimators=120, max_depth=8, random_state=42).fit(Xl_tr, yl_tr)
    perm = permutation_importance(rf_loan, Xl_te, yl_te, n_repeats=25, random_state=42, scoring="accuracy")
    perm_means = [round(float(v), 4) for v in perm.importances_mean]
    mdi_means = [round(float(v), 4) for v in rf_loan.feature_importances_]
    top3_perm = sorted(range(5), key=lambda i: perm_means[i], reverse=True)[:3]
    noise_perm_max = max(abs(perm_means[3]), abs(perm_means[4]))

    c2_ok = set(top3_perm) == {0, 1, 2} and min(perm_means[:3]) > max(perm_means[3:]) + 0.04 and noise_perm_max < 0.04
    cases.append(dict(
        name="permutation_importance_signal_vs_noise",
        inputs=dict(n_samples=n_loan, signal_features=3, noise_features=2, n_repeats=25),
        prerequisites="在独立测试集上用 permutation_importance 识别真实驱动特征并过滤纯噪声特征",
        action="验证全部 3 个真实特征在测试集置换重要性排名前三且显著高于 2 个噪声特征(噪声绝对值 <0.04)。",
        expected=dict(top3_exact_signal=True, clear_gap_over_noise=True, noise_near_zero=True),
        actual=dict(
            top3_exact_signal=(set(top3_perm) == {0, 1, 2}),
            clear_gap_over_noise=(min(perm_means[:3]) > max(perm_means[3:]) + 0.04),
            noise_near_zero=(noise_perm_max < 0.04),
        ),
        measurements=dict(perm_means=perm_means, mdi_importances=mdi_means, top3_indices=top3_perm),
        passed=c2_ok,
    ))

    # 3. Pure-Python exact Shapley values (2^4 = 16 coalitions): efficiency, dummy & linear axioms
    bg = rng.normal(0.0, 1.0, size=(80, 4))
    x_explain = np.array([1.5, -0.8, 1.2, 2.0])

    # Nonlinear model with interaction x0*x2 and unused dummy feature x3
    def nonlin_model(arr: np.ndarray) -> np.ndarray:
        return 3.0 * arr[:, 0] - 2.0 * arr[:, 1] + 1.5 * arr[:, 0] * arr[:, 2]

    base_nl, phi_nl = exact_shapley_values(nonlin_model, x_explain, bg)
    fx_nl = float(nonlin_model(x_explain.reshape(1, -1))[0])
    efficiency_err = float(abs((base_nl + float(np.sum(phi_nl))) - fx_nl))
    dummy_err = float(abs(phi_nl[3]))

    # Linear model closed-form check: phi_i == w_i * (x_i - E[X_i])
    w_lin = np.array([2.5, -1.5, 0.8, 0.0])
    def lin_model(arr: np.ndarray) -> np.ndarray:
        return arr @ w_lin + 1.2
    _, phi_lin = exact_shapley_values(lin_model, x_explain, bg)
    closed_form = w_lin * (x_explain - bg.mean(axis=0))
    lin_max_err = float(np.max(np.abs(phi_lin - closed_form)))

    c3_ok = efficiency_err < 1e-9 and dummy_err < 1e-12 and lin_max_err < 1e-9
    cases.append(dict(
        name="exact_shapley_values_pure_python",
        inputs=dict(features=4, coalitions=16, background_n=80),
        prerequisites="纯 Python 遍历全部 2^4=16 个特征子集计算精确博弈论 Shapley 值",
        action="验证非线性交互模型满足可加性效率公理 (误差 <1e-9) 与哑特征零贡献公理 (|phi_3| <1e-12),线性模型精确匹配解析解。",
        expected=dict(efficiency_exact=True, dummy_zero=True, linear_closed_form_match=True),
        actual=dict(efficiency_exact=efficiency_err < 1e-9, dummy_zero=dummy_err < 1e-12, linear_closed_form_match=lin_max_err < 1e-9),
        measurements=dict(
            base_value=round(base_nl, 4), fx=round(fx_nl, 4),
            shapley_nonlin=[round(float(v), 4) for v in phi_nl],
            efficiency_err=efficiency_err, lin_max_err=lin_max_err,
        ),
        passed=c3_ok,
    ))

    # 4. Local surrogate explanation (LIME principle: proximity-weighted local Ridge)
    x0_idx = 0
    x0 = Xl_te[x0_idx]
    n_pert = 500
    Z_local = x0 + rng.normal(0.0, 0.45, size=(n_pert, Xl_te.shape[1]))
    y_bb_prob = rf_loan.predict_proba(Z_local)[:, 1]
    dists = np.linalg.norm(Z_local - x0, axis=1)
    kernel_w = np.exp(-(dists ** 2) / (2.0 * (0.75 ** 2)))
    surrogate = Ridge(alpha=1.0).fit(Z_local, y_bb_prob, sample_weight=kernel_w)
    local_r2 = round(float(r2_score(y_bb_prob, surrogate.predict(Z_local), sample_weight=kernel_w)), 4)
    # Surrogate signs on top drivers: income (+) and credit (+) vs debt (-)
    signs_match = bool(float(surrogate.coef_[0]) > 0 and float(surrogate.coef_[1]) > 0 and float(surrogate.coef_[2]) < 0)
    c4_ok = bool(local_r2 >= 0.80 and signs_match)
    cases.append(dict(
        name="local_surrogate_lime_principle",
        inputs=dict(perturbations=n_pert, kernel_sigma=0.75, target_sample=x0_idx),
        prerequisites="在黑箱 RandomForest 单样本邻域内用高斯核距离加权 Ridge 局部近似概率输出(LIME 原理)",
        action="验证局部线性代理模型的加权 R2 >=0.80,且局部回归系数符号准确还原真实正向/负向驱动方向。",
        expected=dict(local_r2_ge_80=True, driver_signs_recovered=True),
        actual=dict(local_r2_ge_80=local_r2 >= 0.80, driver_signs_recovered=signs_match),
        measurements=dict(local_weighted_r2=local_r2, local_coefs=[round(float(v), 4) for v in surrogate.coef_], bb_prob_x0=round(float(rf_loan.predict_proba(x0.reshape(1, -1))[0, 1]), 4)),
        passed=c4_ok,
    ))

    # 5. Attention weight inspection & 2D decision boundary verification
    tokens = ["我", "喜欢", "机器学习", "的", "可解释性", "研究"]
    attn = np.array([0.10, 0.15, 0.40, 0.05, 0.25, 0.05])
    attn_sum = round(float(np.sum(attn)), 6)
    top_token = tokens[int(np.argmax(attn))]

    X_2d = rng.normal(0.0, 1.0, size=(200, 2))
    y_2d = (X_2d[:, 0] + X_2d[:, 1] > 0.0).astype(int)
    X2_tr, X2_te, y2_tr, y2_te = train_test_split(X_2d, y_2d, test_size=0.25, random_state=42, stratify=y_2d)
    clf_2d = LogisticRegression(random_state=42).fit(X2_tr, y2_tr)
    acc_2d = round(float(accuracy_score(y2_te, clf_2d.predict(X2_te))), 4)
    gx, gy = np.meshgrid(np.linspace(-2.5, 2.5, 51), np.linspace(-2.5, 2.5, 51))
    grid_pred = clf_2d.predict(np.column_stack([gx.ravel(), gy.ravel()]))
    pos_grid_ratio = round(float(np.mean(grid_pred)), 4)

    c5_ok = abs(attn_sum - 1.0) < 1e-6 and top_token == "机器学习" and acc_2d >= 0.94 and 0.40 <= pos_grid_ratio <= 0.60
    cases.append(dict(
        name="attention_weights_and_2d_boundary",
        inputs=dict(tokens_count=6, grid_points=2601, test_2d_n=50),
        prerequisites="核对注意力权重归一化焦点与二维线性分类决策边界网格划分",
        action="验证示例注意力总和 1.0、最高关注词为「机器学习」,且二维逻辑回归测试准确率 >=0.94、正负决策区域比例均衡 (0.40~0.60)。",
        expected=dict(attn_sum_one=True, top_token="机器学习", boundary_acc_ge_94=True, grid_balanced=True),
        actual=dict(attn_sum_one=abs(attn_sum - 1.0) < 1e-6, top_token=top_token, boundary_acc_ge_94=acc_2d >= 0.94, grid_balanced=(0.40 <= pos_grid_ratio <= 0.60)),
        measurements=dict(attn_sum=attn_sum, acc_2d=acc_2d, pos_grid_ratio=pos_grid_ratio, coef_2d=[round(float(v), 4) for v in clf_2d.coef_.ravel()]),
        passed=c5_ok,
    ))

    payload = dict(
        version=platform.python_version(),
        system=platform.system(),
        cases=cases,
    )
    print(json.dumps(payload, ensure_ascii=False))


if __name__ == "__main__":
    run_cases()
核对 Iris 四类模型规则与参数量、测试集 permutation_importance 剥离噪声、纯 Python 16 联盟精确 Shapley 公理 (<1e-14)、LIME 风格局部代理 R2>=0.80 及注意力/二维边界。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a449.zip) ↓ 查看运行说明 ↗

本章附件与实例包

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

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

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

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

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

随机森林默认的基于不纯度下降(MDI)重要性是在训练集上统计的,容易偏爱高基数连续变量甚至给纯噪声特征分配非零份额(本站实测噪声 MDI 达 0.06~0.07);测试集置换重要性直接衡量打乱该特征后泛化得分的真实跌幅,纯噪声列会稳定接近 0。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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