<jupyter_start><jupyter_text>Forecasting - Facebook Prophet https://facebook.github.io/prophet/https://research.fb.com/blog/2017/02/prophet-forecasting-at-scale/https://peerj.com/preprints/3190.pdf<jupyter_code>import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt





%matplotlib inline
mpl.rcParams['figure.figsize'] = (16, 10)
pd.set_option('display.max_rows', 500)

import plotly.graph_objects as go
from fbprophet import Prophet

%matplotlib inline
plt.style.use('fivethirtyeight')

def mean_absolute_percentage_error(y_true, y_pred): 
    y_true, y_pred = np.array(y_true), np.array(y_pred)
    return np.mean(np.abs((y_true - y_pred) / y_true)) * 100<jupyter_output><empty_output><jupyter_text>Trivial Forecast (rolling mean)<jupyter_code>df = pd.DataFrame({'X': np.arange(0,10)})
df['y']=df.rolling(3).mean()
df
df_all = pd.read_csv("C:/Users/LATITUDE/ads_covid-19/data/processed/COVID_small_flat_table.csv",sep=';')
df=df_all[['date','Germany']]
df=df.rename(columns={'date': 'ds',
                        'Germany': 'y'})
ax = df.set_index('ds').plot(figsize=(12, 8),
                             logy=True)
ax.set_ylabel('Daily Number of confimed cases')
ax.set_xlabel('Date')

plt.show()

# set the uncertainty interval to 95% (the Prophet default is 80%)

my_model = Prophet(growth='logistic') 
df['cap']=1000000.
my_model.fit(df)
# defining the periods and the frequency 'D'== days

future_dates = my_model.make_future_dataframe(periods=7, freq='D')
future_dates['cap']=1000000. # only mandatory for the logistic model
future_dates.tail()
forecast = my_model.predict(future_dates)
my_model.plot(forecast,
              uncertainty=True );
import plotly.offline as py
from fbprophet.plot import plot_plotly

fig = plot_plotly(my_model, forecast)  # This returns a plotly Figure

fig.update_layout(
    width=1024,
    height=900,
    xaxis_title="Time",
    yaxis_title="Confirmed infected people (source johns hopkins csse, log-scale)",
)
fig.update_yaxes(type="log",range=[1.1,5.5])
py.iplot(fig)

forecast.sort_values(by='ds').head()
my_model.plot_components(forecast);
forecast[['ds','trend']].set_index('ds').plot(figsize=(12, 8),logy=True)<jupyter_output><empty_output><jupyter_text>Cross Validation<jupyter_code>from fbprophet.diagnostics import cross_validation
df_cv = cross_validation(my_model, 
                         initial='40 days',
                         period='1 days',
                         horizon = '7 days')
df_cv.sort_values(by=['cutoff','ds'])[0:12]
df_cv.head()
from fbprophet.diagnostics import performance_metrics
df_p = performance_metrics(df_cv)
df_p
from fbprophet.plot import plot_cross_validation_metric
fig = plot_cross_validation_metric(df_cv, metric='mape',)<jupyter_output><empty_output><jupyter_text>Diagonal Plot* gives a good understanding for the under and over estimation w.r.t. magnitude<jupyter_code>horizon='7 days'
df_cv['horizon']=df_cv.ds-df_cv.cutoff

date_vec=df_cv[df_cv['horizon']==horizon]['ds']
y_hat=df_cv[df_cv['horizon']==horizon]['yhat']
y=df_cv[df_cv['horizon']==horizon]['y']
df_cv_7=df_cv[df_cv['horizon']==horizon]
df_cv_7.tail()
type(df_cv['horizon'][0])
fig, ax = plt.subplots(1, 1)


ax.plot(np.arange(max(y)),np.arange(max(y)),'--',label='diagonal')
ax.plot(y,y_hat,'-',label=horizon)  # horizon is a np.timedelta objct

ax.set_title('Diagonal Plot')
ax.set_ylim(10, max(y))

ax.set_xlabel('truth: y')
ax.set_ylabel('prediciton: y_hat')
ax.set_yscale('log')

ax.set_xlim(10, max(y))
ax.set_xscale('log')
ax.legend(loc='best',
           prop={'size': 16});<jupyter_output><empty_output><jupyter_text>Trivial forecast* Example trivial forecast, prediciton 7 days into the future<jupyter_code>def mean_absolute_percentage_error(y_true, y_pred): 
    ''' MAPE calculation '''
    y_true, y_pred = np.array(y_true), np.array(y_pred)
    return np.mean(np.abs((y_true - y_pred) / y_true)) * 100
parse_dates=['date']
df_all = pd.read_csv(r"C:/Users/LATITUDE/ads_covid-19/data/processed/COVID_small_flat_table.csv",sep=';',parse_dates=parse_dates)
df_trivial=df_all[['date','Germany']]
df_trivial=df_trivial.rename(columns={'date': 'ds',
                        'Germany': 'y'})<jupyter_output><empty_output><jupyter_text>Rolling Mean<jupyter_code>df_trivial['y_mean_r3']=df_trivial.y.rolling(3).mean()
df_trivial['cutoff']=df_trivial['ds'].shift(7)
df_trivial['y_hat']=df_trivial['y_mean_r3'].shift(7)
df_trivial['horizon']=df_trivial['ds']-df_trivial['cutoff']
print('MAPE: '+str(mean_absolute_percentage_error(df_trivial['y_hat'].iloc[12:,], df_trivial['y'].iloc[12:,])))
df_trivia<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.16030204962243796, 'fraction_numerical': 0.020711974110032363, 'mean_word_length': 5.981927710843373, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 25, 'https://': 3, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '193021', 'license': 'MIT', 'n_tokens_mistral': 1867, 'n_tokens_neox': 1753, 'n_words': 261, 'path': 'notebooks/Facebook Prophet.ipynb', 'repo_name': 'iamnawazahmed/Covid_19_Data_Analysis', 'size': '4635'}