forecaster.py 40 KB

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