【问题标题】:returned a value having type `Figure` which is not JSON serializable返回一个类型为“Figure”的值,它不是 JSON 可序列化的
【发布时间】:2021-07-16 08:06:25
【问题描述】:

我正在构建一个可用于预测销售的 Python Dash 应用程序。例如,

  1. 用户应在应用程序上选择商店 ID
  2. 将使用 LSTM 模型来预测销售额
  3. 应在网络应用程序上显示预测图表

我收到一条错误消息,指出“返回了一个类型为 Figure 的值,它不是 JSON 可序列化的。”尝试运行应用程序时。

请让我知道我做错了什么。

在下面找到代码和输出。

####APP Layout#####
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objs as go
from dash.dependencies import Input, Output
from keras.models import load_model
from sklearn.preprocessing import MinMaxScaler
import numpy as np
import numpy as np, pandas as pd, matplotlib.pyplot as plt, keras, itertools
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, LSTM, Dropout


app = dash.Dash()
server = app.server

Dataset = pd.read_csv("weeklysales.csv")

df=Dataset[["store_Id", "Normalized_sales"]]

model=load_model("model.h5")


#app = dash.Dash(__name__,external_stylesheets=external_stylesheets)
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div(style={'backgroundColor': 'white'},children=[
html.P(html.H1(children='Sales Forecast',style={
            'textAlign': 'center',
            'height': '60px',
    'line-height': '60px',
    'border-bottom': 'thin lightgrey solid',
            'color': 'black'
        })),
html.Label('store_ID',style={
            'color': 'black',
            'font-size':25
        }),
dcc.Dropdown(id = 'g3',options=[
                                {'label': '11362691', 'value': '11362691'},
                                {'label': '108110', 'value': '108110'},
                                {'label': '145325821', 'value': '145325821'},
                                {'label': '3', 'value': '3'},
                                {'label': '4', 'value': '4'},
                                {'label': '5 or above', 'value': '5'}
                            ],style = dict(
                            width = '30%',
                            display = 'inline-block',
                            verticalAlign = "middle"
                            )),
dcc.Graph(id='example'),

html.Div([html.Button(id='submit_button',
                    n_clicks=0,
                    children='Submit',
                    style={'fontSize': 18, 'marginLeft': '30px', 'backgroundColor': 'white'}
                    )

    ], style={'display': 'inline-block'})
])



@app.callback(Output(component_id='submit-val', component_property='fig'), 
              [Input(component_id='g3', component_property='value')])'''

@app.callback(
    dash.dependencies.Output('example', 'figure'),
    [dash.dependencies.Input('g3', 'value')]
)

def update_graph(value):
    #print(value)
    value = int(value)
    sales_data=df[df['repoID']==value]
    s_data=sales_data.Normalized_sales
    s_forecast=s_data[-20:].values
    series = np.array(s_forecast)
    series=np.reshape(series,(1,series.shape[0],1))

    predictions = np.zeros(12)
    predictions[0] = model.predict(series, batch_size = 1)
    n_ahead = 12
    if n_ahead > 1:
        for i in range(1,n_ahead):
            x_new = np.append(series[0][1:],predictions[i-1])
            series = x_new.reshape(1,x_new.shape[0],1)
            predictions[i] = model.predict(series,batch_size = 1)
            
    Final_Score=predictions.reshape(12)
    Final_Score[Final_Score<0] = 0

        # data to be plotted 
    x = np.arange(start=1, stop=13, step=1)
    #first = go.line(x, Final_Score)
    #data = [first]
        #print(i)
        #print(rows[i])
    fig = plt.figure()
    fig.patch.set_facecolor('black') 
    plt.title("Sales for the next 12 weeks")  
    plt.xlabel("Date")  
    plt.ylabel("Sales")
    plt.plot(x, Final_Score, color ="green")  
    return fig


if __name__=='__main__':
    model=load_model("model.h5")
    Dataset = pd.read_csv("weeklysales.csv")
    app.run_server(host='0.0.0.0', port=80)

运行此应用时,我收到以下错误。

dash.exceptions.InvalidCallbackReturnValue: The callback for `<Output `example.figure`>`
returned a value having type `Figure`
which is not JSON serializable.


The value in question is either the only value returned,
or is in the top level of the returned list,

and has string representation
`Figure(432x288)`

In general, Dash properties can only be
dash components, strings, dictionaries, numbers, None,
or lists of those.

请帮助我解决此问题。提前谢谢!

【问题讨论】:

    标签: python lstm plotly-dash forecast


    【解决方案1】:

    您正在返回一个 matplotlib 图形对象,该对象在 Dash 中不受支持。如果您返回一个绘图对象,它应该可以工作。

    【讨论】:

    • 我收到了相同的错误消息,其中包含从 plotly.express.bar 返回的数字。
    【解决方案2】:

    我遇到了一个非常相似的问题,这是因为我的 Plotly.plot 中的一个 y 值是 dash 不知道的数据类型 (sympy.float)。如果您使用外部模块来计算结果,请确保返回的数字是浮点数,方法是先检查它们,然后再将它们传递给 dash。

    【讨论】:

      猜你喜欢
      • 2022-06-12
      • 2021-09-22
      • 2021-12-09
      • 1970-01-01
      • 2021-06-22
      • 1970-01-01
      • 2021-11-27
      • 2016-04-15
      • 2020-08-04
      相关资源
      最近更新 更多