模型可解释性:特征重要性/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 任意模型 局部
相关推荐
qq_22589174663 分钟前
基于Flask的城市地铁客流量数据预测系统设计与实现
后端·python·flask
IT_陈寒5 分钟前
搞不定JavaScript的数组去重?你可能漏了这两个坑
前端·人工智能·后端
豌豆学姐8 分钟前
likeadmin-api 全驱动数字人参数避坑:file_url、ref_file_url 和 mode 怎么传
人工智能·aigc·api·数字人·全驱动数字人
海兰9 分钟前
mcporter — 安装部署及使用完全指南(四)
人工智能·agent·openclaw
W_3260010 分钟前
Python 常用标准 / 第三方库:random、tqdm、turtle、jieba 用法
开发语言·python
手写码匠11 分钟前
华为云Flexus+DeepSeek征文|Dify 多 Agent 评测实战:用 DeepSeek-R1 当裁判,打造多智能体系统的自动化质量保障体系
人工智能·深度学习·算法·aigc
MartinYeung512 分钟前
[论文学习]JBShield:通过激活概念分析与操纵防御大语言模型越狱攻击
人工智能·学习·语言模型
ZJU_统一阿萨姆12 分钟前
【推理优化】KV Cache 量化:在不牺牲质量的前提下压榨更多内存
人工智能·语言模型·系统架构·vllm
安逸sgr15 分钟前
Dropout 和正则化:深度学习如何缓解过拟合?
人工智能·ai·大模型·agent·智能体