File size: 2,258 Bytes
04affa2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1fc725
04affa2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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)