forecaster.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110
  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 logging
  14. logger = logging.getLogger(__name__)
  15. from matplotlib import pyplot as plt
  16. from matplotlib.dates import MonthLocator, num2date
  17. from matplotlib.ticker import FuncFormatter
  18. import numpy as np
  19. import pandas as pd
  20. # fb-block 1 start
  21. from fbprophet.models import prophet_stan_models
  22. # fb-block 1 end
  23. try:
  24. import pystan
  25. except ImportError:
  26. logger.error('You cannot run prophet without pystan installed')
  27. raise
  28. # fb-block 2
  29. class Prophet(object):
  30. """Prophet forecaster.
  31. Parameters
  32. ----------
  33. growth: String 'linear' or 'logistic' to specify a linear or logistic
  34. trend.
  35. changepoints: List of dates at which to include potential changepoints. If
  36. not specified, potential changepoints are selected automatically.
  37. n_changepoints: Number of potential changepoints to include. Not used
  38. if input `changepoints` is supplied. If `changepoints` is not supplied,
  39. then n_changepoints potential changepoints are selected uniformly from
  40. the first 80 percent of the history.
  41. yearly_seasonality: Fit yearly seasonality. Can be 'auto', True, or False.
  42. weekly_seasonality: Fit weekly seasonality. Can be 'auto', True, or False.
  43. holidays: pd.DataFrame with columns holiday (string) and ds (date type)
  44. and optionally columns lower_window and upper_window which specify a
  45. range of days around the date to be included as holidays.
  46. lower_window=-2 will include 2 days prior to the date as holidays.
  47. seasonality_prior_scale: Parameter modulating the strength of the
  48. seasonality model. Larger values allow the model to fit larger seasonal
  49. fluctuations, smaller values dampen the seasonality.
  50. holidays_prior_scale: Parameter modulating the strength of the holiday
  51. components model.
  52. changepoint_prior_scale: Parameter modulating the flexibility of the
  53. automatic changepoint selection. Large values will allow many
  54. changepoints, small values will allow few changepoints.
  55. mcmc_samples: Integer, if greater than 0, will do full Bayesian inference
  56. with the specified number of MCMC samples. If 0, will do MAP
  57. estimation.
  58. interval_width: Float, width of the uncertainty intervals provided
  59. for the forecast. If mcmc_samples=0, this will be only the uncertainty
  60. in the trend using the MAP estimate of the extrapolated generative
  61. model. If mcmc.samples>0, this will be integrated over all model
  62. parameters, which will include uncertainty in seasonality.
  63. uncertainty_samples: Number of simulated draws used to estimate
  64. uncertainty intervals.
  65. """
  66. def __init__(
  67. self,
  68. growth='linear',
  69. changepoints=None,
  70. n_changepoints=25,
  71. yearly_seasonality='auto',
  72. weekly_seasonality='auto',
  73. holidays=None,
  74. seasonality_prior_scale=10.0,
  75. holidays_prior_scale=10.0,
  76. changepoint_prior_scale=0.05,
  77. mcmc_samples=0,
  78. interval_width=0.80,
  79. uncertainty_samples=1000,
  80. ):
  81. self.growth = growth
  82. self.changepoints = pd.to_datetime(changepoints)
  83. if self.changepoints is not None:
  84. self.n_changepoints = len(self.changepoints)
  85. else:
  86. self.n_changepoints = n_changepoints
  87. self.yearly_seasonality = yearly_seasonality
  88. self.weekly_seasonality = weekly_seasonality
  89. if holidays is not None:
  90. if not (
  91. isinstance(holidays, pd.DataFrame)
  92. and 'ds' in holidays
  93. and 'holiday' in holidays
  94. ):
  95. raise ValueError("holidays must be a DataFrame with 'ds' and "
  96. "'holiday' columns.")
  97. holidays['ds'] = pd.to_datetime(holidays['ds'])
  98. self.holidays = holidays
  99. self.seasonality_prior_scale = float(seasonality_prior_scale)
  100. self.changepoint_prior_scale = float(changepoint_prior_scale)
  101. self.holidays_prior_scale = float(holidays_prior_scale)
  102. self.mcmc_samples = mcmc_samples
  103. self.interval_width = interval_width
  104. self.uncertainty_samples = uncertainty_samples
  105. # Set during fitting
  106. self.start = None
  107. self.y_scale = None
  108. self.t_scale = None
  109. self.changepoints_t = None
  110. self.stan_fit = None
  111. self.params = {}
  112. self.history = None
  113. self.history_dates = None
  114. self.validate_inputs()
  115. def validate_inputs(self):
  116. """Validates the inputs to Prophet."""
  117. if self.growth not in ('linear', 'logistic'):
  118. raise ValueError(
  119. "Parameter 'growth' should be 'linear' or 'logistic'.")
  120. if self.holidays is not None:
  121. has_lower = 'lower_window' in self.holidays
  122. has_upper = 'upper_window' in self.holidays
  123. if has_lower + has_upper == 1:
  124. raise ValueError('Holidays must have both lower_window and ' +
  125. 'upper_window, or neither')
  126. if has_lower:
  127. if max(self.holidays['lower_window']) > 0:
  128. raise ValueError('Holiday lower_window should be <= 0')
  129. if min(self.holidays['upper_window']) < 0:
  130. raise ValueError('Holiday upper_window should be >= 0')
  131. for h in self.holidays['holiday'].unique():
  132. if '_delim_' in h:
  133. raise ValueError('Holiday name cannot contain "_delim_"')
  134. if h in ['zeros', 'yearly', 'weekly', 'yhat', 'seasonal',
  135. 'trend']:
  136. raise ValueError('Holiday name {} reserved.'.format(h))
  137. def setup_dataframe(self, df, initialize_scales=False):
  138. """Prepare dataframe for fitting or predicting.
  139. Adds a time index and scales y. Creates auxillary columns 't', 't_ix',
  140. 'y_scaled', and 'cap_scaled'. These columns are used during both
  141. fitting and predicting.
  142. Parameters
  143. ----------
  144. df: pd.DataFrame with columns ds, y, and cap if logistic growth.
  145. initialize_scales: Boolean set scaling factors in self from df.
  146. Returns
  147. -------
  148. pd.DataFrame prepared for fitting or predicting.
  149. """
  150. if 'y' in df:
  151. df['y'] = pd.to_numeric(df['y'])
  152. df['ds'] = pd.to_datetime(df['ds'])
  153. df = df.sort_values('ds')
  154. df.reset_index(inplace=True, drop=True)
  155. if initialize_scales:
  156. self.y_scale = df['y'].abs().max()
  157. self.start = df['ds'].min()
  158. self.t_scale = df['ds'].max() - self.start
  159. df['t'] = (df['ds'] - self.start) / self.t_scale
  160. if 'y' in df:
  161. df['y_scaled'] = df['y'] / self.y_scale
  162. if self.growth == 'logistic':
  163. assert 'cap' in df
  164. df['cap_scaled'] = df['cap'] / self.y_scale
  165. return df
  166. def set_changepoints(self):
  167. """Set changepoints
  168. Sets m$changepoints to the dates of changepoints. Either:
  169. 1) The changepoints were passed in explicitly.
  170. A) They are empty.
  171. B) They are not empty, and need validation.
  172. 2) We are generating a grid of them.
  173. 3) The user prefers no changepoints be used.
  174. """
  175. if self.changepoints is not None:
  176. if len(self.changepoints) == 0:
  177. pass
  178. else:
  179. too_low = min(self.changepoints) < self.history['ds'].min()
  180. too_high = max(self.changepoints) > self.history['ds'].max()
  181. if too_low or too_high:
  182. raise ValueError('Changepoints must fall within training data.')
  183. elif self.n_changepoints > 0:
  184. # Place potential changepoints evenly throuh first 80% of history
  185. max_ix = np.floor(self.history.shape[0] * 0.8)
  186. cp_indexes = (
  187. np.linspace(0, max_ix, self.n_changepoints + 1)
  188. .round()
  189. .astype(np.int)
  190. )
  191. self.changepoints = self.history.ix[cp_indexes]['ds'].tail(-1)
  192. else:
  193. # set empty changepoints
  194. self.changepoints = []
  195. if len(self.changepoints) > 0:
  196. self.changepoints_t = np.sort(np.array(
  197. (self.changepoints - self.start) / self.t_scale))
  198. else:
  199. self.changepoints_t = np.array([0]) # dummy changepoint
  200. def get_changepoint_matrix(self):
  201. """Gets changepoint matrix for history dataframe."""
  202. A = np.zeros((self.history.shape[0], len(self.changepoints_t)))
  203. for i, t_i in enumerate(self.changepoints_t):
  204. A[self.history['t'].values >= t_i, i] = 1
  205. return A
  206. @staticmethod
  207. def fourier_series(dates, period, series_order):
  208. """Provides Fourier series components with the specified frequency
  209. and order.
  210. Parameters
  211. ----------
  212. dates: pd.Series containing timestamps.
  213. period: Number of days of the period.
  214. series_order: Number of components.
  215. Returns
  216. -------
  217. Matrix with seasonality features.
  218. """
  219. # convert to days since epoch
  220. t = np.array(
  221. (dates - pd.datetime(1970, 1, 1))
  222. .dt.days
  223. .astype(np.float)
  224. )
  225. return np.column_stack([
  226. fun((2.0 * (i + 1) * np.pi * t / period))
  227. for i in range(series_order)
  228. for fun in (np.sin, np.cos)
  229. ])
  230. @classmethod
  231. def make_seasonality_features(cls, dates, period, series_order, prefix):
  232. """Data frame with seasonality features.
  233. Parameters
  234. ----------
  235. cls: Prophet class.
  236. dates: pd.Series containing timestamps.
  237. period: Number of days of the period.
  238. series_order: Number of components.
  239. prefix: Column name prefix.
  240. Returns
  241. -------
  242. pd.DataFrame with seasonality features.
  243. """
  244. features = cls.fourier_series(dates, period, series_order)
  245. columns = [
  246. '{}_delim_{}'.format(prefix, i + 1)
  247. for i in range(features.shape[1])
  248. ]
  249. return pd.DataFrame(features, columns=columns)
  250. def make_holiday_features(self, dates):
  251. """Construct a dataframe of holiday features.
  252. Parameters
  253. ----------
  254. dates: pd.Series containing timestamps used for computing seasonality.
  255. Returns
  256. -------
  257. pd.DataFrame with a column for each holiday.
  258. """
  259. # A smaller prior scale will shrink holiday estimates more
  260. scale_ratio = self.holidays_prior_scale / self.seasonality_prior_scale
  261. # Holds columns of our future matrix.
  262. expanded_holidays = defaultdict(lambda: np.zeros(dates.shape[0]))
  263. # Makes an index so we can perform `get_loc` below.
  264. row_index = pd.DatetimeIndex(dates)
  265. for _ix, row in self.holidays.iterrows():
  266. dt = row.ds.date()
  267. try:
  268. lw = int(row.get('lower_window', 0))
  269. uw = int(row.get('upper_window', 0))
  270. except ValueError:
  271. lw = 0
  272. uw = 0
  273. for offset in range(lw, uw + 1):
  274. occurrence = dt + timedelta(days=offset)
  275. try:
  276. loc = row_index.get_loc(occurrence)
  277. except KeyError:
  278. loc = None
  279. key = '{}_delim_{}{}'.format(
  280. row.holiday,
  281. '+' if offset >= 0 else '-',
  282. abs(offset)
  283. )
  284. if loc is not None:
  285. expanded_holidays[key][loc] = scale_ratio
  286. else:
  287. # Access key to generate value
  288. expanded_holidays[key]
  289. # This relies pretty importantly on pandas keeping the columns in order.
  290. return pd.DataFrame(expanded_holidays)
  291. def make_all_seasonality_features(self, df):
  292. """Dataframe with seasonality features.
  293. Parameters
  294. ----------
  295. df: pd.DataFrame with dates for computing seasonality features.
  296. Returns
  297. -------
  298. pd.DataFrame with seasonality.
  299. """
  300. seasonal_features = [
  301. # Add a column of zeros in case no seasonality is used.
  302. pd.DataFrame({'zeros': np.zeros(df.shape[0])})
  303. ]
  304. # Seasonality features
  305. if self.yearly_seasonality:
  306. seasonal_features.append(self.make_seasonality_features(
  307. df['ds'],
  308. 365.25,
  309. 10,
  310. 'yearly',
  311. ))
  312. if self.weekly_seasonality:
  313. seasonal_features.append(self.make_seasonality_features(
  314. df['ds'],
  315. 7,
  316. 3,
  317. 'weekly',
  318. ))
  319. if self.holidays is not None:
  320. seasonal_features.append(self.make_holiday_features(df['ds']))
  321. return pd.concat(seasonal_features, axis=1)
  322. def set_auto_seasonalities(self):
  323. """Set seasonalities that were left on auto.
  324. Turns on yearly seasonality if there is >=2 years of history.
  325. Turns on weekly seasonality if there is >=2 weeks of history, and the
  326. spacing between dates in the history is <7 days.
  327. """
  328. first = self.history['ds'].min()
  329. last = self.history['ds'].max()
  330. if self.yearly_seasonality == 'auto':
  331. if last - first < pd.Timedelta(days=730):
  332. self.yearly_seasonality = False
  333. logger.info('Disabling yearly seasonality. Run prophet with '
  334. 'yearly_seasonality=True to override this.')
  335. else:
  336. self.yearly_seasonality = True
  337. if self.weekly_seasonality == 'auto':
  338. dt = self.history['ds'].diff()
  339. min_dt = dt.iloc[dt.nonzero()[0]].min()
  340. if ((last - first < pd.Timedelta(weeks=2)) or
  341. (min_dt >= pd.Timedelta(weeks=1))):
  342. self.weekly_seasonality = False
  343. logger.info('Disabling weekly seasonality. Run prophet with '
  344. 'weekly_seasonality=True to override this.')
  345. else:
  346. self.weekly_seasonality = True
  347. @staticmethod
  348. def linear_growth_init(df):
  349. """Initialize linear growth.
  350. Provides a strong initialization for linear growth by calculating the
  351. growth and offset parameters that pass the function through the first
  352. and last points in the time series.
  353. Parameters
  354. ----------
  355. df: pd.DataFrame with columns ds (date), y_scaled (scaled time series),
  356. and t (scaled time).
  357. Returns
  358. -------
  359. A tuple (k, m) with the rate (k) and offset (m) of the linear growth
  360. function.
  361. """
  362. i0, i1 = df['ds'].idxmin(), df['ds'].idxmax()
  363. T = df['t'].ix[i1] - df['t'].ix[i0]
  364. k = (df['y_scaled'].ix[i1] - df['y_scaled'].ix[i0]) / T
  365. m = df['y_scaled'].ix[i0] - k * df['t'].ix[i0]
  366. return (k, m)
  367. @staticmethod
  368. def logistic_growth_init(df):
  369. """Initialize logistic growth.
  370. Provides a strong initialization for logistic growth by calculating the
  371. growth and offset parameters that pass the function through the first
  372. and last points in the time series.
  373. Parameters
  374. ----------
  375. df: pd.DataFrame with columns ds (date), cap_scaled (scaled capacity),
  376. y_scaled (scaled time series), and t (scaled time).
  377. Returns
  378. -------
  379. A tuple (k, m) with the rate (k) and offset (m) of the logistic growth
  380. function.
  381. """
  382. i0, i1 = df['ds'].idxmin(), df['ds'].idxmax()
  383. T = df['t'].ix[i1] - df['t'].ix[i0]
  384. # Force valid values, in case y > cap.
  385. r0 = max(1.01, df['cap_scaled'].ix[i0] / df['y_scaled'].ix[i0])
  386. r1 = max(1.01, df['cap_scaled'].ix[i1] / df['y_scaled'].ix[i1])
  387. if abs(r0 - r1) <= 0.01:
  388. r0 = 1.05 * r0
  389. L0 = np.log(r0 - 1)
  390. L1 = np.log(r1 - 1)
  391. # Initialize the offset
  392. m = L0 * T / (L0 - L1)
  393. # And the rate
  394. k = L0 / m
  395. return (k, m)
  396. # fb-block 7
  397. def fit(self, df, **kwargs):
  398. """Fit the Prophet model.
  399. This sets self.params to contain the fitted model parameters. It is a
  400. dictionary parameter names as keys and the following items:
  401. k (Mx1 array): M posterior samples of the initial slope.
  402. m (Mx1 array): The initial intercept.
  403. delta (MxN array): The slope change at each of N changepoints.
  404. beta (MxK matrix): Coefficients for K seasonality features.
  405. sigma_obs (Mx1 array): Noise level.
  406. Note that M=1 if MAP estimation.
  407. Parameters
  408. ----------
  409. df: pd.DataFrame containing the history. Must have columns ds (date
  410. type) and y, the time series. If self.growth is 'logistic', then
  411. df must also have a column cap that specifies the capacity at
  412. each ds.
  413. kwargs: Additional arguments passed to the optimizing or sampling
  414. functions in Stan.
  415. Returns
  416. -------
  417. The fitted Prophet object.
  418. """
  419. if self.history is not None:
  420. raise Exception('Prophet object can only be fit once. '
  421. 'Instantiate a new object.')
  422. history = df[df['y'].notnull()].copy()
  423. self.history_dates = pd.to_datetime(df['ds']).sort_values()
  424. history = self.setup_dataframe(history, initialize_scales=True)
  425. self.history = history
  426. self.set_auto_seasonalities()
  427. seasonal_features = self.make_all_seasonality_features(history)
  428. self.set_changepoints()
  429. A = self.get_changepoint_matrix()
  430. dat = {
  431. 'T': history.shape[0],
  432. 'K': seasonal_features.shape[1],
  433. 'S': len(self.changepoints_t),
  434. 'y': history['y_scaled'],
  435. 't': history['t'],
  436. 'A': A,
  437. 't_change': self.changepoints_t,
  438. 'X': seasonal_features,
  439. 'sigma': self.seasonality_prior_scale,
  440. 'tau': self.changepoint_prior_scale,
  441. }
  442. if self.growth == 'linear':
  443. kinit = self.linear_growth_init(history)
  444. else:
  445. dat['cap'] = history['cap_scaled']
  446. kinit = self.logistic_growth_init(history)
  447. model = prophet_stan_models[self.growth]
  448. def stan_init():
  449. return {
  450. 'k': kinit[0],
  451. 'm': kinit[1],
  452. 'delta': np.zeros(len(self.changepoints_t)),
  453. 'beta': np.zeros(seasonal_features.shape[1]),
  454. 'sigma_obs': 1,
  455. }
  456. if self.mcmc_samples > 0:
  457. stan_fit = model.sampling(
  458. dat,
  459. init=stan_init,
  460. iter=self.mcmc_samples,
  461. **kwargs
  462. )
  463. for par in stan_fit.model_pars:
  464. self.params[par] = stan_fit[par]
  465. else:
  466. try:
  467. params = model.optimizing(
  468. dat, init=stan_init, iter=1e4, **kwargs)
  469. except RuntimeError:
  470. params = model.optimizing(
  471. dat, init=stan_init, iter=1e4, algorithm='Newton',
  472. **kwargs
  473. )
  474. for par in params:
  475. self.params[par] = params[par].reshape((1, -1))
  476. # If no changepoints were requested, replace delta with 0s
  477. if len(self.changepoints) == 0:
  478. # Fold delta into the base rate k
  479. self.params['k'] = self.params['k'] + self.params['delta']
  480. self.params['delta'] = np.zeros(self.params['delta'].shape)
  481. return self
  482. # fb-block 8
  483. def predict(self, df=None):
  484. """Predict using the prophet model.
  485. Parameters
  486. ----------
  487. df: pd.DataFrame with dates for predictions (column ds), and capacity
  488. (column cap) if logistic growth. If not provided, predictions are
  489. made on the history.
  490. Returns
  491. -------
  492. A pd.DataFrame with the forecast components.
  493. """
  494. if df is None:
  495. df = self.history.copy()
  496. else:
  497. df = self.setup_dataframe(df)
  498. df['trend'] = self.predict_trend(df)
  499. seasonal_components = self.predict_seasonal_components(df)
  500. intervals = self.predict_uncertainty(df)
  501. df2 = pd.concat((df, intervals, seasonal_components), axis=1)
  502. df2['yhat'] = df2['trend'] + df2['seasonal']
  503. return df2
  504. @staticmethod
  505. def piecewise_linear(t, deltas, k, m, changepoint_ts):
  506. """Evaluate the piecewise linear function.
  507. Parameters
  508. ----------
  509. t: np.array of times on which the function is evaluated.
  510. deltas: np.array of rate changes at each changepoint.
  511. k: Float initial rate.
  512. m: Float initial offset.
  513. changepoint_ts: np.array of changepoint times.
  514. Returns
  515. -------
  516. Vector y(t).
  517. """
  518. # Intercept changes
  519. gammas = -changepoint_ts * deltas
  520. # Get cumulative slope and intercept at each t
  521. k_t = k * np.ones_like(t)
  522. m_t = m * np.ones_like(t)
  523. for s, t_s in enumerate(changepoint_ts):
  524. indx = t >= t_s
  525. k_t[indx] += deltas[s]
  526. m_t[indx] += gammas[s]
  527. return k_t * t + m_t
  528. @staticmethod
  529. def piecewise_logistic(t, cap, deltas, k, m, changepoint_ts):
  530. """Evaluate the piecewise logistic function.
  531. Parameters
  532. ----------
  533. t: np.array of times on which the function is evaluated.
  534. cap: np.array of capacities at each t.
  535. deltas: np.array of rate changes at each changepoint.
  536. k: Float initial rate.
  537. m: Float initial offset.
  538. changepoint_ts: np.array of changepoint times.
  539. Returns
  540. -------
  541. Vector y(t).
  542. """
  543. # Compute offset changes
  544. k_cum = np.concatenate((np.atleast_1d(k), np.cumsum(deltas) + k))
  545. gammas = np.zeros(len(changepoint_ts))
  546. for i, t_s in enumerate(changepoint_ts):
  547. gammas[i] = (
  548. (t_s - m - np.sum(gammas))
  549. * (1 - k_cum[i] / k_cum[i + 1])
  550. )
  551. # Get cumulative rate and offset at each t
  552. k_t = k * np.ones_like(t)
  553. m_t = m * np.ones_like(t)
  554. for s, t_s in enumerate(changepoint_ts):
  555. indx = t >= t_s
  556. k_t[indx] += deltas[s]
  557. m_t[indx] += gammas[s]
  558. return cap / (1 + np.exp(-k_t * (t - m_t)))
  559. def predict_trend(self, df):
  560. """Predict trend using the prophet model.
  561. Parameters
  562. ----------
  563. df: Prediction dataframe.
  564. Returns
  565. -------
  566. Vector with trend on prediction dates.
  567. """
  568. k = np.nanmean(self.params['k'])
  569. m = np.nanmean(self.params['m'])
  570. deltas = np.nanmean(self.params['delta'], axis=0)
  571. t = np.array(df['t'])
  572. if self.growth == 'linear':
  573. trend = self.piecewise_linear(t, deltas, k, m, self.changepoints_t)
  574. else:
  575. cap = df['cap_scaled']
  576. trend = self.piecewise_logistic(
  577. t, cap, deltas, k, m, self.changepoints_t)
  578. return trend * self.y_scale
  579. def predict_seasonal_components(self, df):
  580. """Predict seasonality broken down into components.
  581. Parameters
  582. ----------
  583. df: Prediction dataframe.
  584. Returns
  585. -------
  586. Dataframe with seasonal components.
  587. """
  588. seasonal_features = self.make_all_seasonality_features(df)
  589. lower_p = 100 * (1.0 - self.interval_width) / 2
  590. upper_p = 100 * (1.0 + self.interval_width) / 2
  591. components = pd.DataFrame({
  592. 'col': np.arange(seasonal_features.shape[1]),
  593. 'component': [x.split('_delim_')[0] for x in seasonal_features.columns],
  594. })
  595. # Remove the placeholder
  596. components = components[components['component'] != 'zeros']
  597. if components.shape[0] > 0:
  598. X = seasonal_features.as_matrix()
  599. data = {}
  600. for component, features in components.groupby('component'):
  601. cols = features.col.tolist()
  602. comp_beta = self.params['beta'][:, cols]
  603. comp_features = X[:, cols]
  604. comp = (
  605. np.matmul(comp_features, comp_beta.transpose())
  606. * self.y_scale
  607. )
  608. data[component] = np.nanmean(comp, axis=1)
  609. data[component + '_lower'] = np.nanpercentile(comp, lower_p,
  610. axis=1)
  611. data[component + '_upper'] = np.nanpercentile(comp, upper_p,
  612. axis=1)
  613. component_predictions = pd.DataFrame(data)
  614. component_predictions['seasonal'] = (
  615. component_predictions[components['component'].unique()].sum(1))
  616. else:
  617. component_predictions = pd.DataFrame(
  618. {'seasonal': np.zeros(df.shape[0])})
  619. return component_predictions
  620. def predict_uncertainty(self, df):
  621. """Predict seasonality broken down into components.
  622. Parameters
  623. ----------
  624. df: Prediction dataframe.
  625. Returns
  626. -------
  627. Dataframe with uncertainty intervals.
  628. """
  629. n_iterations = self.params['k'].shape[0]
  630. samp_per_iter = max(1, int(np.ceil(
  631. self.uncertainty_samples / float(n_iterations)
  632. )))
  633. # Generate seasonality features once so we can re-use them.
  634. seasonal_features = self.make_all_seasonality_features(df)
  635. sim_values = {'yhat': [], 'trend': [], 'seasonal': []}
  636. for i in range(n_iterations):
  637. for _j in range(samp_per_iter):
  638. sim = self.sample_model(df, seasonal_features, i)
  639. for key in sim_values:
  640. sim_values[key].append(sim[key])
  641. lower_p = 100 * (1.0 - self.interval_width) / 2
  642. upper_p = 100 * (1.0 + self.interval_width) / 2
  643. series = {}
  644. for key, value in sim_values.items():
  645. mat = np.column_stack(value)
  646. series['{}_lower'.format(key)] = np.nanpercentile(mat, lower_p,
  647. axis=1)
  648. series['{}_upper'.format(key)] = np.nanpercentile(mat, upper_p,
  649. axis=1)
  650. return pd.DataFrame(series)
  651. def sample_model(self, df, seasonal_features, iteration):
  652. """Simulate observations from the extrapolated generative model.
  653. Parameters
  654. ----------
  655. df: Prediction dataframe.
  656. seasonal_features: pd.DataFrame of seasonal features.
  657. iteration: Int sampling iteration to use parameters from.
  658. Returns
  659. -------
  660. Dataframe with trend, seasonality, and yhat, each like df['t'].
  661. """
  662. trend = self.sample_predictive_trend(df, iteration)
  663. beta = self.params['beta'][iteration]
  664. seasonal = np.matmul(seasonal_features.as_matrix(), beta) * self.y_scale
  665. sigma = self.params['sigma_obs'][iteration]
  666. noise = np.random.normal(0, sigma, df.shape[0]) * self.y_scale
  667. return pd.DataFrame({
  668. 'yhat': trend + seasonal + noise,
  669. 'trend': trend,
  670. 'seasonal': seasonal,
  671. })
  672. def sample_predictive_trend(self, df, iteration):
  673. """Simulate the trend using the extrapolated generative model.
  674. Parameters
  675. ----------
  676. df: Prediction dataframe.
  677. seasonal_features: pd.DataFrame of seasonal features.
  678. iteration: Int sampling iteration to use parameters from.
  679. Returns
  680. -------
  681. np.array of simulated trend over df['t'].
  682. """
  683. k = self.params['k'][iteration]
  684. m = self.params['m'][iteration]
  685. deltas = self.params['delta'][iteration]
  686. t = np.array(df['t'])
  687. T = t.max()
  688. if T > 1:
  689. # Get the time discretization of the history
  690. dt = np.diff(self.history['t'])
  691. dt = np.min(dt[dt > 0])
  692. # Number of time periods in the future
  693. N = np.ceil((T - 1) / float(dt))
  694. S = len(self.changepoints_t)
  695. prob_change = min(1, (S * (T - 1)) / N)
  696. n_changes = np.random.binomial(N, prob_change)
  697. # Sample ts
  698. changepoint_ts_new = sorted(np.random.uniform(1, T, n_changes))
  699. else:
  700. # Case where we're not extrapolating.
  701. changepoint_ts_new = []
  702. n_changes = 0
  703. # Get the empirical scale of the deltas, plus epsilon to avoid NaNs.
  704. lambda_ = np.mean(np.abs(deltas)) + 1e-8
  705. # Sample deltas
  706. deltas_new = np.random.laplace(0, lambda_, n_changes)
  707. # Prepend the times and deltas from the history
  708. changepoint_ts = np.concatenate((self.changepoints_t,
  709. changepoint_ts_new))
  710. deltas = np.concatenate((deltas, deltas_new))
  711. if self.growth == 'linear':
  712. trend = self.piecewise_linear(t, deltas, k, m, changepoint_ts)
  713. else:
  714. cap = df['cap_scaled']
  715. trend = self.piecewise_logistic(t, cap, deltas, k, m,
  716. changepoint_ts)
  717. return trend * self.y_scale
  718. def make_future_dataframe(self, periods, freq='D', include_history=True):
  719. """Simulate the trend using the extrapolated generative model.
  720. Parameters
  721. ----------
  722. periods: Int number of periods to forecast forward.
  723. freq: Any valid frequency for pd.date_range, such as 'D' or 'M'.
  724. include_history: Boolean to include the historical dates in the data
  725. frame for predictions.
  726. Returns
  727. -------
  728. pd.Dataframe that extends forward from the end of self.history for the
  729. requested number of periods.
  730. """
  731. last_date = self.history_dates.max()
  732. dates = pd.date_range(
  733. start=last_date,
  734. periods=periods + 1, # An extra in case we include start
  735. freq=freq)
  736. dates = dates[dates > last_date] # Drop start if equals last_date
  737. dates = dates[:periods] # Return correct number of periods
  738. if include_history:
  739. dates = np.concatenate((np.array(self.history_dates), dates))
  740. return pd.DataFrame({'ds': dates})
  741. def plot(self, fcst, ax=None, uncertainty=True, plot_cap=True, xlabel='ds',
  742. ylabel='y'):
  743. """Plot the Prophet forecast.
  744. Parameters
  745. ----------
  746. fcst: pd.DataFrame output of self.predict.
  747. ax: Optional matplotlib axes on which to plot.
  748. uncertainty: Optional boolean to plot uncertainty intervals.
  749. plot_cap: Optional boolean indicating if the capacity should be shown
  750. in the figure, if available.
  751. xlabel: Optional label name on X-axis
  752. ylabel: Optional label name on Y-axis
  753. Returns
  754. -------
  755. A matplotlib figure.
  756. """
  757. if ax is None:
  758. fig = plt.figure(facecolor='w', figsize=(10, 6))
  759. ax = fig.add_subplot(111)
  760. else:
  761. fig = ax.get_figure()
  762. ax.plot(self.history['ds'].values, self.history['y'], 'k.')
  763. ax.plot(fcst['ds'].values, fcst['yhat'], ls='-', c='#0072B2')
  764. if 'cap' in fcst and plot_cap:
  765. ax.plot(fcst['ds'].values, fcst['cap'], ls='--', c='k')
  766. if uncertainty:
  767. ax.fill_between(fcst['ds'].values, fcst['yhat_lower'],
  768. fcst['yhat_upper'], color='#0072B2',
  769. alpha=0.2)
  770. ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
  771. ax.set_xlabel(xlabel)
  772. ax.set_ylabel(ylabel)
  773. fig.tight_layout()
  774. return fig
  775. def plot_components(self, fcst, uncertainty=True, plot_cap=True,
  776. weekly_start=0, yearly_start=0):
  777. """Plot the Prophet forecast components.
  778. Will plot whichever are available of: trend, holidays, weekly
  779. seasonality, and yearly seasonality.
  780. Parameters
  781. ----------
  782. fcst: pd.DataFrame output of self.predict.
  783. uncertainty: Optional boolean to plot uncertainty intervals.
  784. plot_cap: Optional boolean indicating if the capacity should be shown
  785. in the figure, if available.
  786. weekly_start: Optional int specifying the start day of the weekly
  787. seasonality plot. 0 (default) starts the week on Sunday. 1 shifts
  788. by 1 day to Monday, and so on.
  789. yearly_start: Optional int specifying the start day of the yearly
  790. seasonality plot. 0 (default) starts the year on Jan 1. 1 shifts
  791. by 1 day to Jan 2, and so on.
  792. Returns
  793. -------
  794. A matplotlib figure.
  795. """
  796. # Identify components to be plotted
  797. components = [('trend', True),
  798. ('holidays', self.holidays is not None),
  799. ('weekly', 'weekly' in fcst),
  800. ('yearly', 'yearly' in fcst)]
  801. components = [plot for plot, cond in components if cond]
  802. npanel = len(components)
  803. fig, axes = plt.subplots(npanel, 1, facecolor='w',
  804. figsize=(9, 3 * npanel))
  805. for ax, plot in zip(axes, components):
  806. if plot == 'trend':
  807. self.plot_trend(
  808. fcst, ax=ax, uncertainty=uncertainty, plot_cap=plot_cap)
  809. elif plot == 'holidays':
  810. self.plot_holidays(fcst, ax=ax, uncertainty=uncertainty)
  811. elif plot == 'weekly':
  812. self.plot_weekly(
  813. ax=ax, uncertainty=uncertainty, weekly_start=weekly_start)
  814. elif plot == 'yearly':
  815. self.plot_yearly(
  816. ax=ax, uncertainty=uncertainty, yearly_start=yearly_start)
  817. fig.tight_layout()
  818. return fig
  819. def plot_trend(self, fcst, ax=None, uncertainty=True, plot_cap=True):
  820. """Plot the trend component of the forecast.
  821. Parameters
  822. ----------
  823. fcst: pd.DataFrame output of self.predict.
  824. ax: Optional matplotlib Axes to plot on.
  825. uncertainty: Optional boolean to plot uncertainty intervals.
  826. plot_cap: Optional boolean indicating if the capacity should be shown
  827. in the figure, if available.
  828. Returns
  829. -------
  830. a list of matplotlib artists
  831. """
  832. artists = []
  833. if not ax:
  834. fig = plt.figure(facecolor='w', figsize=(10, 6))
  835. ax = fig.add_subplot(111)
  836. artists += ax.plot(fcst['ds'].values, fcst['trend'], ls='-',
  837. c='#0072B2')
  838. if 'cap' in fcst and plot_cap:
  839. artists += ax.plot(fcst['ds'].values, fcst['cap'], ls='--', c='k')
  840. if uncertainty:
  841. artists += [ax.fill_between(
  842. fcst['ds'].values, fcst['trend_lower'], fcst['trend_upper'],
  843. color='#0072B2', alpha=0.2)]
  844. ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
  845. ax.set_xlabel('ds')
  846. ax.set_ylabel('trend')
  847. return artists
  848. def plot_holidays(self, fcst, ax=None, uncertainty=True):
  849. """Plot the holidays component of the forecast.
  850. Parameters
  851. ----------
  852. fcst: pd.DataFrame output of self.predict.
  853. ax: Optional matplotlib Axes to plot on. One will be created if this
  854. is not provided.
  855. uncertainty: Optional boolean to plot uncertainty intervals.
  856. Returns
  857. -------
  858. a list of matplotlib artists
  859. """
  860. artists = []
  861. if not ax:
  862. fig = plt.figure(facecolor='w', figsize=(10, 6))
  863. ax = fig.add_subplot(111)
  864. holiday_comps = self.holidays['holiday'].unique()
  865. y_holiday = fcst[holiday_comps].sum(1)
  866. y_holiday_l = fcst[[h + '_lower' for h in holiday_comps]].sum(1)
  867. y_holiday_u = fcst[[h + '_upper' for h in holiday_comps]].sum(1)
  868. # NOTE the above CI calculation is incorrect if holidays overlap
  869. # in time. Since it is just for the visualization we will not
  870. # worry about it now.
  871. artists += ax.plot(fcst['ds'].values, y_holiday, ls='-',
  872. c='#0072B2')
  873. if uncertainty:
  874. artists += [ax.fill_between(fcst['ds'].values,
  875. y_holiday_l, y_holiday_u,
  876. color='#0072B2', alpha=0.2)]
  877. ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
  878. ax.set_xlabel('ds')
  879. ax.set_ylabel('holidays')
  880. return artists
  881. def plot_weekly(self, ax=None, uncertainty=True, weekly_start=0):
  882. """Plot the weekly component of the forecast.
  883. Parameters
  884. ----------
  885. ax: Optional matplotlib Axes to plot on. One will be created if this
  886. is not provided.
  887. uncertainty: Optional boolean to plot uncertainty intervals.
  888. weekly_start: Optional int specifying the start day of the weekly
  889. seasonality plot. 0 (default) starts the week on Sunday. 1 shifts
  890. by 1 day to Monday, and so on.
  891. Returns
  892. -------
  893. a list of matplotlib artists
  894. """
  895. artists = []
  896. if not ax:
  897. fig = plt.figure(facecolor='w', figsize=(10, 6))
  898. ax = fig.add_subplot(111)
  899. # Compute weekly seasonality for a Sun-Sat sequence of dates.
  900. days = (pd.date_range(start='2017-01-01', periods=7) +
  901. pd.Timedelta(days=weekly_start))
  902. df_w = pd.DataFrame({'ds': days, 'cap': 1.})
  903. df_w = self.setup_dataframe(df_w)
  904. seas = self.predict_seasonal_components(df_w)
  905. days = days.weekday_name
  906. artists += ax.plot(range(len(days)), seas['weekly'], ls='-',
  907. c='#0072B2')
  908. if uncertainty:
  909. artists += [ax.fill_between(range(len(days)),
  910. seas['weekly_lower'], seas['weekly_upper'],
  911. color='#0072B2', alpha=0.2)]
  912. ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
  913. ax.set_xticks(range(len(days)))
  914. ax.set_xticklabels(days)
  915. ax.set_xlabel('Day of week')
  916. ax.set_ylabel('weekly')
  917. return artists
  918. def plot_yearly(self, ax=None, uncertainty=True, yearly_start=0):
  919. """Plot the yearly component of the forecast.
  920. Parameters
  921. ----------
  922. ax: Optional matplotlib Axes to plot on. One will be created if
  923. this is not provided.
  924. uncertainty: Optional boolean to plot uncertainty intervals.
  925. yearly_start: Optional int specifying the start day of the yearly
  926. seasonality plot. 0 (default) starts the year on Jan 1. 1 shifts
  927. by 1 day to Jan 2, and so on.
  928. Returns
  929. -------
  930. a list of matplotlib artists
  931. """
  932. artists = []
  933. if not ax:
  934. fig = plt.figure(facecolor='w', figsize=(10, 6))
  935. ax = fig.add_subplot(111)
  936. # Compute yearly seasonality for a Jan 1 - Dec 31 sequence of dates.
  937. df_y = pd.DataFrame(
  938. {'ds': pd.date_range(start='2017-01-01', periods=365) +
  939. pd.Timedelta(days=yearly_start), 'cap': 1.})
  940. df_y = self.setup_dataframe(df_y)
  941. seas = self.predict_seasonal_components(df_y)
  942. artists += ax.plot(df_y['ds'], seas['yearly'], ls='-',
  943. c='#0072B2')
  944. if uncertainty:
  945. artists += [ax.fill_between(
  946. df_y['ds'].values, seas['yearly_lower'],
  947. seas['yearly_upper'], color='#0072B2', alpha=0.2)]
  948. ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
  949. months = MonthLocator(range(1, 13), bymonthday=1, interval=2)
  950. ax.xaxis.set_major_formatter(FuncFormatter(
  951. lambda x, pos=None: '{dt:%B} {dt.day}'.format(dt=num2date(x))))
  952. ax.xaxis.set_major_locator(months)
  953. ax.set_xlabel('Day of year')
  954. ax.set_ylabel('yearly')
  955. return artists