forecaster.py 40 KB

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