如何在streamlit中缓存绘图?

vpv*_*inc 6 matplotlib shap streamlit

我在 Streamlit 中构建了一个仪表板,您可以在其中选择 client_ID 并显示 SHAP 图(瀑布图和力图)来解释该客户的信用违约预测。

我还想显示整个列车数据集的 SHAP 摘要图。每次进行新的预测时,后者都不会改变,并且需要花费大量时间来绘制,所以我想缓存它。我想最好的方法是使用 st.cache 但我没能做到。

下面是我在 main.py 中尝试失败的代码:我首先定义要缓存输出的函数(图),然后在 st.pyplot 中执行输出。它可以在没有 st.cache 装饰器的情况下工作,但是一旦我添加它并重新运行应用程序,函数summary_plot_all就会无限期地运行

在:

@st.cache    
def summary_plot_all():
    fig, axes = plt.subplots(nrows=1, ncols=1)
    shap.summary_plot(shapvs[1], prep_train.iloc[:, :-1].values, 
    prep_train.columns, max_display=50)
    return fig
    
st.pyplot(summary_plot_all())
Run Code Online (Sandbox Code Playgroud)

OUT(在 Streamlit 应用程序中显示)

运行summary_plot_all()。

有谁知道出了什么问题或者在streamlit中缓存情节的更好方法?

version of packages:
streamlit==0.84.1, 
matplotlib==3.4.2, 
shap==0.39.0
Run Code Online (Sandbox Code Playgroud)

Plu*_*ile 1

尝试

import matplotlib

@st.cache(hash_funcs={matplotlib.figure.Figure: lambda _: None})
def summary_plot_all():
    fig, axes = plt.subplots(nrows=1, ncols=1)
    shap.summary_plot(shapvs[1], prep_train.iloc[:, :-1].values, 
    prep_train.columns, max_display=50)
    return fig
Run Code Online (Sandbox Code Playgroud)

检查这个streamlitgithub问题