有两种方法可以参考。
- xgboost 的
pred_contribs
参数:
import lightgbm as lgb
import numpy as np
import pandas as pd
import sklearn
X, y = sklearn.datasets.load_breast_cancer(return_X_y=True)
model = xgb.XGBClassifier(
)
model.fit(X, y)
model._Booster.predict(xgb.DMatrix(X[[0],:]),pred_contribs=True) # for first sample, each feature's contribu
# array([[ 0.01069788, 0.5564505 , 0. , -0.18979889, -0.12519032,
# 0.0419167 , -0.04723313, -1.0029427 , 0.00691214, 0.0219936 ,
# -0.24528527, -0.01379179, -0.08468378, -0.870576 , 0.00372334,
# 0.11168513, -0.01564308, 0.01463292, 0.03310397, 0.01167833,
# -0.70834243, 1.7004861 , -0.53104496, -1.2110311 , -0.2576103 ,
# -0.07476614, -0.40844473, -1.656179 , -0.02658875, -0.03065292,
# 0.9892135 ]], dtype=float32)
- eli5 的实现
https://github.com/eli5-org/eli5/blob/69637074ad07cdb0d0aa3a650302a721c9272e4b/eli5/xgboost.py#L239