Prophet uses the normal model fitting API. We provide a prophet
function that performs fitting and returns a model object. You can then call predict
and plot
on this model object.
First we read in the data and create the outcome variable.
library(readr)
df <- read_csv('../tests/testthat/data.csv')
#> Parsed with column specification:
#> cols(
#> ds = col_date(format = ""),
#> y = col_double()
#> )
We call the prophet
function to fit the model. The first argument is the historical dataframe. Additional arguments control how Prophet fits the data.
m <- prophet(df)
#> STAN OPTIMIZATION COMMAND (LBFGS)
#> init = user
#> save_iterations = 1
#> init_alpha = 0.001
#> tol_obj = 1e-12
#> tol_grad = 1e-08
#> tol_param = 1e-08
#> tol_rel_obj = 10000
#> tol_rel_grad = 1e+07
#> history_size = 5
#> seed = 164695422
#> initial log joint probability = -15.5191
#> Optimization terminated normally:
#> Convergence detected: relative gradient magnitude is below tolerance
We need to construct a dataframe for prediction. The make_future_dataframe
function takes the model object and a number of periods to forecast:
future <- make_future_dataframe(m, periods = 365)
head(future)
#> ds
#> 1 2012-05-18
#> 2 2012-05-21
#> 3 2012-05-22
#> 4 2012-05-23
#> 5 2012-05-24
#> 6 2012-05-25
As with most modeling procedures in R, we use the generic predict
function to get our forecast:
forecast <- predict(m, future)
head(forecast)
#> ds t trend yhat_lower yhat_upper trend_lower
#> 1 2012-05-18 0.000000000 42.10982 33.03550 39.96755 42.10982
#> 2 2012-05-21 0.004043127 41.52828 31.36199 38.25872 41.52828
#> 3 2012-05-22 0.005390836 41.33444 31.23292 37.85191 41.33444
#> 4 2012-05-23 0.006738544 41.14059 30.71174 37.67929 41.14059
#> 5 2012-05-24 0.008086253 40.94675 30.51604 37.59262 40.94675
#> 6 2012-05-25 0.009433962 40.75290 30.09176 36.86602 40.75290
#> trend_upper seasonal_lower seasonal_upper weekly weekly_lower
#> 1 42.10982 -5.616323 -5.616323 0.9115110 0.9115110
#> 2 41.52828 -6.541880 -6.541880 0.6478262 0.6478262
#> 3 41.33444 -6.683620 -6.683620 0.7374589 0.7374589
#> 4 41.14059 -6.796344 -6.796344 0.8591329 0.8591329
#> 5 40.94675 -6.870829 -6.870829 1.0202820 1.0202820
#> 6 40.75290 -7.214456 -7.214456 0.9115110 0.9115110
#> weekly_upper yearly yearly_lower yearly_upper seasonal yhat
#> 1 0.9115110 -6.527834 -6.527834 -6.527834 -5.616323 36.49349
#> 2 0.6478262 -7.189706 -7.189706 -7.189706 -6.541880 34.98640
#> 3 0.7374589 -7.421079 -7.421079 -7.421079 -6.683620 34.65082
#> 4 0.8591329 -7.655477 -7.655477 -7.655477 -6.796344 34.34425
#> 5 1.0202820 -7.891111 -7.891111 -7.891111 -6.870829 34.07592
#> 6 0.9115110 -8.125967 -8.125967 -8.125967 -7.214456 33.53845
You can use the generic plot
function to plot the forecast, but you must also pass the model in to be plotted:
plot(m, forecast)
Just as in Python, you can plot the components of the forecast. In R, you use the prophet_plot_components
function instead of an instance method:
prophet_plot_components(m, forecast)