模型可解释性:特征重要性/SHAP/LIME

模型可解释性:特征重要性/SHAP/LIME

1. 特征重要性

python 复制代码
from sklearn.ensemble import RandomForestClassifier
import pandas as pd

# 树模型内置特征重要性
rf = RandomForestClassifier(n_estimators=100, random_state=42)
rf.fit(X_train, y_train)

importance = pd.Series(rf.feature_importances_, index=feature_names)
print(importance.nlargest(10))

# XGBoost 特征重要性
import xgboost as xgb
xgb_clf = xgb.XGBClassifier().fit(X_train, y_train)
xgb.plot_importance(xgb_clf, max_num_features=10)

2. SHAP 值

python 复制代码
import shap

# 计算 SHAP 值
explainer = shap.TreeExplainer(rf)
shap_values = explainer.shap_values(X_test)

# 摘要图
shap.summary_plot(shap_values[1], X_test, feature_names=feature_names)

# 单样本解释
shap.force_plot(explainer.expected_value[1], shap_values[1][0], X_test.iloc[0])

# 依赖图
shap.dependence_plot('feature_name', shap_values[1], X_test)

3. LIME

python 复制代码
from lime.lime_tabular import LimeTabularExplainer

explainer = LimeTabularExplainer(
    X_train.values,
    feature_names=feature_names,
    class_names=['class_0', 'class_1'],
    mode='classification'
)

# 解释单个样本
exp = explainer.explain_instance(
    X_test.iloc[0].values,
    rf.predict_proba,
    num_features=10
)

exp.show_in_notebook()

总结

方法 适用模型 粒度 计算速度
特征重要性 树模型 全局
SHAP 任意模型 全局+局部
LIME 任意模型 局部
相关推荐
霖大侠1 小时前
Decoupled and Reusable Adaptation for Efficient Cross-Modal Transfer
人工智能·深度学习·算法·机器学习·transformer
代码不接地1 小时前
【时间序列预测】0.时间序列任务知识地图
python·ai编程
武子康2 小时前
调查研究-216 Tesla Robotaxi 进了 Miami,但真正的考题才刚开始
人工智能·llm·自动驾驶
LaughingZhu2 小时前
Product Hunt 每日热榜 | 2026-07-05
人工智能·经验分享·深度学习·神经网络·产品运营
海兰2 小时前
【AI编程思考:第六篇】学习记忆与 Agent 状态:让 AI 真正“记得”你
人工智能·学习·ai编程
Dragon Wu2 小时前
ComfyUI ReActor需要下载检测模型的解决方案
人工智能·ai
雨辰AI2 小时前
【零基础实战】大模型入门面试 100 问:基础概念 + 环境实操(一问一答版,直接背诵)
人工智能·ai·面试·职场和发展·ai编程
龙萱坤诺2 小时前
Claude Fable 5 重新开放:最强模型回归
大数据·运维·人工智能