forecaster.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  1. # Copyright (c) 2017-present, Facebook, Inc.
  2. # All rights reserved.
  3. #
  4. # This source code is licensed under the BSD-style license found in the
  5. # LICENSE file in the root directory of this source tree. An additional grant
  6. # of patent rights can be found in the PATENTS file in the same directory.
  7. from __future__ import absolute_import
  8. from __future__ import division
  9. from __future__ import print_function
  10. from __future__ import unicode_literals
  11. from collections import defaultdict
  12. from datetime import timedelta
  13. import pickle
  14. from matplotlib import pyplot as plt
  15. from matplotlib.dates import DateFormatter, MonthLocator
  16. from matplotlib.ticker import MaxNLocator
  17. import numpy as np
  18. import pandas as pd
  19. # fb-block 1 start
  20. import pkg_resources
  21. # fb-block 1 end
  22. try:
  23. import pystan
  24. except ImportError:
  25. print('You cannot run prophet without pystan installed')
  26. raise
  27. # fb-block 2
  28. class Prophet(object):
  29. def __init__(
  30. self,
  31. growth='linear',
  32. changepoints=None,
  33. n_changepoints=25,
  34. yearly_seasonality=True,
  35. weekly_seasonality=True,
  36. holidays=None,
  37. seasonality_prior_scale=10.0,
  38. holidays_prior_scale=10.0,
  39. changepoint_prior_scale=0.05,
  40. mcmc_samples=0,
  41. interval_width=0.80,
  42. uncertainty_samples=1000,
  43. ):
  44. if growth not in ('linear', 'logistic'):
  45. raise ValueError("growth setting must be 'linear' or 'logistic'")
  46. self.growth = growth
  47. self.changepoints = pd.to_datetime(changepoints)
  48. if self.changepoints is not None:
  49. self.n_changepoints = len(self.changepoints)
  50. else:
  51. self.n_changepoints = n_changepoints
  52. self.yearly_seasonality = yearly_seasonality
  53. self.weekly_seasonality = weekly_seasonality
  54. if holidays is not None:
  55. if not (
  56. isinstance(holidays, pd.DataFrame)
  57. and 'ds' in holidays
  58. and 'holiday' in holidays
  59. ):
  60. raise ValueError("holidays must be a DataFrame with 'ds' and "
  61. "'holiday' columns.")
  62. holidays['ds'] = pd.to_datetime(holidays['ds'])
  63. self.holidays = holidays
  64. self.seasonality_prior_scale = float(seasonality_prior_scale)
  65. self.changepoint_prior_scale = float(changepoint_prior_scale)
  66. self.holidays_prior_scale = float(holidays_prior_scale)
  67. self.mcmc_samples = mcmc_samples
  68. self.interval_width = interval_width
  69. self.uncertainty_samples = uncertainty_samples
  70. # Set during fitting
  71. self.start = None
  72. self.end = None
  73. self.y_scale = None
  74. self.stan_fit = None
  75. self.params = {}
  76. self.history = None
  77. @classmethod
  78. def get_linear_model(cls):
  79. # fb-block 3
  80. # fb-block 4 start
  81. model_file = pkg_resources.resource_filename(
  82. 'fbprophet',
  83. 'stan_models/linear_growth.pkl'
  84. )
  85. # fb-block 4 end
  86. with open(model_file, 'rb') as f:
  87. return pickle.load(f)
  88. @classmethod
  89. def get_logistic_model(cls):
  90. # fb-block 5
  91. # fb-block 6 start
  92. model_file = pkg_resources.resource_filename(
  93. 'fbprophet',
  94. 'stan_models/logistic_growth.pkl'
  95. )
  96. # fb-block 6 end
  97. with open(model_file, 'rb') as f:
  98. return pickle.load(f)
  99. def setup_dataframe(self, df, initialize_scales=False):
  100. """Create auxillary columns 't', 't_ix', 'y_scaled', and 'cap_scaled'.
  101. These columns are used during both fitting and prediction.
  102. """
  103. if 'y' in df:
  104. df['y'] = pd.to_numeric(df['y'])
  105. df['ds'] = pd.to_datetime(df['ds'])
  106. df = df.sort_values('ds')
  107. if initialize_scales:
  108. self.y_scale = df['y'].max()
  109. self.start, self.end = df['ds'].min(), df['ds'].max()
  110. t_scale = self.end - self.start
  111. df['t'] = (df['ds'] - self.start) / t_scale
  112. if 'y' in df:
  113. df['y_scaled'] = df['y'] / self.y_scale
  114. if self.growth == 'logistic':
  115. assert 'cap' in df
  116. df['cap_scaled'] = df['cap'] / self.y_scale
  117. return df
  118. def set_changepoints(self):
  119. """Generate a list of changepoints.
  120. Either:
  121. 1) the changepoints were passed in explicitly
  122. A) they are empty
  123. B) not empty, needs validation
  124. 2) we are generating a grid of them
  125. 3) the user prefers no changepoints to be used
  126. """
  127. if self.changepoints is not None:
  128. if len(self.changepoints) == 0:
  129. pass
  130. else:
  131. too_low = min(self.changepoints) < self.history['ds'].min()
  132. too_high = max(self.changepoints) > self.history['ds'].max()
  133. if too_low or too_high:
  134. raise ValueError('Changepoints must fall within training data.')
  135. elif self.n_changepoints > 0:
  136. # Place potential changepoints evenly throuh first 80% of history
  137. max_ix = np.floor(self.history.shape[0] * 0.8)
  138. cp_indexes = (
  139. np.linspace(0, max_ix, self.n_changepoints + 1)
  140. .round()
  141. .astype(np.int)
  142. )
  143. self.changepoints = self.history.ix[cp_indexes]['ds'].tail(-1)
  144. else:
  145. # set empty changepoints
  146. self.changepoints = []
  147. def get_changepoint_indexes(self):
  148. if len(self.changepoints) == 0:
  149. return np.array([0]) # a dummy changepoint
  150. else:
  151. row_index = pd.DatetimeIndex(self.history['ds'])
  152. indexes = []
  153. for cp in self.changepoints:
  154. # In the future this may raise a KeyError, but for now we
  155. # should guarantee that all changepoint dates are included in
  156. # the historical data.
  157. indexes.append(row_index.get_loc(cp))
  158. return np.array(indexes).astype(np.int)
  159. def get_changepoint_times(self):
  160. cpi = self.get_changepoint_indexes()
  161. return np.array(self.history['t'].iloc[cpi])
  162. def get_changepoint_matrix(self):
  163. changepoint_indexes = self.get_changepoint_indexes()
  164. A = np.zeros((self.history.shape[0], len(changepoint_indexes)))
  165. for i, index in enumerate(changepoint_indexes):
  166. A[index:self.history.shape[0], i] = 1
  167. return A
  168. @staticmethod
  169. def fourier_series(dates, period, series_order):
  170. """Generate a Fourier expansion for a fixed frequency and order.
  171. Parameters
  172. ----------
  173. dates: a pd.Series containing timestamps
  174. period: an integer frequency (number of days)
  175. series_order: number of components to generate
  176. Returns
  177. -------
  178. a 2-dimensional np.array with one row per row in `dt`
  179. """
  180. # convert to days since epoch
  181. t = np.array(
  182. (dates - pd.datetime(1970, 1, 1))
  183. .apply(lambda x: x.days)
  184. .astype(np.float)
  185. )
  186. return np.column_stack([
  187. fun((2.0 * (i + 1) * np.pi * t / period))
  188. for i in range(series_order)
  189. for fun in (np.sin, np.cos)
  190. ])
  191. @classmethod
  192. def make_seasonality_features(cls, dates, period, series_order, prefix):
  193. features = cls.fourier_series(dates, period, series_order)
  194. columns = [
  195. '{}_{}'.format(prefix, i + 1)
  196. for i in range(features.shape[1])
  197. ]
  198. return pd.DataFrame(features, columns=columns)
  199. def make_holiday_features(self, dates):
  200. """Generate a DataFrame with each column corresponding to a holiday.
  201. """
  202. # A smaller prior scale will shrink holiday estimates more
  203. scale_ratio = self.holidays_prior_scale / self.seasonality_prior_scale
  204. # Holds columns of our future matrix.
  205. expanded_holidays = defaultdict(lambda: np.zeros(dates.shape[0]))
  206. # Makes an index so we can perform `get_loc` below.
  207. row_index = pd.DatetimeIndex(dates)
  208. for ix, row in self.holidays.iterrows():
  209. dt = row.ds.date()
  210. try:
  211. lw = int(row.get('lower_window', 0))
  212. uw = int(row.get('upper_window', 0))
  213. except ValueError:
  214. lw = 0
  215. uw = 0
  216. for offset in range(lw, uw + 1):
  217. occurrence = dt + timedelta(days=offset)
  218. try:
  219. loc = row_index.get_loc(occurrence)
  220. except KeyError:
  221. loc = None
  222. key = '{}_{}{}'.format(
  223. row.holiday,
  224. '+' if offset >= 0 else '-',
  225. abs(offset)
  226. )
  227. if loc is not None:
  228. expanded_holidays[key][loc] = scale_ratio
  229. else:
  230. # Access key to generate value
  231. expanded_holidays[key]
  232. # This relies pretty importantly on pandas keeping the columns in order.
  233. return pd.DataFrame(expanded_holidays)
  234. def make_all_seasonality_features(self, df):
  235. seasonal_features = [
  236. # Add a column of zeros in case no seasonality is used.
  237. pd.DataFrame({'zeros': np.zeros(df.shape[0])})
  238. ]
  239. # Seasonality features
  240. if self.yearly_seasonality:
  241. seasonal_features.append(self.make_seasonality_features(
  242. df['ds'],
  243. 365.25,
  244. 10,
  245. 'yearly',
  246. ))
  247. if self.weekly_seasonality:
  248. seasonal_features.append(self.make_seasonality_features(
  249. df['ds'],
  250. 7,
  251. 3,
  252. 'weekly',
  253. ))
  254. if self.holidays is not None:
  255. seasonal_features.append(self.make_holiday_features(df['ds']))
  256. return pd.concat(seasonal_features, axis=1)
  257. @staticmethod
  258. def linear_growth_init(df):
  259. i0, i1 = df['ds'].idxmin(), df['ds'].idxmax()
  260. T = df['t'].ix[i1] - df['t'].ix[i0]
  261. k = (df['y_scaled'].ix[i1] - df['y_scaled'].ix[i0]) / T
  262. m = df['y_scaled'].ix[i0] - k * df['t'].ix[i0]
  263. return (k, m)
  264. @staticmethod
  265. def logistic_growth_init(df):
  266. i0, i1 = df['ds'].idxmin(), df['ds'].idxmax()
  267. T = df['t'].ix[i1] - df['t'].ix[i0]
  268. # Force valid values, in case y > cap.
  269. r0 = max(1.01, df['cap_scaled'].ix[i0] / df['y_scaled'].ix[i0])
  270. r1 = max(1.01, df['cap_scaled'].ix[i1] / df['y_scaled'].ix[i1])
  271. if abs(r0 - r1) <= 0.01:
  272. r0 = 1.05 * r0
  273. L0 = np.log(r0 - 1)
  274. L1 = np.log(r1 - 1)
  275. # Initialize the offset
  276. m = L0 * T / (L0 - L1)
  277. # And the rate
  278. k = L0 / m
  279. return (k, m)
  280. # fb-block 7
  281. def fit(self, df, **kwargs):
  282. """Fit the Prophet model to data.
  283. Parameters
  284. ----------
  285. df: pd.DataFrame containing history. Must have columns 'ds', 'y', and
  286. if logistic growth, 'cap'.
  287. kwargs: Additional arguments passed to Stan's sampling or optimizing
  288. function, as appropriate.
  289. Returns
  290. -------
  291. The fitted Prophet object.
  292. """
  293. history = df[df['y'].notnull()].copy()
  294. history.reset_index(inplace=True, drop=True)
  295. history = self.setup_dataframe(history, initialize_scales=True)
  296. self.history = history
  297. seasonal_features = self.make_all_seasonality_features(history)
  298. self.set_changepoints()
  299. A = self.get_changepoint_matrix()
  300. changepoint_indexes = self.get_changepoint_indexes()
  301. dat = {
  302. 'T': history.shape[0],
  303. 'K': seasonal_features.shape[1],
  304. 'S': len(changepoint_indexes),
  305. 'y': history['y_scaled'],
  306. 't': history['t'],
  307. 'A': A,
  308. # Need to add one because Stan is 1-indexed.
  309. 's_indx': changepoint_indexes + 1,
  310. 'X': seasonal_features,
  311. 'sigma': self.seasonality_prior_scale,
  312. 'tau': self.changepoint_prior_scale,
  313. }
  314. if self.growth == 'linear':
  315. kinit = self.linear_growth_init(history)
  316. model = self.get_linear_model()
  317. else:
  318. dat['cap'] = history['cap_scaled']
  319. kinit = self.logistic_growth_init(history)
  320. model = self.get_logistic_model()
  321. def stan_init():
  322. return {
  323. 'k': kinit[0],
  324. 'm': kinit[1],
  325. 'delta': np.zeros(len(changepoint_indexes)),
  326. 'beta': np.zeros(seasonal_features.shape[1]),
  327. 'sigma_obs': 1,
  328. }
  329. if self.mcmc_samples > 0:
  330. stan_fit = model.sampling(
  331. dat,
  332. init=stan_init,
  333. iter=self.mcmc_samples,
  334. **kwargs
  335. )
  336. for par in stan_fit.model_pars:
  337. self.params[par] = stan_fit[par]
  338. else:
  339. params = model.optimizing(dat, init=stan_init, iter=1e4, **kwargs)
  340. for par in params:
  341. self.params[par] = params[par].reshape((1, -1))
  342. # If no changepoints were requested, replace delta with 0s
  343. if len(self.changepoints) == 0:
  344. # Fold delta into the base rate k
  345. params['k'] = params['k'] + params['delta']
  346. params['delta'] = np.zeros(params['delta'].shape)
  347. return self
  348. # fb-block 8
  349. def predict(self, df=None):
  350. """Predict historical and future values for y.
  351. Note: you must only pass in future dates here.
  352. Historical dates are prepended before predictions are made.
  353. `df` can be None, in which case we predict only on history.
  354. """
  355. if df is None:
  356. df = self.history
  357. else:
  358. df = self.setup_dataframe(df)
  359. df['trend'] = self.predict_trend(df)
  360. seasonal_components = self.predict_seasonal_components(df)
  361. intervals = self.predict_uncertainty(df)
  362. df2 = pd.concat((df, intervals, seasonal_components), axis=1)
  363. df2['yhat'] = df2['trend'] + df2['seasonal']
  364. return df2
  365. @staticmethod
  366. def piecewise_linear(t, deltas, k, m, changepoint_ts):
  367. # Intercept changes
  368. gammas = -changepoint_ts * deltas
  369. # Get cumulative slope and intercept at each t
  370. k_t = k * np.ones_like(t)
  371. m_t = m * np.ones_like(t)
  372. for s, t_s in enumerate(changepoint_ts):
  373. indx = t >= t_s
  374. k_t[indx] += deltas[s]
  375. m_t[indx] += gammas[s]
  376. return k_t * t + m_t
  377. @staticmethod
  378. def piecewise_logistic(t, cap, deltas, k, m, changepoint_ts):
  379. # Compute offset changes
  380. k_cum = np.concatenate((np.atleast_1d(k), np.cumsum(deltas) + k))
  381. gammas = np.zeros(len(changepoint_ts))
  382. for i, t_s in enumerate(changepoint_ts):
  383. gammas[i] = (
  384. (t_s - m - np.sum(gammas))
  385. * (1 - k_cum[i] / k_cum[i + 1])
  386. )
  387. # Get cumulative rate and offset at each t
  388. k_t = k * np.ones_like(t)
  389. m_t = m * np.ones_like(t)
  390. for s, t_s in enumerate(changepoint_ts):
  391. indx = t >= t_s
  392. k_t[indx] += deltas[s]
  393. m_t[indx] += gammas[s]
  394. return cap / (1 + np.exp(-k_t * (t - m_t)))
  395. def predict_trend(self, df):
  396. k = np.nanmean(self.params['k'])
  397. m = np.nanmean(self.params['m'])
  398. deltas = np.nanmean(self.params['delta'], axis=0)
  399. t = np.array(df['t'])
  400. cpts = self.get_changepoint_times()
  401. if self.growth == 'linear':
  402. trend = self.piecewise_linear(t, deltas, k, m, cpts)
  403. else:
  404. cap = df['cap_scaled']
  405. trend = self.piecewise_logistic(t, cap, deltas, k, m, cpts)
  406. return trend * self.y_scale
  407. def predict_seasonal_components(self, df):
  408. seasonal_features = self.make_all_seasonality_features(df)
  409. lower_p = 100 * (1.0 - self.interval_width) / 2
  410. upper_p = 100 * (1.0 + self.interval_width) / 2
  411. components = pd.DataFrame({
  412. 'col': np.arange(seasonal_features.shape[1]),
  413. 'component': [x.split('_')[0] for x in seasonal_features.columns],
  414. })
  415. # Remove the placeholder
  416. components = components[components['component'] != 'zeros']
  417. if components.shape[0] > 0:
  418. X = seasonal_features.as_matrix()
  419. data = {}
  420. for component, features in components.groupby('component'):
  421. cols = features.col.tolist()
  422. comp_beta = self.params['beta'][:, cols]
  423. comp_features = X[:, cols]
  424. comp = (
  425. np.matmul(comp_features, comp_beta.transpose())
  426. * self.y_scale
  427. )
  428. data[component] = np.nanmean(comp, axis=1)
  429. data[component + '_lower'] = np.nanpercentile(comp, lower_p,
  430. axis=1)
  431. data[component + '_upper'] = np.nanpercentile(comp, upper_p,
  432. axis=1)
  433. component_predictions = pd.DataFrame(data)
  434. component_predictions['seasonal'] = (
  435. component_predictions[components['component'].unique()].sum(1))
  436. else:
  437. component_predictions = pd.DataFrame(
  438. {'seasonal': np.zeros(df.shape[0])})
  439. return component_predictions
  440. def predict_uncertainty(self, df):
  441. n_iterations = self.params['k'].shape[0]
  442. samp_per_iter = max(1, int(np.ceil(
  443. self.uncertainty_samples / float(n_iterations)
  444. )))
  445. # Generate seasonality features once so we can re-use them.
  446. seasonal_features = self.make_all_seasonality_features(df)
  447. sim_values = {'yhat': [], 'trend': [], 'seasonal': []}
  448. for i in range(n_iterations):
  449. for j in range(samp_per_iter):
  450. sim = self.sample_model(df, seasonal_features, i)
  451. for key in sim_values:
  452. sim_values[key].append(sim[key])
  453. lower_p = 100 * (1.0 - self.interval_width) / 2
  454. upper_p = 100 * (1.0 + self.interval_width) / 2
  455. series = {}
  456. for key, value in sim_values.items():
  457. mat = np.column_stack(value)
  458. series['{}_lower'.format(key)] = np.nanpercentile(mat, lower_p,
  459. axis=1)
  460. series['{}_upper'.format(key)] = np.nanpercentile(mat, upper_p,
  461. axis=1)
  462. return pd.DataFrame(series)
  463. def sample_model(self, df, seasonal_features, iteration):
  464. trend = self.sample_predictive_trend(df, iteration)
  465. beta = self.params['beta'][iteration]
  466. seasonal = np.matmul(seasonal_features.as_matrix(), beta) * self.y_scale
  467. sigma = self.params['sigma_obs'][iteration]
  468. noise = np.random.normal(0, sigma, df.shape[0]) * self.y_scale
  469. return pd.DataFrame({
  470. 'yhat': trend + seasonal + noise,
  471. 'trend': trend,
  472. 'seasonal': seasonal,
  473. })
  474. def sample_predictive_trend(self, df, iteration):
  475. k = self.params['k'][iteration]
  476. m = self.params['m'][iteration]
  477. deltas = self.params['delta'][iteration]
  478. t = np.array(df['t'])
  479. changepoint_ts = self.get_changepoint_times()
  480. T = t.max()
  481. if T > 1:
  482. # Get the time discretization of the history
  483. dt = np.diff(self.history['t'])
  484. dt = np.min(dt[dt > 0])
  485. # Number of time periods in the future
  486. N = np.ceil((T - 1) / float(dt))
  487. S = len(changepoint_ts)
  488. prob_change = min(1, (S * (T - 1)) / N)
  489. n_changes = np.random.binomial(N, prob_change)
  490. # Sample ts
  491. changepoint_ts_new = sorted(np.random.uniform(1, T, n_changes))
  492. else:
  493. # Case where we're not extrapolating.
  494. changepoint_ts_new = []
  495. n_changes = 0
  496. # Get the empirical scale of the deltas, plus epsilon to avoid NaNs.
  497. lambda_ = np.mean(np.abs(deltas)) + 1e-8
  498. # Sample deltas
  499. deltas_new = np.random.laplace(0, lambda_, n_changes)
  500. # Prepend the times and deltas from the history
  501. changepoint_ts = np.concatenate((changepoint_ts, changepoint_ts_new))
  502. deltas = np.concatenate((deltas, deltas_new))
  503. if self.growth == 'linear':
  504. trend = self.piecewise_linear(t, deltas, k, m, changepoint_ts)
  505. else:
  506. cap = df['cap_scaled']
  507. trend = self.piecewise_logistic(t, cap, deltas, k, m,
  508. changepoint_ts)
  509. return trend * self.y_scale
  510. def make_future_dataframe(self, periods, freq='D', include_history=True):
  511. last_date = self.history['ds'].max()
  512. dates = pd.date_range(
  513. start=last_date,
  514. periods=periods + 1, # closed='right' removes a period
  515. freq=freq,
  516. closed='right') # omits the start date
  517. if include_history:
  518. dates = np.concatenate((np.array(self.history['ds']), dates))
  519. return pd.DataFrame({'ds': dates})
  520. def plot(self, fcst, uncertainty=True, xlabel='ds', ylabel='y'):
  521. """Plot the Prophet forecast.
  522. Parameters
  523. ----------
  524. fcst: pd.DataFrame output of self.predict.
  525. uncertainty: Optional boolean to plot uncertainty intervals.
  526. xlabel: Optional label name on X-axis
  527. ylabel: Optional label name on Y-axis
  528. Returns
  529. -------
  530. a matplotlib figure.
  531. """
  532. forecast_color = '#0072B2'
  533. fig = plt.figure(facecolor='w', figsize=(10, 6))
  534. ax = fig.add_subplot(111)
  535. ax.plot(self.history['ds'].values, self.history['y'], 'k.')
  536. ax.plot(fcst['ds'].values, fcst['yhat'], ls='-', c=forecast_color)
  537. if 'cap' in fcst:
  538. ax.plot(fcst['ds'].values, fcst['cap'], ls='--', c='k')
  539. if uncertainty:
  540. ax.fill_between(fcst['ds'].values, fcst['yhat_lower'],
  541. fcst['yhat_upper'], color=forecast_color, alpha=0.2)
  542. ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
  543. ax.set_xlabel(xlabel)
  544. ax.set_ylabel(ylabel)
  545. fig.tight_layout()
  546. return fig
  547. def plot_components(self, fcst, uncertainty=True):
  548. """Plot the Prophet forecast components.
  549. Will plot whichever are available of: trend, holidays, weekly
  550. seasonality, and yearly seasonality.
  551. Parameters
  552. ----------
  553. fcst: pd.DataFrame output of self.predict.
  554. uncertainty: Optional boolean to plot uncertainty intervals.
  555. Returns
  556. -------
  557. a matplotlib figure.
  558. """
  559. # Identify components to be plotted
  560. plot_trend = True
  561. plot_holidays = self.holidays is not None
  562. plot_weekly = 'weekly' in fcst
  563. plot_yearly = 'yearly' in fcst
  564. npanel = plot_trend + plot_holidays + plot_weekly + plot_yearly
  565. forecast_color = '#0072B2'
  566. fig = plt.figure(facecolor='w', figsize=(9, 3 * npanel))
  567. panel_num = 1
  568. ax = fig.add_subplot(npanel, 1, panel_num)
  569. ax.plot(fcst['ds'].values, fcst['trend'], ls='-', c=forecast_color)
  570. if 'cap' in fcst:
  571. ax.plot(fcst['ds'].values, fcst['cap'], ls='--', c='k')
  572. if uncertainty:
  573. ax.fill_between(
  574. fcst['ds'].values, fcst['trend_lower'], fcst['trend_upper'],
  575. color=forecast_color, alpha=0.2)
  576. ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
  577. ax.xaxis.set_major_locator(MaxNLocator(nbins=7))
  578. ax.set_xlabel('ds')
  579. ax.set_ylabel('trend')
  580. if plot_holidays:
  581. panel_num += 1
  582. ax = fig.add_subplot(npanel, 1, panel_num)
  583. holiday_comps = self.holidays['holiday'].unique()
  584. y_holiday = fcst[holiday_comps].sum(1)
  585. y_holiday_l = fcst[[h + '_lower' for h in holiday_comps]].sum(1)
  586. y_holiday_u = fcst[[h + '_upper' for h in holiday_comps]].sum(1)
  587. # NOTE the above CI calculation is incorrect if holidays overlap
  588. # in time. Since it is just for the visualization we will not
  589. # worry about it now.
  590. ax.plot(fcst['ds'].values, y_holiday, ls='-', c=forecast_color)
  591. if uncertainty:
  592. ax.fill_between(fcst['ds'].values, y_holiday_l, y_holiday_u,
  593. color=forecast_color, alpha=0.2)
  594. ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
  595. ax.xaxis.set_major_locator(MaxNLocator(nbins=7))
  596. ax.set_xlabel('ds')
  597. ax.set_ylabel('holidays')
  598. if plot_weekly:
  599. panel_num += 1
  600. ax = fig.add_subplot(npanel, 1, panel_num)
  601. df_s = fcst.copy()
  602. df_s['dow'] = df_s['ds'].dt.weekday_name
  603. df_s = df_s.groupby('dow').first()
  604. days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday',
  605. 'Friday', 'Saturday']
  606. y_weekly = [df_s.loc[d]['weekly'] for d in days]
  607. y_weekly_l = [df_s.loc[d]['weekly_lower'] for d in days]
  608. y_weekly_u = [df_s.loc[d]['weekly_upper'] for d in days]
  609. ax.plot(range(len(days)), y_weekly, ls='-', c=forecast_color)
  610. if uncertainty:
  611. ax.fill_between(range(len(days)), y_weekly_l, y_weekly_u,
  612. color=forecast_color, alpha=0.2)
  613. ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
  614. ax.set_xticklabels(days)
  615. ax.set_xlabel('Day of week')
  616. ax.set_ylabel('weekly')
  617. if plot_yearly:
  618. panel_num += 1
  619. ax = fig.add_subplot(npanel, 1, panel_num)
  620. df_s = fcst.copy()
  621. df_s['doy'] = df_s['ds'].map(lambda x: x.strftime('2000-%m-%d'))
  622. df_s = df_s.groupby('doy').first().sort_index()
  623. ax.plot(pd.to_datetime(df_s.index), df_s['yearly'], ls='-',
  624. c=forecast_color)
  625. if uncertainty:
  626. ax.fill_between(
  627. pd.to_datetime(df_s.index), df_s['yearly_lower'],
  628. df_s['yearly_upper'], color=forecast_color, alpha=0.2)
  629. ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
  630. months = MonthLocator(range(1, 13), bymonthday=1, interval=2)
  631. ax.xaxis.set_major_formatter(DateFormatter('%B %-d'))
  632. ax.xaxis.set_major_locator(months)
  633. ax.set_xlabel('Day of year')
  634. ax.set_ylabel('yearly')
  635. fig.tight_layout()
  636. return fig
  637. # fb-block 9