我在阅读https://towardsdatascience.com/explain-your-model-with-the-shap-values-bc36aac4de3d,尝试让force_plot
输出图像。
我使用的是Ubuntu 20.04上的Python 3.8.5
我运行了以下代码:
shap.initjs()# Write in a functionrandom_picks = np.arange(1,330,50) # Every 50 rowsS = 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>
我不是Python专家,所以我尝试查看这些数据:
display(z)
但display
未定义。
而print(z)
只返回对象的名称,并不能帮助我看到绘制的图像。
我也尝试使用已经加载的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)