forecaster.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158
  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. row_index = pd.DatetimeIndex(dates)
  274. for _ix, row in self.holidays.iterrows():
  275. dt = row.ds.date()
  276. try:
  277. lw = int(row.get('lower_window', 0))
  278. uw = int(row.get('upper_window', 0))
  279. except ValueError:
  280. lw = 0
  281. uw = 0
  282. for offset in range(lw, uw + 1):
  283. occurrence = dt + timedelta(days=offset)
  284. try:
  285. loc = row_index.get_loc(occurrence)
  286. except KeyError:
  287. loc = None
  288. key = '{}_delim_{}{}'.format(
  289. row.holiday,
  290. '+' if offset >= 0 else '-',
  291. abs(offset)
  292. )
  293. if loc is not None:
  294. expanded_holidays[key][loc] = scale_ratio
  295. else:
  296. # Access key to generate value
  297. expanded_holidays[key]
  298. # This relies pretty importantly on pandas keeping the columns in order.
  299. return pd.DataFrame(expanded_holidays)
  300. def make_all_seasonality_features(self, df):
  301. """Dataframe with seasonality features.
  302. Parameters
  303. ----------
  304. df: pd.DataFrame with dates for computing seasonality features.
  305. Returns
  306. -------
  307. pd.DataFrame with seasonality.
  308. """
  309. seasonal_features = [
  310. # Add a column of zeros in case no seasonality is used.
  311. pd.DataFrame({'zeros': np.zeros(df.shape[0])})
  312. ]
  313. for name, (period, series_order) in self.seasonalities.items():
  314. seasonal_features.append(self.make_seasonality_features(
  315. df['ds'],
  316. period,
  317. series_order,
  318. name,
  319. ))
  320. if self.holidays is not None:
  321. seasonal_features.append(self.make_holiday_features(df['ds']))
  322. return pd.concat(seasonal_features, axis=1)
  323. def parse_seasonality_args(self, name, arg, auto_disable, default_order):
  324. """Get number of fourier components for built-in seasonalities.
  325. Parameters
  326. ----------
  327. name: string name of the seasonality component.
  328. arg: 'auto', True, False, or number of fourier components as provided.
  329. auto_disable: bool if seasonality should be disabled when 'auto'.
  330. default_order: int default fourier order
  331. Returns
  332. -------
  333. Number of fourier components, or 0 for disabled.
  334. """
  335. if arg == 'auto':
  336. fourier_order = 0
  337. if name in self.seasonalities:
  338. logger.info(
  339. 'Found custom seasonality named "{name}", '
  340. 'disabling built-in {name} seasonality.'.format(name=name)
  341. )
  342. elif auto_disable:
  343. logger.info(
  344. 'Disabling {name} seasonality. Run prophet with '
  345. '{name}_seasonality=True to override this.'.format(
  346. name=name)
  347. )
  348. else:
  349. fourier_order = default_order
  350. elif arg is True:
  351. fourier_order = default_order
  352. elif arg is False:
  353. fourier_order = 0
  354. else:
  355. fourier_order = int(arg)
  356. return fourier_order
  357. def set_auto_seasonalities(self):
  358. """Set seasonalities that were left on auto.
  359. Turns on yearly seasonality if there is >=2 years of history.
  360. Turns on weekly seasonality if there is >=2 weeks of history, and the
  361. spacing between dates in the history is <7 days.
  362. Turns on daily seasonality if there is >=2 days of history, and the
  363. spacing between dates in the history is <1 day.
  364. """
  365. first = self.history['ds'].min()
  366. last = self.history['ds'].max()
  367. dt = self.history['ds'].diff()
  368. min_dt = dt.iloc[dt.nonzero()[0]].min()
  369. # Yearly seasonality
  370. yearly_disable = last - first < pd.Timedelta(days=730)
  371. fourier_order = self.parse_seasonality_args(
  372. 'yearly', self.yearly_seasonality, yearly_disable, 10)
  373. if fourier_order > 0:
  374. self.seasonalities['yearly'] = (365.25, fourier_order)
  375. # Weekly seasonality
  376. weekly_disable = ((last - first < pd.Timedelta(weeks=2)) or
  377. (min_dt >= pd.Timedelta(weeks=1)))
  378. fourier_order = self.parse_seasonality_args(
  379. 'weekly', self.weekly_seasonality, weekly_disable, 3)
  380. if fourier_order > 0:
  381. self.seasonalities['weekly'] = (7, fourier_order)
  382. # Daily seasonality
  383. daily_disable = ((last - first < pd.Timedelta(days=2)) or
  384. (min_dt >= pd.Timedelta(days=1)))
  385. fourier_order = self.parse_seasonality_args(
  386. 'daily', self.daily_seasonality, daily_disable, 4)
  387. if fourier_order > 0:
  388. self.seasonalities['daily'] = (1, fourier_order)
  389. @staticmethod
  390. def linear_growth_init(df):
  391. """Initialize linear growth.
  392. Provides a strong initialization for linear growth by calculating the
  393. growth and offset parameters that pass the function through the first
  394. and last points in the time series.
  395. Parameters
  396. ----------
  397. df: pd.DataFrame with columns ds (date), y_scaled (scaled time series),
  398. and t (scaled time).
  399. Returns
  400. -------
  401. A tuple (k, m) with the rate (k) and offset (m) of the linear growth
  402. function.
  403. """
  404. i0, i1 = df['ds'].idxmin(), df['ds'].idxmax()
  405. T = df['t'].ix[i1] - df['t'].ix[i0]
  406. k = (df['y_scaled'].ix[i1] - df['y_scaled'].ix[i0]) / T
  407. m = df['y_scaled'].ix[i0] - k * df['t'].ix[i0]
  408. return (k, m)
  409. @staticmethod
  410. def logistic_growth_init(df):
  411. """Initialize logistic growth.
  412. Provides a strong initialization for logistic growth by calculating the
  413. growth and offset parameters that pass the function through the first
  414. and last points in the time series.
  415. Parameters
  416. ----------
  417. df: pd.DataFrame with columns ds (date), cap_scaled (scaled capacity),
  418. y_scaled (scaled time series), and t (scaled time).
  419. Returns
  420. -------
  421. A tuple (k, m) with the rate (k) and offset (m) of the logistic growth
  422. function.
  423. """
  424. i0, i1 = df['ds'].idxmin(), df['ds'].idxmax()
  425. T = df['t'].ix[i1] - df['t'].ix[i0]
  426. # Force valid values, in case y > cap.
  427. r0 = max(1.01, df['cap_scaled'].ix[i0] / df['y_scaled'].ix[i0])
  428. r1 = max(1.01, df['cap_scaled'].ix[i1] / df['y_scaled'].ix[i1])
  429. if abs(r0 - r1) <= 0.01:
  430. r0 = 1.05 * r0
  431. L0 = np.log(r0 - 1)
  432. L1 = np.log(r1 - 1)
  433. # Initialize the offset
  434. m = L0 * T / (L0 - L1)
  435. # And the rate
  436. k = L0 / m
  437. return (k, m)
  438. # fb-block 7
  439. def fit(self, df, **kwargs):
  440. """Fit the Prophet model.
  441. This sets self.params to contain the fitted model parameters. It is a
  442. dictionary parameter names as keys and the following items:
  443. k (Mx1 array): M posterior samples of the initial slope.
  444. m (Mx1 array): The initial intercept.
  445. delta (MxN array): The slope change at each of N changepoints.
  446. beta (MxK matrix): Coefficients for K seasonality features.
  447. sigma_obs (Mx1 array): Noise level.
  448. Note that M=1 if MAP estimation.
  449. Parameters
  450. ----------
  451. df: pd.DataFrame containing the history. Must have columns ds (date
  452. type) and y, the time series. If self.growth is 'logistic', then
  453. df must also have a column cap that specifies the capacity at
  454. each ds.
  455. kwargs: Additional arguments passed to the optimizing or sampling
  456. functions in Stan.
  457. Returns
  458. -------
  459. The fitted Prophet object.
  460. """
  461. if self.history is not None:
  462. raise Exception('Prophet object can only be fit once. '
  463. 'Instantiate a new object.')
  464. history = df[df['y'].notnull()].copy()
  465. if np.isinf(history['y'].values).any():
  466. raise ValueError('Found infinity in column y.')
  467. self.history_dates = pd.to_datetime(df['ds']).sort_values()
  468. history = self.setup_dataframe(history, initialize_scales=True)
  469. self.history = history
  470. self.set_auto_seasonalities()
  471. seasonal_features = self.make_all_seasonality_features(history)
  472. self.set_changepoints()
  473. A = self.get_changepoint_matrix()
  474. dat = {
  475. 'T': history.shape[0],
  476. 'K': seasonal_features.shape[1],
  477. 'S': len(self.changepoints_t),
  478. 'y': history['y_scaled'],
  479. 't': history['t'],
  480. 'A': A,
  481. 't_change': self.changepoints_t,
  482. 'X': seasonal_features,
  483. 'sigma': self.seasonality_prior_scale,
  484. 'tau': self.changepoint_prior_scale,
  485. }
  486. if self.growth == 'linear':
  487. kinit = self.linear_growth_init(history)
  488. else:
  489. dat['cap'] = history['cap_scaled']
  490. kinit = self.logistic_growth_init(history)
  491. model = prophet_stan_models[self.growth]
  492. def stan_init():
  493. return {
  494. 'k': kinit[0],
  495. 'm': kinit[1],
  496. 'delta': np.zeros(len(self.changepoints_t)),
  497. 'beta': np.zeros(seasonal_features.shape[1]),
  498. 'sigma_obs': 1,
  499. }
  500. if self.mcmc_samples > 0:
  501. stan_fit = model.sampling(
  502. dat,
  503. init=stan_init,
  504. iter=self.mcmc_samples,
  505. **kwargs
  506. )
  507. for par in stan_fit.model_pars:
  508. self.params[par] = stan_fit[par]
  509. else:
  510. try:
  511. params = model.optimizing(
  512. dat, init=stan_init, iter=1e4, **kwargs)
  513. except RuntimeError:
  514. params = model.optimizing(
  515. dat, init=stan_init, iter=1e4, algorithm='Newton',
  516. **kwargs
  517. )
  518. for par in params:
  519. self.params[par] = params[par].reshape((1, -1))
  520. # If no changepoints were requested, replace delta with 0s
  521. if len(self.changepoints) == 0:
  522. # Fold delta into the base rate k
  523. self.params['k'] = self.params['k'] + self.params['delta']
  524. self.params['delta'] = np.zeros(self.params['delta'].shape)
  525. return self
  526. # fb-block 8
  527. def predict(self, df=None):
  528. """Predict using the prophet model.
  529. Parameters
  530. ----------
  531. df: pd.DataFrame with dates for predictions (column ds), and capacity
  532. (column cap) if logistic growth. If not provided, predictions are
  533. made on the history.
  534. Returns
  535. -------
  536. A pd.DataFrame with the forecast components.
  537. """
  538. if df is None:
  539. df = self.history.copy()
  540. else:
  541. df = self.setup_dataframe(df)
  542. df['trend'] = self.predict_trend(df)
  543. seasonal_components = self.predict_seasonal_components(df)
  544. intervals = self.predict_uncertainty(df)
  545. df2 = pd.concat((df, intervals, seasonal_components), axis=1)
  546. df2['yhat'] = df2['trend'] + df2['seasonal']
  547. return df2
  548. @staticmethod
  549. def piecewise_linear(t, deltas, k, m, changepoint_ts):
  550. """Evaluate the piecewise linear function.
  551. Parameters
  552. ----------
  553. t: np.array of times on which the function is evaluated.
  554. deltas: np.array of rate changes at each changepoint.
  555. k: Float initial rate.
  556. m: Float initial offset.
  557. changepoint_ts: np.array of changepoint times.
  558. Returns
  559. -------
  560. Vector y(t).
  561. """
  562. # Intercept changes
  563. gammas = -changepoint_ts * deltas
  564. # Get cumulative slope and intercept at each t
  565. k_t = k * np.ones_like(t)
  566. m_t = m * np.ones_like(t)
  567. for s, t_s in enumerate(changepoint_ts):
  568. indx = t >= t_s
  569. k_t[indx] += deltas[s]
  570. m_t[indx] += gammas[s]
  571. return k_t * t + m_t
  572. @staticmethod
  573. def piecewise_logistic(t, cap, deltas, k, m, changepoint_ts):
  574. """Evaluate the piecewise logistic function.
  575. Parameters
  576. ----------
  577. t: np.array of times on which the function is evaluated.
  578. cap: np.array of capacities at each t.
  579. deltas: np.array of rate changes at each changepoint.
  580. k: Float initial rate.
  581. m: Float initial offset.
  582. changepoint_ts: np.array of changepoint times.
  583. Returns
  584. -------
  585. Vector y(t).
  586. """
  587. # Compute offset changes
  588. k_cum = np.concatenate((np.atleast_1d(k), np.cumsum(deltas) + k))
  589. gammas = np.zeros(len(changepoint_ts))
  590. for i, t_s in enumerate(changepoint_ts):
  591. gammas[i] = (
  592. (t_s - m - np.sum(gammas))
  593. * (1 - k_cum[i] / k_cum[i + 1])
  594. )
  595. # Get cumulative rate and offset at each t
  596. k_t = k * np.ones_like(t)
  597. m_t = m * np.ones_like(t)
  598. for s, t_s in enumerate(changepoint_ts):
  599. indx = t >= t_s
  600. k_t[indx] += deltas[s]
  601. m_t[indx] += gammas[s]
  602. return cap / (1 + np.exp(-k_t * (t - m_t)))
  603. def predict_trend(self, df):
  604. """Predict trend using the prophet model.
  605. Parameters
  606. ----------
  607. df: Prediction dataframe.
  608. Returns
  609. -------
  610. Vector with trend on prediction dates.
  611. """
  612. k = np.nanmean(self.params['k'])
  613. m = np.nanmean(self.params['m'])
  614. deltas = np.nanmean(self.params['delta'], axis=0)
  615. t = np.array(df['t'])
  616. if self.growth == 'linear':
  617. trend = self.piecewise_linear(t, deltas, k, m, self.changepoints_t)
  618. else:
  619. cap = df['cap_scaled']
  620. trend = self.piecewise_logistic(
  621. t, cap, deltas, k, m, self.changepoints_t)
  622. return trend * self.y_scale
  623. def predict_seasonal_components(self, df):
  624. """Predict seasonality broken down into components.
  625. Parameters
  626. ----------
  627. df: Prediction dataframe.
  628. Returns
  629. -------
  630. Dataframe with seasonal components.
  631. """
  632. seasonal_features = self.make_all_seasonality_features(df)
  633. lower_p = 100 * (1.0 - self.interval_width) / 2
  634. upper_p = 100 * (1.0 + self.interval_width) / 2
  635. components = pd.DataFrame({
  636. 'col': np.arange(seasonal_features.shape[1]),
  637. 'component': [x.split('_delim_')[0] for x in seasonal_features.columns],
  638. })
  639. # Remove the placeholder
  640. components = components[components['component'] != 'zeros']
  641. if components.shape[0] > 0:
  642. X = seasonal_features.as_matrix()
  643. data = {}
  644. for component, features in components.groupby('component'):
  645. cols = features.col.tolist()
  646. comp_beta = self.params['beta'][:, cols]
  647. comp_features = X[:, cols]
  648. comp = (
  649. np.matmul(comp_features, comp_beta.transpose())
  650. * self.y_scale
  651. )
  652. data[component] = np.nanmean(comp, axis=1)
  653. data[component + '_lower'] = np.nanpercentile(comp, lower_p,
  654. axis=1)
  655. data[component + '_upper'] = np.nanpercentile(comp, upper_p,
  656. axis=1)
  657. component_predictions = pd.DataFrame(data)
  658. component_predictions['seasonal'] = (
  659. component_predictions[components['component'].unique()].sum(1))
  660. else:
  661. component_predictions = pd.DataFrame(
  662. {'seasonal': np.zeros(df.shape[0])})
  663. return component_predictions
  664. def predict_uncertainty(self, df):
  665. """Predict seasonality broken down into components.
  666. Parameters
  667. ----------
  668. df: Prediction dataframe.
  669. Returns
  670. -------
  671. Dataframe with uncertainty intervals.
  672. """
  673. n_iterations = self.params['k'].shape[0]
  674. samp_per_iter = max(1, int(np.ceil(
  675. self.uncertainty_samples / float(n_iterations)
  676. )))
  677. # Generate seasonality features once so we can re-use them.
  678. seasonal_features = self.make_all_seasonality_features(df)
  679. sim_values = {'yhat': [], 'trend': [], 'seasonal': []}
  680. for i in range(n_iterations):
  681. for _j in range(samp_per_iter):
  682. sim = self.sample_model(df, seasonal_features, i)
  683. for key in sim_values:
  684. sim_values[key].append(sim[key])
  685. lower_p = 100 * (1.0 - self.interval_width) / 2
  686. upper_p = 100 * (1.0 + self.interval_width) / 2
  687. series = {}
  688. for key, value in sim_values.items():
  689. mat = np.column_stack(value)
  690. series['{}_lower'.format(key)] = np.nanpercentile(mat, lower_p,
  691. axis=1)
  692. series['{}_upper'.format(key)] = np.nanpercentile(mat, upper_p,
  693. axis=1)
  694. return pd.DataFrame(series)
  695. def sample_model(self, df, seasonal_features, iteration):
  696. """Simulate observations from the extrapolated generative model.
  697. Parameters
  698. ----------
  699. df: Prediction dataframe.
  700. seasonal_features: pd.DataFrame of seasonal features.
  701. iteration: Int sampling iteration to use parameters from.
  702. Returns
  703. -------
  704. Dataframe with trend, seasonality, and yhat, each like df['t'].
  705. """
  706. trend = self.sample_predictive_trend(df, iteration)
  707. beta = self.params['beta'][iteration]
  708. seasonal = np.matmul(seasonal_features.as_matrix(), beta) * self.y_scale
  709. sigma = self.params['sigma_obs'][iteration]
  710. noise = np.random.normal(0, sigma, df.shape[0]) * self.y_scale
  711. return pd.DataFrame({
  712. 'yhat': trend + seasonal + noise,
  713. 'trend': trend,
  714. 'seasonal': seasonal,
  715. })
  716. def sample_predictive_trend(self, df, iteration):
  717. """Simulate the trend using the extrapolated generative model.
  718. Parameters
  719. ----------
  720. df: Prediction dataframe.
  721. seasonal_features: pd.DataFrame of seasonal features.
  722. iteration: Int sampling iteration to use parameters from.
  723. Returns
  724. -------
  725. np.array of simulated trend over df['t'].
  726. """
  727. k = self.params['k'][iteration]
  728. m = self.params['m'][iteration]
  729. deltas = self.params['delta'][iteration]
  730. t = np.array(df['t'])
  731. T = t.max()
  732. if T > 1:
  733. # Get the time discretization of the history
  734. dt = np.diff(self.history['t'])
  735. dt = np.min(dt[dt > 0])
  736. # Number of time periods in the future
  737. N = np.ceil((T - 1) / float(dt))
  738. S = len(self.changepoints_t)
  739. prob_change = min(1, (S * (T - 1)) / N)
  740. n_changes = np.random.binomial(N, prob_change)
  741. # Sample ts
  742. changepoint_ts_new = sorted(np.random.uniform(1, T, n_changes))
  743. else:
  744. # Case where we're not extrapolating.
  745. changepoint_ts_new = []
  746. n_changes = 0
  747. # Get the empirical scale of the deltas, plus epsilon to avoid NaNs.
  748. lambda_ = np.mean(np.abs(deltas)) + 1e-8
  749. # Sample deltas
  750. deltas_new = np.random.laplace(0, lambda_, n_changes)
  751. # Prepend the times and deltas from the history
  752. changepoint_ts = np.concatenate((self.changepoints_t,
  753. changepoint_ts_new))
  754. deltas = np.concatenate((deltas, deltas_new))
  755. if self.growth == 'linear':
  756. trend = self.piecewise_linear(t, deltas, k, m, changepoint_ts)
  757. else:
  758. cap = df['cap_scaled']
  759. trend = self.piecewise_logistic(t, cap, deltas, k, m,
  760. changepoint_ts)
  761. return trend * self.y_scale
  762. def make_future_dataframe(self, periods, freq='D', include_history=True):
  763. """Simulate the trend using the extrapolated generative model.
  764. Parameters
  765. ----------
  766. periods: Int number of periods to forecast forward.
  767. freq: Any valid frequency for pd.date_range, such as 'D' or 'M'.
  768. include_history: Boolean to include the historical dates in the data
  769. frame for predictions.
  770. Returns
  771. -------
  772. pd.Dataframe that extends forward from the end of self.history for the
  773. requested number of periods.
  774. """
  775. last_date = self.history_dates.max()
  776. dates = pd.date_range(
  777. start=last_date,
  778. periods=periods + 1, # An extra in case we include start
  779. freq=freq)
  780. dates = dates[dates > last_date] # Drop start if equals last_date
  781. dates = dates[:periods] # Return correct number of periods
  782. if include_history:
  783. dates = np.concatenate((np.array(self.history_dates), dates))
  784. return pd.DataFrame({'ds': dates})
  785. def plot(self, fcst, ax=None, uncertainty=True, plot_cap=True, xlabel='ds',
  786. ylabel='y'):
  787. """Plot the Prophet forecast.
  788. Parameters
  789. ----------
  790. fcst: pd.DataFrame output of self.predict.
  791. ax: Optional matplotlib axes on which to plot.
  792. uncertainty: Optional boolean to plot uncertainty intervals.
  793. plot_cap: Optional boolean indicating if the capacity should be shown
  794. in the figure, if available.
  795. xlabel: Optional label name on X-axis
  796. ylabel: Optional label name on Y-axis
  797. Returns
  798. -------
  799. A matplotlib figure.
  800. """
  801. if ax is None:
  802. fig = plt.figure(facecolor='w', figsize=(10, 6))
  803. ax = fig.add_subplot(111)
  804. else:
  805. fig = ax.get_figure()
  806. ax.plot(self.history['ds'].values, self.history['y'], 'k.')
  807. ax.plot(fcst['ds'].values, fcst['yhat'], ls='-', c='#0072B2')
  808. if 'cap' in fcst and plot_cap:
  809. ax.plot(fcst['ds'].values, fcst['cap'], ls='--', c='k')
  810. if uncertainty:
  811. ax.fill_between(fcst['ds'].values, fcst['yhat_lower'],
  812. fcst['yhat_upper'], color='#0072B2',
  813. alpha=0.2)
  814. ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
  815. ax.set_xlabel(xlabel)
  816. ax.set_ylabel(ylabel)
  817. fig.tight_layout()
  818. return fig
  819. def plot_components(self, fcst, uncertainty=True, plot_cap=True,
  820. weekly_start=0, yearly_start=0):
  821. """Plot the Prophet forecast components.
  822. Will plot whichever are available of: trend, holidays, weekly
  823. seasonality, and yearly seasonality.
  824. Parameters
  825. ----------
  826. fcst: pd.DataFrame output of self.predict.
  827. uncertainty: Optional boolean to plot uncertainty intervals.
  828. plot_cap: Optional boolean indicating if the capacity should be shown
  829. in the figure, if available.
  830. weekly_start: Optional int specifying the start day of the weekly
  831. seasonality plot. 0 (default) starts the week on Sunday. 1 shifts
  832. by 1 day to Monday, and so on.
  833. yearly_start: Optional int specifying the start day of the yearly
  834. seasonality plot. 0 (default) starts the year on Jan 1. 1 shifts
  835. by 1 day to Jan 2, and so on.
  836. Returns
  837. -------
  838. A matplotlib figure.
  839. """
  840. # Identify components to be plotted
  841. components = [('trend', True),
  842. ('holidays', self.holidays is not None),
  843. ('weekly', 'weekly' in fcst),
  844. ('yearly', 'yearly' in fcst)]
  845. components = [plot for plot, cond in components if cond]
  846. npanel = len(components)
  847. fig, axes = plt.subplots(npanel, 1, facecolor='w',
  848. figsize=(9, 3 * npanel))
  849. for ax, plot in zip(axes, components):
  850. if plot == 'trend':
  851. self.plot_trend(
  852. fcst, ax=ax, uncertainty=uncertainty, plot_cap=plot_cap)
  853. elif plot == 'holidays':
  854. self.plot_holidays(fcst, ax=ax, uncertainty=uncertainty)
  855. elif plot == 'weekly':
  856. self.plot_weekly(
  857. ax=ax, uncertainty=uncertainty, weekly_start=weekly_start)
  858. elif plot == 'yearly':
  859. self.plot_yearly(
  860. ax=ax, uncertainty=uncertainty, yearly_start=yearly_start)
  861. fig.tight_layout()
  862. return fig
  863. def plot_trend(self, fcst, ax=None, uncertainty=True, plot_cap=True):
  864. """Plot the trend component of the forecast.
  865. Parameters
  866. ----------
  867. fcst: pd.DataFrame output of self.predict.
  868. ax: Optional matplotlib Axes to plot on.
  869. uncertainty: Optional boolean to plot uncertainty intervals.
  870. plot_cap: Optional boolean indicating if the capacity should be shown
  871. in the figure, if available.
  872. Returns
  873. -------
  874. a list of matplotlib artists
  875. """
  876. artists = []
  877. if not ax:
  878. fig = plt.figure(facecolor='w', figsize=(10, 6))
  879. ax = fig.add_subplot(111)
  880. artists += ax.plot(fcst['ds'].values, fcst['trend'], ls='-',
  881. c='#0072B2')
  882. if 'cap' in fcst and plot_cap:
  883. artists += ax.plot(fcst['ds'].values, fcst['cap'], ls='--', c='k')
  884. if uncertainty:
  885. artists += [ax.fill_between(
  886. fcst['ds'].values, fcst['trend_lower'], fcst['trend_upper'],
  887. color='#0072B2', alpha=0.2)]
  888. ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
  889. ax.set_xlabel('ds')
  890. ax.set_ylabel('trend')
  891. return artists
  892. def plot_holidays(self, fcst, ax=None, uncertainty=True):
  893. """Plot the holidays component of the forecast.
  894. Parameters
  895. ----------
  896. fcst: pd.DataFrame output of self.predict.
  897. ax: Optional matplotlib Axes to plot on. One will be created if this
  898. is not provided.
  899. uncertainty: Optional boolean to plot uncertainty intervals.
  900. Returns
  901. -------
  902. a list of matplotlib artists
  903. """
  904. artists = []
  905. if not ax:
  906. fig = plt.figure(facecolor='w', figsize=(10, 6))
  907. ax = fig.add_subplot(111)
  908. holiday_comps = self.holidays['holiday'].unique()
  909. y_holiday = fcst[holiday_comps].sum(1)
  910. y_holiday_l = fcst[[h + '_lower' for h in holiday_comps]].sum(1)
  911. y_holiday_u = fcst[[h + '_upper' for h in holiday_comps]].sum(1)
  912. # NOTE the above CI calculation is incorrect if holidays overlap
  913. # in time. Since it is just for the visualization we will not
  914. # worry about it now.
  915. artists += ax.plot(fcst['ds'].values, y_holiday, ls='-',
  916. c='#0072B2')
  917. if uncertainty:
  918. artists += [ax.fill_between(fcst['ds'].values,
  919. y_holiday_l, y_holiday_u,
  920. color='#0072B2', alpha=0.2)]
  921. ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
  922. ax.set_xlabel('ds')
  923. ax.set_ylabel('holidays')
  924. return artists
  925. def plot_weekly(self, ax=None, uncertainty=True, weekly_start=0):
  926. """Plot the weekly component of the forecast.
  927. Parameters
  928. ----------
  929. ax: Optional matplotlib Axes to plot on. One will be created if this
  930. is not provided.
  931. uncertainty: Optional boolean to plot uncertainty intervals.
  932. weekly_start: Optional int specifying the start day of the weekly
  933. seasonality plot. 0 (default) starts the week on Sunday. 1 shifts
  934. by 1 day to Monday, and so on.
  935. Returns
  936. -------
  937. a list of matplotlib artists
  938. """
  939. artists = []
  940. if not ax:
  941. fig = plt.figure(facecolor='w', figsize=(10, 6))
  942. ax = fig.add_subplot(111)
  943. # Compute weekly seasonality for a Sun-Sat sequence of dates.
  944. days = (pd.date_range(start='2017-01-01', periods=7) +
  945. pd.Timedelta(days=weekly_start))
  946. df_w = pd.DataFrame({'ds': days, 'cap': 1.})
  947. df_w = self.setup_dataframe(df_w)
  948. seas = self.predict_seasonal_components(df_w)
  949. days = days.weekday_name
  950. artists += ax.plot(range(len(days)), seas['weekly'], ls='-',
  951. c='#0072B2')
  952. if uncertainty:
  953. artists += [ax.fill_between(range(len(days)),
  954. seas['weekly_lower'], seas['weekly_upper'],
  955. color='#0072B2', alpha=0.2)]
  956. ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
  957. ax.set_xticks(range(len(days)))
  958. ax.set_xticklabels(days)
  959. ax.set_xlabel('Day of week')
  960. ax.set_ylabel('weekly')
  961. return artists
  962. def plot_yearly(self, ax=None, uncertainty=True, yearly_start=0):
  963. """Plot the yearly component of the forecast.
  964. Parameters
  965. ----------
  966. ax: Optional matplotlib Axes to plot on. One will be created if
  967. this is not provided.
  968. uncertainty: Optional boolean to plot uncertainty intervals.
  969. yearly_start: Optional int specifying the start day of the yearly
  970. seasonality plot. 0 (default) starts the year on Jan 1. 1 shifts
  971. by 1 day to Jan 2, and so on.
  972. Returns
  973. -------
  974. a list of matplotlib artists
  975. """
  976. artists = []
  977. if not ax:
  978. fig = plt.figure(facecolor='w', figsize=(10, 6))
  979. ax = fig.add_subplot(111)
  980. # Compute yearly seasonality for a Jan 1 - Dec 31 sequence of dates.
  981. df_y = pd.DataFrame(
  982. {'ds': pd.date_range(start='2017-01-01', periods=365) +
  983. pd.Timedelta(days=yearly_start), 'cap': 1.})
  984. df_y = self.setup_dataframe(df_y)
  985. seas = self.predict_seasonal_components(df_y)
  986. artists += ax.plot(df_y['ds'], seas['yearly'], ls='-',
  987. c='#0072B2')
  988. if uncertainty:
  989. artists += [ax.fill_between(
  990. df_y['ds'].values, seas['yearly_lower'],
  991. seas['yearly_upper'], color='#0072B2', alpha=0.2)]
  992. ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
  993. months = MonthLocator(range(1, 13), bymonthday=1, interval=2)
  994. ax.xaxis.set_major_formatter(FuncFormatter(
  995. lambda x, pos=None: '{dt:%B} {dt.day}'.format(dt=num2date(x))))
  996. ax.xaxis.set_major_locator(months)
  997. ax.set_xlabel('Day of year')
  998. ax.set_ylabel('yearly')
  999. return artists