"""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()
本例需在 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-interpretability-problem-lab/explore-interpretability-problem.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-interpretability-problem.py,或下载右侧课程工程包。 - 确认本地已准备 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。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联58章) · 含当前章节或实例 · mbskycom202612a449.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a477.zip