SHAP

SHAP [https://github.com/slundberg/shap] 用于树模型的解释性工作。主要介绍图的二次调整。

二次修改

import shap
from matplotlib import pyplot as plt

explainer = shap.Explainer(model)
df = pd.DataFrame(record)
df.columns = model.feature_names
shap_values = explainer(df)
# Init figure before plot by shap. Or use plot.gcf() to get figure after plot.
figure = plt.figure()
# Set show=False to allow modifaction on plots.
shap.plots.waterfall(shap_values[0], show=False)
axs = figure.get_axes()
ax = axs[0]
labels = ax.get_yticklabels()
feature_names = []
# The labels have 2 * feature_count, one for black feature_name, one for grey feature value.
for i in labels:
    if i.get_color() == "#999999":
        feature_names.append(i.get_text())
for f in feature_names[::-1]:
    print(f)
figure.set_figwidth(12)
# Set tight_layout() to ensure whole feature names can involved.
figure.tight_layout()
Written on July 29, 2021