形状力图未显示图形:shap.plots._force.AdditiveForceVisualizer

Shap force plot not displaying figure: shap.plots._force.AdditiveForceVisualizer

我正在 https://towardsdatascience.com/explain-your-model-with-the-shap-values-bc36aac4de3d 尝试打印 force_plot

我 运行宁 Python 3.8.5 Ubuntu 20.04

我运行这个代码:

shap.initjs()

# Write in a function

random_picks = np.arange(1,330,50) # Every 50 rows
S = X_test.iloc[random_picks]
def shap_plot(j):
    explainerModel = shap.TreeExplainer(xg_clf)
    shap_values_Model = explainerModel.shap_values(S)
    p = shap.force_plot(explainerModel.expected_value, shap_values_Model[j], S.iloc[[j]])
    return(p)
z = shap_plot(3)

我得到 <shap.plots._force.AdditiveForceVisualizer object at 0x7f1568cac070>

到return.

我不是 python 专家,所以我尝试查看以下数据:

display(z)

未定义。

print(z) 只是 return 对象的名称,并不能帮助我查看绘制的内容。

我也试过使用已经加载的 matplotlib

def shap_plot(j):
    explainerModel = shap.TreeExplainer(xg_clf)
    shap_values_Model = explainerModel.shap_values(S)
    p = shap.force_plot(explainerModel.expected_value, shap_values_Model[j], S.iloc[[j]])
    plt.savefig('tmp.svg')
    plt.close()
    return(p)
shap_plot(3)

但这只是一个空图像。

如果有错误,我没看到。

如何让这个 shap.force_plot 显示图像?

解决方法在手册中:

help(shap.force_plot)

显示

matplotlib : bool
        Whether to use the default Javascript output, or the (less developed) matplotlib output. Using matplotlib can be helpful in scenarios where rendering Javascript/HTML is inconvenient.

的确,运行笔记本对我来说很不方便。

所以为了保存图像:

def shap_plot(j):
    explainerModel = shap.TreeExplainer(xg_clf)
    shap_values_Model = explainerModel.shap_values(S)
    p = shap.force_plot(explainerModel.expected_value, shap_values_Model[j], S.iloc[[j]], matplotlib = True, show = False)
    plt.savefig('tmp.svg')
    plt.close()
    return(p)