forecaster.py 40 KB

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