解释树模型的损失

解释模型的损失对于调试和模型监控非常有用。 本笔记本给出了一个非常简单的例子来说明这是如何工作的。 请注意,解释模型的损失需要传递标签,并且仅支持 TreeExplainer 的 feature_perturbation="independent" 选项。

一旦我们发布此方法的完整书面说明,本笔记本将被充实。

[1]:
import numpy as np
import xgboost

import shap

训练 XGBoost 分类器

[2]:
X, y = shap.datasets.adult()

model = xgboost.XGBClassifier()
model.fit(X, y)

# compute the logistic log-loss
model_loss = -np.log(model.predict_proba(X)[:, 1]) * y + -np.log(model.predict_proba(X)[:, 0]) * (1 - y)

model_loss[:10]
[2]:
array([8.43880873e-04, 2.47898608e-01, 1.17997164e-02, 7.11527169e-02,
       6.41849875e-01, 1.76084566e+00, 5.70287136e-03, 8.60033274e-01,
       4.78262809e-04, 6.43801317e-03])

使用 TreeExplainer 解释模型的对数损失

请注意,模型损失的 expected_value 取决于标签,因此它现在是一个函数而不是单个数字。

[3]:
explainer = shap.TreeExplainer(model, X, feature_perturbation="interventional", model_output="log_loss")
explainer.shap_values(X.iloc[:10, :], y[:10]).sum(1) + np.array([explainer.expected_value(v) for v in y[:10]])
[3]:
array([8.43887488e-04, 2.47898585e-01, 1.17997435e-02, 7.11527711e-02,
       6.41849874e-01, 1.76084475e+00, 5.70285151e-03, 8.60033255e-01,
       4.78233521e-04, 6.43796897e-03])