forecaster.py 43 KB

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