forecaster.py 41 KB

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