In [1]:
import pandas as pd
import numpy as np
from fbprophet import Prophet
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['figure.figsize']=(20,10)
plt.style.use('ggplot')
In [2]:
sales_df = pd.read_csv('../examples/retail_sales.csv', index_col='date', parse_dates=True)
In [3]:
sales_df.head()
Out[3]:
In [4]:
df = sales_df.reset_index()
In [5]:
df.head()
Out[5]:
Let's rename the columns as required by fbprophet. Additioinally, fbprophet doesn't like the index to be a datetime...it wants to see 'ds' as a non-index column, so we won't set an index differnetly than the integer index.
In [6]:
df=df.rename(columns={'date':'ds', 'sales':'y'})
In [7]:
df.head()
Out[7]:
Now's a good time to take a look at your data. Plot the data using pandas' plot
function
In [8]:
df.set_index('ds').y.plot()
Out[8]:
When working with time-series data, its good to take a look at the data to determine if trends exist, whether it is stationary, has any outliers and/or any other anamolies. Facebook prophet's example uses the log-transform as a way to remove some of these anomolies but it isn't the absolute 'best' way to do this...but given that its the example and a simple data series, I'll follow their lead for now. Taking the log of a number is easily reversible to be able to see your original data.
To log-transform your data, you can use numpy's log() function
In [9]:
df['y'] = np.log(df['y'])
In [10]:
df.tail()
Out[10]:
In [11]:
df.set_index('ds').y.plot()
Out[11]:
As you can see in the above chart, the plot looks the same as the first one but just at a different scale.
Now, let's set prophet up to begin modeling our data.
Note: Since we are using monthly data, you'll see a message from Prophet saying Disabling weekly seasonality. Run prophet with weekly_seasonality=True to override this.
This is OK since we are workign with monthly data but you can disable it by using weekly_seasonality=True
in the instantiation of Prophet.
In [12]:
model = Prophet()
model.fit(df);
Forecasting is fairly useless unless you can look into the future, so we need to add some future dates to our dataframe. For this example, I want to forecast 2 years into the future, so I'll built a future dataframe with 24 periods since we are working with monthly data. Note the freq='m'
inclusion to ensure we are adding 24 months of data.
This can be done with the following code:
In [13]:
future = model.make_future_dataframe(periods=24, freq = 'm')
future.tail()
Out[13]:
To forecast this future data, we need to run it through Prophet's model.
In [14]:
forecast = model.predict(future)
The resulting forecast dataframe contains quite a bit of data, but we really only care about a few columns. First, let's look at the full dataframe:
In [15]:
forecast.tail()
Out[15]:
We really only want to look at yhat, yhat_lower and yhat_upper, so we can do that with:
In [16]:
forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail()
Out[16]:
In [17]:
model.plot(forecast);
Personally, I'm not a fan of this visualization so I like to break the data up and build a chart myself. The next section describes how I build my own visualization for Prophet modeling
In order to build a useful dataframe to visualize our model versus our original data, we need to combine the output of the Prophet model with our original data set, then we'll build a new chart manually using pandas and matplotlib.
First, let's set our dataframes to have the same index of ds
In [18]:
df.set_index('ds', inplace=True)
forecast.set_index('ds', inplace=True)
Now, we'll combine the original data and our forecast model data
In [19]:
viz_df = sales_df.join(forecast[['yhat', 'yhat_lower','yhat_upper']], how = 'outer')
If we look at the head()
, we see the data has been joined correctly but the scales of our original data (sales) and our model (yhat) are different. We need to rescale the yhat colums(s) to get the same scale, so we'll use numpy's exp
function to do that.
In [20]:
viz_df.head()
Out[20]:
In [21]:
viz_df['yhat_rescaled'] = np.exp(viz_df['yhat'])
In [22]:
viz_df.head()
Out[22]:
Let's take a look at the sales
and yhat_rescaled
data together in a chart.
In [23]:
viz_df[['sales', 'yhat_rescaled']].plot()
Out[23]:
You can see from the chart that the model (blue) is pretty good when plotted against the actual signal (orange) but I like to make my vizualization's a little better to understand. To build my 'better' visualization, we'll need to go back to our original sales_df
and forecast
dataframes.
First things first - we need to find the 2nd to last date of the original sales data in sales_df
in order to ensure the original sales data and model data charts are connected.
In [24]:
sales_df.index = pd.to_datetime(sales_df.index) #make sure our index as a datetime object
connect_date = sales_df.index[-2] #select the 2nd to last date
Using the connect_date
we can now grab only the model data that after that date (you'll see why in a minute). To do this, we'll mask the forecast data.
In [25]:
mask = (forecast.index > connect_date)
predict_df = forecast.loc[mask]
In [26]:
predict_df.head()
Out[26]:
Now, let's build a dataframe to use in our new visualization. We'll follow the same steps we did before.
In [27]:
viz_df = sales_df.join(predict_df[['yhat', 'yhat_lower','yhat_upper']], how = 'outer')
viz_df['yhat_scaled']=np.exp(viz_df['yhat'])
Now, if we take a look at the head()
of viz_df
we'll see 'NaN's everywhere except for our original data rows.
In [28]:
viz_df.head()
Out[28]:
If we take a look at the tail()
of the viz_df
you'll see we have data for the forecasted data and NaN's for the original data series.
In [29]:
viz_df.tail()
Out[29]:
In [30]:
fig, ax1 = plt.subplots()
ax1.plot(viz_df.sales)
ax1.plot(viz_df.yhat_scaled, color='black', linestyle=':')
ax1.fill_between(viz_df.index, np.exp(viz_df['yhat_upper']), np.exp(viz_df['yhat_lower']), alpha=0.5, color='darkgray')
ax1.set_title('Sales (Orange) vs Sales Forecast (Black)')
ax1.set_ylabel('Dollar Sales')
ax1.set_xlabel('Date')
L=ax1.legend() #get the legend
L.get_texts()[0].set_text('Actual Sales') #change the legend text for 1st plot
L.get_texts()[1].set_text('Forecasted Sales') #change the legend text for 2nd plot
This visualization is much better (in my opinion) than the default fbprophet plot. It is much easier to quickly understand and describe what's happening. The orange line is actual sales data and the black dotted line is the forecast. The gray shaded area is the uncertaintity estimation of the forecast.
In [ ]: