Getting Started with Facebook Prophet | by Greg Rafferty | Towards Data Science

This post contains an excerpt from my new book all about Facebook Prophet. The book is available for purchase on Amazon. The full contents of the book are listed at the end of this post!
If you find this article useful and would like to use Prophet to improve your forecasts, please consider buying the full book at https://amzn.to/373oIcf.
The longest record of direct measurements of CO­2 in the atmosphere was started in March of 1958 by Charles David Keeling of the Scripps Institution of Oceanography. Keeling was based in La Jolla, California, but had received permission from the National Oceanic and Atmospheric Administration (NOAA) to use their facility located two miles above sea level on the northern slope of Mauna Loa, a volcano on the island of Hawaii, to collect carbon dioxide samples. At that elevation, Keeling’s measurements would be unaffected by local releases of CO2 such as by nearby factories.
In 1961, Keeling published the data he had collected thus far, establishing that there was strong seasonal variation in CO2 levels and that they were rising steadily, a trend that later became known as the Keeling Curve. By May 1974, the NOAA began their own parallel measurements and have continued since then. The keeling curve graph is as follows:
With its seasonality and increasing trend, this curve makes a good candidate to try out Prophet. This data set contains over 19,000 daily observations across 53 years. The unit of measurement for CO2 is PPM, or parts per million, a measure of CO2 molecules per million molecules of air.
To begin our model, we need to import the necessary libraries, pandas and Matplotlib, and import the Prophet class from the fbprophet package.
import pandas as pdimport matplotlib.pyplot as pltfrom fbprophet import Prophet
As input, Prophet always requires a pandas DataFrame with two columns:
ds, for datestamp, should be a datestamp or timestamp column in a format expected by pandas.
y, a numeric column containing the measurement we wish to forecast.
Here, we use pandas to import the data, in this case a csv file [Note: This csv can be downloaded at https://git.io/JYG6T], and then load it into a DataFrame. Note that we also convert the ds column to a pandas datetime format, to ensure that Pandas is correctly identifying it as dates and not simply loading it as an alphanumeric string.
df = pd.read_csv(‘co2-ppm-daily_csv.csv’)df[‘date’] = pd.to_datetime(df[‘date’])df.columns = [‘ds’, ‘y’]
If you’re familiar with the scikit-learn (sklearn) package, you’ll feel right at home in Prophet because it was designed to operate in a similar way. Prophet follows the sklearn paradigm of first creating an instance of the model class before calling the fit and predict methods.
model = Prophet()model.fit(df)
In that single fit command, Prophet analyzed the data and isolated both the seasonality and trend without requiring us to specify any additional parameters. It has not yet made any future forecast though. To do that, we need to first make a DataFrame of future dates and then call the predict method. The make_future_dataframe method requires us to specify the number of days we intend to forecast out. In this case, we will choose ten years, or 365 days times 10.
future = model.make_future_dataframe(periods=365 * 10)forecast = model.predict(future)
At this point, the forecast DataFrame contains Prophet’s prediction for CO2 concentrations going ten years into the future. We will explore that DataFrame in a moment, but first let’s plot the data using Prophet’s plot functionality. The plot method is built upon Matplotlib; it requires a DataFrame output from the predict method (our forecast DataFrame in this example).
We’re labeling the axes with the optional xlabel and ylabel arguments, but just sticking with the default for the optional figsize argument. Note that I am also adding a title using raw Matplotlib syntax; because the Prophet plot is built upon Matplotlib, anything you can do to a Matplotlib figure can be performed here as well. Also, don’t be confused by the odd ylabel text with the dollar signs; that just tells Matplotlib to use its own TeX-like engine to make the subscript in CO2.
fig = model.plot(forecast, xlabel=’Date’, ylabel=r’CO$_2$ PPM’)plt.title(‘Daily Carbon Dioxide Levels Measured at Mauna Loa’)plt.show()
The graph is as follows:
And that’s it! In those 12 lines of code, we have arrived at our ten year forecast.
Now, let’s take a look at that forecast DataFrame by displaying the first three rows (I’ve transposed it here, in order to better see the column names on the page) and learn how these values were used in the above chart:
forecast.head(3).T
After running that command, you should see the following table print out:
The following is a description of each of the columns in the forecast DataFrame:
‘ds’ — Datestamp or timestamp which values in that row pertain to
‘trend’ — Value of the trend component alone
‘yhat_lower’ — Lower bound of the uncertainty interval around the final prediction
‘yhat_upper’ — Upper bound of the uncertainty interval around the final prediction
‘trend_lower’ — Lower bound of the uncertainty interval around the trend component
‘trend_upper’ — Upper bound of the uncertainty interval around the trend component
‘additive_terms’ — Combined value of all additive seasonalities
‘additive_terms_lower’ — Lower bound of the uncertainty interval around the additive seasonalities
‘additive_terms_upper’ — Upper bound of the uncertainty interval around the additive seasonalities
‘weekly’ — Value of the weekly seasonality component
‘weekly_lower’ — Lower bound of the uncertainty interval around the weekly component
‘weekly_upper’ — Upper bound of the uncertainty interval around the weekly component
‘yearly’ — Value of the yearly seasonality component
‘yearly_lower’ — Lower bound of the uncertainty interval around the yearly component
‘yearly_upper’ — Upper bound of the uncertainty interval around the yearly component
‘multiplicative_terms’ — Combined value of all multiplicative seasonalities
‘multiplicative_terms_lower’ — Lower bound of the uncertainty interval around the multiplicative seasonalities
‘multiplicative_terms_upper’ — Upper bound of the uncertainty interval around the multiplicative seasonalities
‘yhat’ — Final predicted value; a combination of ‘trend’, ‘multiplicative_terms’, and ‘additive_terms’
If the data contains a daily seasonality, then columns for ‘daily’, ‘daily_upper’, and ‘daily_lower’ will also be included, following the pattern established with the ‘weekly’ and ‘yearly’ columns. Later chapters will include discussion and examples of both the additive/multiplicative seasonalities and of the uncertainty intervals.
In the forecast plot above, the black dots represent the actual recorded y values we fit on (those in the df[‘y’] column) whereas the solid line represents the calculated yhat values (the forecast[‘yhat’] column). Note that the solid line extends beyond the range of the black dots where we have forecasted into the future. The lighter shading notable around the solid line in the forecasted region represents the uncertainty interval, bound by forecast[‘yhat_lower’] and forecast[‘yhat_upper’].
Now let’s break down that forecast into its components.
In Chapter 1, History and Development of Time Series Forecasting, Prophet was introduced as an additive regression model. Figures 1.4 and 1.5 showed how individual component curves for the trend and the different seasonalities are added together to create a more complex curve. The Prophet algorithm essentially does this in reverse; it takes a complex curve and decomposes it into its constituent parts. The first step towards greater control of a Prophet forecast is to understand these components so that they can be manipulated individually. Prophet provides a method plot_components to visualize these.
Continuing on with our progress on the Mauna Loa model, plotting the components is as simple as running these commands:
fig2 = model.plot_components(forecast)plt.show()
As you can see in the output plot, Prophet has isolated three components in this data set: the trend, a weekly seasonality, and a yearly seasonality:
The trend constantly increases but seems to have a steepening slope as time progresses — an acceleration of CO2 concentration in the atmosphere. The trend line also shows slim uncertainty intervals in the forecasted year. From this curve, we learn that atmospheric CO2 concentrations were about 320 PPM in 1965. This grew to about 400 by 2015 and we expect about 430 PPM by 2030. However, these exact numbers will vary depending upon the day of the week and the time of year, due to the existence of the seasonality effects.
The weekly seasonality shows that by days of the week, values will vary by about 0.01 PPM — an insignificant amount and most likely due purely to noise and random chance. Indeed, intuition tells us that carbon dioxide levels (when measured far enough away from human activity, as they are on the high slopes of Mauna Loa) do not care much what day of the week it is and are unaffected by it.
We will learn in Chapter 4, Seasonality, how to instruct Prophet not to fit a weekly seasonality, as is prudent in this case. In Chapter 10, Uncertainty Intervals, we will learn how to plot uncertainty for seasonality and ensure that a seasonality such as this can be ignored.
Now looking at the yearly seasonality reveals that carbon dioxide rises throughout the winter and peaks in May or so, while falling in the summer with a trough in October. Measurements of carbon dioxide can be 3 PPM above or 3 PPM below what the trend alone would predict, based upon the time of year. If you refer back to the original data, in the Keeling Curve, you will be reminded that there was a very obvious cyclic nature to the curve, captured with this yearly seasonality.
As simple as that model was, that is often all you need to make very accurate forecasts with Prophet! We used no additional parameters than the defaults and yet achieved very good results.
This excerpt is from chapter 2 of Forecasting Time Series Data with Facebook Prophet available now on Amazon. The book has more than 250 pages of examples, lessons, and descriptions of every single aspect of Prophet and more than 10 instructive datasets are provided to help you learn how to perfect your forecasts by demonstrating Prophet functionality from the simple to the advanced with fully working code.
The full book contains the following chapters:
The History and Development of Time Series ForecastingGetting Started with Facebook ProphetNon-Daily DataSeasonalityHolidaysGrowth ModesTrend ChangepointsAdditional RegressorsOutliers and Special EventsUncertainty IntervalsCross-ValidationPerformance MetricsProductionalizing Prophet
The History and Development of Time Series Forecasting
Getting Started with Facebook Prophet
Non-Daily Data
Seasonality
Holidays
Growth Modes
Trend Changepoints
Additional Regressors
Outliers and Special Events
Uncertainty Intervals
Cross-Validation
Performance Metrics
Productionalizing Prophet
If you enjoyed this Medium post, please consider ordering it here: https://amzn.to/373oIcf. If you do read the book, I would be thrilled to hear your thoughts!