forecaster.py 40 KB

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