Spaces:
Sleeping
Sleeping
import pandas as pd | |
from prophet import Prophet | |
import plotly.express as px | |
import gradio as gr | |
from prophet.plot import plot_plotly, plot_components_plotly | |
def forecast_timeseries(data_file, forecast_periods): | |
# Load the input data | |
df = pd.read_csv(data_file.name,encoding='utf-8') | |
df['WEIGHT_LBS'] = df['WEIGHT_LBS'].astype('int64') | |
df = df.rename(columns={'RECV_DATE': 'ds', 'WEIGHT_LBS': 'y'}) | |
weekly_df = df[['ds','y']].sort_values('ds') | |
weekly_df = weekly_df.groupby('ds',as_index=False)['y'].sum() | |
weekly_df['ds'] = pd.to_datetime(weekly_df['ds']) | |
weekly_df.set_index('ds', inplace=True) | |
weekly_df = weekly_df.resample('w').sum() | |
weekly_df.reset_index(inplace=True) | |
train = weekly_df[:int(0.8*(weekly_df.shape[0]))] | |
test = weekly_df[int(0.8*(weekly_df.shape[0]))+1:] | |
m = Prophet() | |
m.fit(train[['ds','y']]) | |
# Create a future dataframe for forecasting | |
future = m.make_future_dataframe(periods=int(forecast_periods),freq='W') | |
# Make predictions | |
forecast = m.predict(future) | |
# Extract relevant columns from the forecast | |
forecast_data = forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']] | |
# Plot the forecasted data with upper and lower bounds | |
# fig = px.line(forecast, x='ds', y='yhat', title='Forecasted Time Series') | |
# fig.add_scatter(x=df['ds'], y=df['y'], mode='markers', name='Actual Values') | |
# fig.add_scatter(x=forecast['ds'], y=forecast['yhat_upper'], mode='lines', name='Upper Bound') | |
# fig.add_scatter(x=forecast['ds'], y=forecast['yhat_lower'], mode='lines', name='Lower Bound') | |
fig = plot_plotly(m, forecast) | |
fig1 = plot_components_plotly(m, forecast) | |
return df.head(),fig,fig1 ,forecast_data | |
# Define input and output interfaces for the Gradio app | |
inputs = [ | |
gr.inputs.File(label="Upload CSV File"), | |
gr.inputs.Number(label="Forecast Periods", default=7), | |
] | |
outputs = [ | |
gr.Dataframe(label="Input Data"), | |
gr.Plot(label="Forecast Plot"), | |
gr.Plot(label="Trends"), | |
gr.Dataframe(label="Forecast Results"), | |
] | |
# Create the Gradio app | |
iface = gr.Interface(fn=forecast_timeseries, inputs=inputs, outputs=outputs, title="Time Series Forecasting with Prophet") | |
iface.launch(inline = False) | |