【问题标题】:Is there a way to render SHAP or LIME output from Flask to React?有没有办法将 Flask 的 SHAP 或 LIME 输出渲染到 React?
【发布时间】:2020-03-10 15:42:52
【问题描述】:

我正在使用 Flask 在 React JS 项目上部署用 Python 编写的机器学习模型。

但是,需要显示 LIME 或 SHAP 输出。有没有人知道如何将 Flask 的 html 或 js 输出渲染到 React 并显示出来?

以下是我目前以数字形式发送数据的代码,而不是图像/html/js

@app.route('/api/v1', methods=['POST'])
def postTest():
    formData = request.json
    cols = ['TYPE','ORIG', 'DEST', 'DISTANCE']
    flight = []
    for a in cols:
        flight.append(formData[a])
    predic_son = formData['prediction']
    shap_values = explainer.shap_values(np.array(flight).reshape(1,-1))
    res = dict(zip(cols, shap_values[0])) 
    print(type(res))
    return res

获取响应响应的代码:

 fetch('http://localhost:5000/api/v1', {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      method: 'POST',
      body: JSON.stringify(flight)
    }).then(response => response.json()).then(response => console.log(response));

【问题讨论】:

  • 您的 React 应用程序是否将其用作 API 端点?您如何执行请求?
  • 是的,没错。我通过获取得到响应。
  • 我可以发送一个数字列表,但我想返回一个图像来反应
  • 您与您所描述的内容非常矛盾。在您的问题中,您说 如何将 Flask 的 html 或 js 输出呈现到 React 现在您说要返回图像?现在什么是正确的?该图像是在哪里生成的?
  • 假设使用烧瓶在反应页面上显示 Jupyter 笔记本?有任何想法吗?还是还是太模糊了?

标签: reactjs machine-learning flask lime shap


【解决方案1】:

这里是解决办法

uf = BytesIO()
shap.force_plot(explainer.expected_value, 
                shap_values[0], 
                flight, 
                matplotlib = True, 
                show = False)
plt.savefig(buf,
            format = "png",
            dpi = 150,
            bbox_inches = 'tight')
dataToTake = base64.b64encode(buf.getbuffer()).decode("ascii")

使用base 64编码,可以作为图片源,一旦在javascript上检索,只需使用dataToTake作为图片源如:

src = data:image/png;base64,{dataToTake}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-29
    • 2016-08-01
    • 2021-07-27
    • 2021-01-26
    • 2020-07-31
    • 2018-07-03
    • 2022-01-19
    • 2013-08-03
    相关资源
    最近更新 更多