forecaster.py 40 KB

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