mirror of
https://gitlab.com/CIEFWorldwideSdnBhd/cief-dashboard.git
synced 2026-08-19 04:24:13 +00:00
86 lines
2.9 KiB
Python
86 lines
2.9 KiB
Python
from app import *
|
|
from mlxtend.regressor import LinearRegression
|
|
|
|
def get_predict(df):
|
|
feature_names=df.columns.to_list()[1:]
|
|
target_name=df.columns.to_list()[1]
|
|
# use 60 days to predict
|
|
window_size=60
|
|
x=[]
|
|
y=[]
|
|
for index in range(len(df)):
|
|
if index >= window_size:
|
|
features=np.array([])
|
|
for feature_name in feature_names:
|
|
feature=df.loc[index-window_size:index-1, feature_name].to_numpy()
|
|
features=np.append(features,feature)
|
|
x.append(features)
|
|
target=df.loc[index, target_name]
|
|
y.append(target)
|
|
x=np.array(x)
|
|
y=np.array(y)
|
|
|
|
# train
|
|
model = LinearRegression()
|
|
model.fit(x, y)
|
|
|
|
# current
|
|
days=60
|
|
plot_df=df.copy()
|
|
plot_df["Type"] = 'Current'
|
|
# predict
|
|
for i in range(days):
|
|
index=len(plot_df)-window_size
|
|
predict_x=np.array([])
|
|
for feature_name in feature_names:
|
|
feature=plot_df[feature_name].iloc[index:].to_numpy()
|
|
predict_x=np.append(predict_x,feature)
|
|
# transform
|
|
predict_x=np.array([predict_x])
|
|
|
|
# predict
|
|
predict_y = model.predict(predict_x)
|
|
|
|
predict_date=plot_df['Date'].iloc[-1]+pd.Timedelta(1, unit='D')
|
|
predict = pd.DataFrame({'Date':predict_date, feature_names[1]:plot_df[feature_names[1]].mean(), feature_names[0]:predict_y, 'Type':'Predict'})
|
|
plot_df = pd.concat([plot_df,predict])
|
|
plot_df.reset_index(drop=True, inplace=True)
|
|
plot_df.sort_values(['Date'],inplace=True)
|
|
return(plot_df)
|
|
|
|
# layout
|
|
ml_list=['Predict Covid-19 Fatal Rate', 'Predict CBM']
|
|
layout = html.Div([
|
|
dcc.Dropdown(
|
|
id='input-ml',
|
|
options=[{'label':a, 'value':i} for i, a in enumerate(ml_list)]),
|
|
dcc.Graph(id='output-predict_fatal_rate')
|
|
])
|
|
|
|
# use default option
|
|
@app.callback(Output('input-ml', 'value'),
|
|
Input('data-machine_learning', 'data'))
|
|
def get_ml(data):
|
|
return(0)
|
|
|
|
@app.callback(Output('output-predict_fatal_rate', 'figure'),
|
|
Input('input-ml', 'value'),
|
|
State('data-machine_learning', 'data'))
|
|
def update_output(selected_ml, data):
|
|
to_df(data)
|
|
if selected_ml==0:
|
|
covid_world_wide_fatal_rate=data['covid_world_wide_fatal_rate']
|
|
predict_fatal_rate=get_predict(covid_world_wide_fatal_rate)
|
|
fig_predict_fatal_rate = px.line(predict_fatal_rate, x="Date", y='Death percentage', color='Type', title='Fatal Rate Prediction')
|
|
fig_predict_fatal_rate.update_yaxes(tickformat=".2%")
|
|
update_theme(fig_predict_fatal_rate)
|
|
return(fig_predict_fatal_rate)
|
|
elif selected_ml==1:
|
|
cbm_ctn=data['cbm_ctn']
|
|
predict_cbm=get_predict(cbm_ctn)
|
|
fig_predict_cbm = px.line(predict_cbm, x="Date", y='Daily CBM', color='Type', title='CBM Prediction')
|
|
update_theme(fig_predict_cbm)
|
|
return(fig_predict_cbm)
|
|
else:
|
|
raise(PreventUpdate)
|