forecaster.py 42 KB

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