【问题标题】:Cannot display SHAP text visualization in Streamlit无法在 Streamlit 中显示 SHAP 文本可视化
【发布时间】:2022-01-13 13:07:55
【问题描述】:

我正在尝试构建我的 NLP 项目的仪表板。所以我使用 BERT 模型进行预测,使用 SHAP 包进行可视化,使用 Streamlit 来创建仪表板:

tokenizer = AutoTokenizer.from_pretrained(model_name_cla)
model = AutoModelForSequenceClassification.from_pretrained(model_name_cla)
labels = ['1- Tarife','2- Dateneingabe','3- Bestätigungsmail','4- Kundenbetreuung','5- Aufwand vom Vergleich bis Abschluss',
          '6- After-sales Wechselprozess','7 - Werbung/VX Kommunikation','8 - Sonstiges','9 - Nicht auswertbar']

def f(x):
    tv = torch.tensor([tokenizer.encode(v, padding='max_length', max_length=128, truncation=True) for v in x])
    attention_mask = (tv!=0).type(torch.int64)
    outputs = model(tv,attention_mask=attention_mask)[0].detach().cpu().numpy()
    scores = (np.exp(outputs).T / np.exp(outputs).sum(-1)).T
    val = sp.special.logit(scores)
    return val

text = ['This is just a test']

# build an explainer using a token masker
explainer = shap.Explainer(f, tokenizer, output_names=labels)

shap_values = explainer(text, fixed_context=1)

shap.plots.text(shap_values)

代码在我的 jupyter 笔记本中运行良好,但是当我尝试将其作为 .py 文件执行时,没有任何反应。它既不显示任何内容,也不抛出错误。我的控制台只是在执行时返回这个:

>

如何在流光中显示我的图表?

【问题讨论】:

    标签: python streamlit shap


    【解决方案1】:

    这可以用Streamlit Components 和最新的SHAP v0.36+(定义一个新的getjs 方法)可视化,以绘制JS SHAP plots

    (一些像summary_plot这样的图实际上是Matplotlib,可以用st.pyplot绘制)

    import streamlit as st
    import streamlit.components.v1 as components
    
    def st_shap(plot, height=None):
        shap_html = f"<head>{shap.getjs()}</head><body>{plot.html()}</body>"
        components.html(shap_html, height=height)
    
    st_shap(shap.plots.text(shap_values),400)
    

    streamlit 此处 - Display SHAP diagrams with Streamlit 中查找有关可视化形状的更详细讨论

    【讨论】:

    • 我不知道为什么但我总是得到这个错误:AttributeError: 'NoneType' object has no attribute 'html'
    • 你实际上得到了None html。与您在问题中添加的代码相同吗?
    • 是的,完全一样。我还为此更新了 shap-
    • 您能否检查一下您是否真的从数据中生成了任何可视化??
    • 当我在我的 jupyter 笔记本中执行代码 (shap.plots.text(shap_values)) 时,它会生成预期的情节。所以我想我正在生成一个......或者我错过了什么?
    猜你喜欢
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-19
    • 1970-01-01
    • 1970-01-01
    • 2017-10-03
    • 2018-08-14
    • 1970-01-01
    相关资源
    最近更新 更多