我正在构建一个可用于预测销售额的Python Dash应用程序。例如,
- 用户应该在应用程序上选择商店ID
- LSTM模型将用于预测销售额
- 预测图应显示在web应用程序上
我收到一个错误,说";返回了一个类型为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.
请帮我解决这个问题。提前谢谢!
我遇到了一个非常类似的问题,这是因为Plotly.plot中的一个y值是dash不知道的数据类型(sympy.foat(。如果您使用外部模块来计算结果,请确保返回的数字是浮点数,方法是在将其传递给dash之前先检查它们。
您正在返回一个matplotlib图形对象,Dash不支持该对象。如果您返回一个绘图图形对象,它应该可以工作。