forecaster.py 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081
  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 pickle
  14. from matplotlib import pyplot as plt
  15. from matplotlib.dates import MonthLocator, num2date
  16. from matplotlib.ticker import FuncFormatter
  17. import numpy as np
  18. import pandas as pd
  19. # fb-block 1 start
  20. import pkg_resources
  21. # fb-block 1 end
  22. try:
  23. import pystan
  24. except ImportError:
  25. print('You cannot run prophet without pystan installed')
  26. raise
  27. # fb-block 2
  28. class Prophet(object):
  29. """Prophet forecaster.
  30. Parameters
  31. ----------
  32. growth: String 'linear' or 'logistic' to specify a linear or logistic
  33. trend.
  34. changepoints: List of dates at which to include potential changepoints. If
  35. not specified, potential changepoints are selected automatically.
  36. n_changepoints: Number of potential changepoints to include. Not used
  37. if input `changepoints` is supplied. If `changepoints` is not supplied,
  38. then n.changepoints potential changepoints are selected uniformly from
  39. the first 80 percent of the history.
  40. yearly_seasonality: Boolean, fit yearly seasonality.
  41. weekly_seasonality: Boolean, fit weekly seasonality.
  42. holidays: pd.DataFrame with columns holiday (string) and ds (date type)
  43. and optionally columns lower_window and upper_window which specify a
  44. range of days around the date to be included as holidays.
  45. lower_window=-2 will include 2 days prior to the date as holidays.
  46. seasonality_prior_scale: Parameter modulating the strength of the
  47. seasonality model. Larger values allow the model to fit larger seasonal
  48. fluctuations, smaller values dampen the seasonality.
  49. holidays_prior_scale: Parameter modulating the strength of the holiday
  50. components model.
  51. changepoint_prior_scale: Parameter modulating the flexibility of the
  52. automatic changepoint selection. Large values will allow many
  53. changepoints, small values will allow few changepoints.
  54. mcmc_samples: Integer, if greater than 0, will do full Bayesian inference
  55. with the specified number of MCMC samples. If 0, will do MAP
  56. estimation.
  57. interval_width: Float, width of the uncertainty intervals provided
  58. for the forecast. If mcmc_samples=0, this will be only the uncertainty
  59. in the trend using the MAP estimate of the extrapolated generative
  60. model. If mcmc.samples>0, this will be integrated over all model
  61. parameters, which will include uncertainty in seasonality.
  62. uncertainty_samples: Number of simulated draws used to estimate
  63. uncertainty intervals.
  64. """
  65. def __init__(
  66. self,
  67. growth='linear',
  68. changepoints=None,
  69. n_changepoints=25,
  70. yearly_seasonality=True,
  71. weekly_seasonality=True,
  72. holidays=None,
  73. seasonality_prior_scale=10.0,
  74. holidays_prior_scale=10.0,
  75. changepoint_prior_scale=0.05,
  76. mcmc_samples=0,
  77. interval_width=0.80,
  78. uncertainty_samples=1000,
  79. ):
  80. self.growth = growth
  81. self.changepoints = pd.to_datetime(changepoints)
  82. if self.changepoints is not None:
  83. self.n_changepoints = len(self.changepoints)
  84. else:
  85. self.n_changepoints = n_changepoints
  86. self.yearly_seasonality = yearly_seasonality
  87. self.weekly_seasonality = weekly_seasonality
  88. if holidays is not None:
  89. if not (
  90. isinstance(holidays, pd.DataFrame)
  91. and 'ds' in holidays
  92. and 'holiday' in holidays
  93. ):
  94. raise ValueError("holidays must be a DataFrame with 'ds' and "
  95. "'holiday' columns.")
  96. holidays['ds'] = pd.to_datetime(holidays['ds'])
  97. self.holidays = holidays
  98. self.seasonality_prior_scale = float(seasonality_prior_scale)
  99. self.changepoint_prior_scale = float(changepoint_prior_scale)
  100. self.holidays_prior_scale = float(holidays_prior_scale)
  101. self.mcmc_samples = mcmc_samples
  102. self.interval_width = interval_width
  103. self.uncertainty_samples = uncertainty_samples
  104. # Set during fitting
  105. self.start = None
  106. self.y_scale = None
  107. self.t_scale = None
  108. self.changepoints_t = None
  109. self.stan_fit = None
  110. self.params = {}
  111. self.history = None
  112. self.history_dates = None
  113. self.validate_inputs()
  114. def validate_inputs(self):
  115. """Validates the inputs to Prophet."""
  116. if self.growth not in ('linear', 'logistic'):
  117. raise ValueError(
  118. "Parameter 'growth' should be 'linear' or 'logistic'.")
  119. if self.holidays is not None:
  120. has_lower = 'lower_window' in self.holidays
  121. has_upper = 'upper_window' in self.holidays
  122. if has_lower + has_upper == 1:
  123. raise ValueError('Holidays must have both lower_window and ' +
  124. 'upper_window, or neither')
  125. if has_lower:
  126. if max(self.holidays['lower_window']) > 0:
  127. raise ValueError('Holiday lower_window should be <= 0')
  128. if min(self.holidays['upper_window']) < 0:
  129. raise ValueError('Holiday upper_window should be >= 0')
  130. for h in self.holidays['holiday'].unique():
  131. if '_delim_' in h:
  132. raise ValueError('Holiday name cannot contain "_delim_"')
  133. if h in ['zeros', 'yearly', 'weekly', 'yhat', 'seasonal',
  134. 'trend']:
  135. raise ValueError('Holiday name {} reserved.'.format(h))
  136. @classmethod
  137. def get_linear_model(cls):
  138. """Load compiled linear trend Stan model"""
  139. # fb-block 3
  140. # fb-block 4 start
  141. model_file = pkg_resources.resource_filename(
  142. 'fbprophet',
  143. 'stan_models/linear_growth.pkl'
  144. )
  145. # fb-block 4 end
  146. with open(model_file, 'rb') as f:
  147. return pickle.load(f)
  148. @classmethod
  149. def get_logistic_model(cls):
  150. """Load compiled logistic trend Stan model"""
  151. # fb-block 5
  152. # fb-block 6 start
  153. model_file = pkg_resources.resource_filename(
  154. 'fbprophet',
  155. 'stan_models/logistic_growth.pkl'
  156. )
  157. # fb-block 6 end
  158. with open(model_file, 'rb') as f:
  159. return pickle.load(f)
  160. def setup_dataframe(self, df, initialize_scales=False):
  161. """Prepare dataframe for fitting or predicting.
  162. Adds a time index and scales y. Creates auxillary columns 't', 't_ix',
  163. 'y_scaled', and 'cap_scaled'. These columns are used during both
  164. fitting and predicting.
  165. Parameters
  166. ----------
  167. df: pd.DataFrame with columns ds, y, and cap if logistic growth.
  168. initialize_scales: Boolean set scaling factors in self from df.
  169. Returns
  170. -------
  171. pd.DataFrame prepared for fitting or predicting.
  172. """
  173. if 'y' in df:
  174. df['y'] = pd.to_numeric(df['y'])
  175. df['ds'] = pd.to_datetime(df['ds'])
  176. df = df.sort_values('ds')
  177. df.reset_index(inplace=True, drop=True)
  178. if initialize_scales:
  179. self.y_scale = df['y'].max()
  180. self.start = df['ds'].min()
  181. self.t_scale = df['ds'].max() - self.start
  182. df['t'] = (df['ds'] - self.start) / self.t_scale
  183. if 'y' in df:
  184. df['y_scaled'] = df['y'] / self.y_scale
  185. if self.growth == 'logistic':
  186. assert 'cap' in df
  187. df['cap_scaled'] = df['cap'] / self.y_scale
  188. return df
  189. def set_changepoints(self):
  190. """Set changepoints
  191. Sets m$changepoints to the dates of changepoints. Either:
  192. 1) The changepoints were passed in explicitly.
  193. A) They are empty.
  194. B) They are not empty, and need validation.
  195. 2) We are generating a grid of them.
  196. 3) The user prefers no changepoints be used.
  197. """
  198. if self.changepoints is not None:
  199. if len(self.changepoints) == 0:
  200. pass
  201. else:
  202. too_low = min(self.changepoints) < self.history['ds'].min()
  203. too_high = max(self.changepoints) > self.history['ds'].max()
  204. if too_low or too_high:
  205. raise ValueError('Changepoints must fall within training data.')
  206. elif self.n_changepoints > 0:
  207. # Place potential changepoints evenly throuh first 80% of history
  208. max_ix = np.floor(self.history.shape[0] * 0.8)
  209. cp_indexes = (
  210. np.linspace(0, max_ix, self.n_changepoints + 1)
  211. .round()
  212. .astype(np.int)
  213. )
  214. self.changepoints = self.history.ix[cp_indexes]['ds'].tail(-1)
  215. else:
  216. # set empty changepoints
  217. self.changepoints = []
  218. if len(self.changepoints) > 0:
  219. self.changepoints_t = np.sort(np.array(
  220. (self.changepoints - self.start) / self.t_scale))
  221. else:
  222. self.changepoints_t = np.array([0]) # dummy changepoint
  223. def get_changepoint_matrix(self):
  224. """Gets changepoint matrix for history dataframe."""
  225. A = np.zeros((self.history.shape[0], len(self.changepoints_t)))
  226. for i, t_i in enumerate(self.changepoints_t):
  227. A[self.history['t'].values >= t_i, i] = 1
  228. return A
  229. @staticmethod
  230. def fourier_series(dates, period, series_order):
  231. """Provides Fourier series components with the specified frequency
  232. and order.
  233. Parameters
  234. ----------
  235. dates: pd.Series containing timestamps.
  236. period: Number of days of the period.
  237. series_order: Number of components.
  238. Returns
  239. -------
  240. Matrix with seasonality features.
  241. """
  242. # convert to days since epoch
  243. t = np.array(
  244. (dates - pd.datetime(1970, 1, 1))
  245. .dt.days
  246. .astype(np.float)
  247. )
  248. return np.column_stack([
  249. fun((2.0 * (i + 1) * np.pi * t / period))
  250. for i in range(series_order)
  251. for fun in (np.sin, np.cos)
  252. ])
  253. @classmethod
  254. def make_seasonality_features(cls, dates, period, series_order, prefix):
  255. """Data frame with seasonality features.
  256. Parameters
  257. ----------
  258. cls: Prophet class.
  259. dates: pd.Series containing timestamps.
  260. period: Number of days of the period.
  261. series_order: Number of components.
  262. prefix: Column name prefix.
  263. Returns
  264. -------
  265. pd.DataFrame with seasonality features.
  266. """
  267. features = cls.fourier_series(dates, period, series_order)
  268. columns = [
  269. '{}_delim_{}'.format(prefix, i + 1)
  270. for i in range(features.shape[1])
  271. ]
  272. return pd.DataFrame(features, columns=columns)
  273. def make_holiday_features(self, dates):
  274. """Construct a dataframe of holiday features.
  275. Parameters
  276. ----------
  277. dates: pd.Series containing timestamps used for computing seasonality.
  278. Returns
  279. -------
  280. pd.DataFrame with a column for each holiday.
  281. """
  282. # A smaller prior scale will shrink holiday estimates more
  283. scale_ratio = self.holidays_prior_scale / self.seasonality_prior_scale
  284. # Holds columns of our future matrix.
  285. expanded_holidays = defaultdict(lambda: np.zeros(dates.shape[0]))
  286. # Makes an index so we can perform `get_loc` below.
  287. row_index = pd.DatetimeIndex(dates)
  288. for _ix, row in self.holidays.iterrows():
  289. dt = row.ds.date()
  290. try:
  291. lw = int(row.get('lower_window', 0))
  292. uw = int(row.get('upper_window', 0))
  293. except ValueError:
  294. lw = 0
  295. uw = 0
  296. for offset in range(lw, uw + 1):
  297. occurrence = dt + timedelta(days=offset)
  298. try:
  299. loc = row_index.get_loc(occurrence)
  300. except KeyError:
  301. loc = None
  302. key = '{}_delim_{}{}'.format(
  303. row.holiday,
  304. '+' if offset >= 0 else '-',
  305. abs(offset)
  306. )
  307. if loc is not None:
  308. expanded_holidays[key][loc] = scale_ratio
  309. else:
  310. # Access key to generate value
  311. expanded_holidays[key]
  312. # This relies pretty importantly on pandas keeping the columns in order.
  313. return pd.DataFrame(expanded_holidays)
  314. def make_all_seasonality_features(self, df):
  315. """Dataframe with seasonality features.
  316. Parameters
  317. ----------
  318. df: pd.DataFrame with dates for computing seasonality features.
  319. Returns
  320. -------
  321. pd.DataFrame with seasonality.
  322. """
  323. seasonal_features = [
  324. # Add a column of zeros in case no seasonality is used.
  325. pd.DataFrame({'zeros': np.zeros(df.shape[0])})
  326. ]
  327. # Seasonality features
  328. if self.yearly_seasonality:
  329. seasonal_features.append(self.make_seasonality_features(
  330. df['ds'],
  331. 365.25,
  332. 10,
  333. 'yearly',
  334. ))
  335. if self.weekly_seasonality:
  336. seasonal_features.append(self.make_seasonality_features(
  337. df['ds'],
  338. 7,
  339. 3,
  340. 'weekly',
  341. ))
  342. if self.holidays is not None:
  343. seasonal_features.append(self.make_holiday_features(df['ds']))
  344. return pd.concat(seasonal_features, axis=1)
  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. seasonal_features = self.make_all_seasonality_features(history)
  425. self.set_changepoints()
  426. A = self.get_changepoint_matrix()
  427. dat = {
  428. 'T': history.shape[0],
  429. 'K': seasonal_features.shape[1],
  430. 'S': len(self.changepoints_t),
  431. 'y': history['y_scaled'],
  432. 't': history['t'],
  433. 'A': A,
  434. 't_change': self.changepoints_t,
  435. 'X': seasonal_features,
  436. 'sigma': self.seasonality_prior_scale,
  437. 'tau': self.changepoint_prior_scale,
  438. }
  439. if self.growth == 'linear':
  440. kinit = self.linear_growth_init(history)
  441. model = self.get_linear_model()
  442. else:
  443. dat['cap'] = history['cap_scaled']
  444. kinit = self.logistic_growth_init(history)
  445. model = self.get_logistic_model()
  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. params['k'] = params['k'] + params['delta']
  471. params['delta'] = np.zeros(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, 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. uncertainty: Optional boolean to plot uncertainty intervals.
  739. plot_cap: Optional boolean indicating if the capacity should be shown
  740. in the figure, if available.
  741. xlabel: Optional label name on X-axis
  742. ylabel: Optional label name on Y-axis
  743. Returns
  744. -------
  745. a matplotlib figure.
  746. """
  747. fig = plt.figure(facecolor='w', figsize=(10, 6))
  748. ax = fig.add_subplot(111)
  749. ax.plot(self.history['ds'].values, self.history['y'], 'k.')
  750. ax.plot(fcst['ds'].values, fcst['yhat'], ls='-', c='#0072B2')
  751. if 'cap' in fcst and plot_cap:
  752. ax.plot(fcst['ds'].values, fcst['cap'], ls='--', c='k')
  753. if uncertainty:
  754. ax.fill_between(fcst['ds'].values, fcst['yhat_lower'],
  755. fcst['yhat_upper'], color='#0072B2',
  756. alpha=0.2)
  757. ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
  758. ax.set_xlabel(xlabel)
  759. ax.set_ylabel(ylabel)
  760. fig.tight_layout()
  761. return fig
  762. def plot_components(self, fcst, uncertainty=True, plot_cap=True):
  763. """Plot the Prophet forecast components.
  764. Will plot whichever are available of: trend, holidays, weekly
  765. seasonality, and yearly seasonality.
  766. Parameters
  767. ----------
  768. fcst: pd.DataFrame output of self.predict.
  769. uncertainty: Optional boolean to plot uncertainty intervals.
  770. plot_cap: Optional boolean indicating if the capacity should be shown
  771. in the figure, if available.
  772. Returns
  773. -------
  774. a matplotlib figure.
  775. """
  776. # Identify components to be plotted
  777. components = [('trend', True),
  778. ('holidays', self.holidays is not None),
  779. ('weekly', 'weekly' in fcst),
  780. ('yearly', 'yearly' in fcst)]
  781. components = [plot for plot, cond in components if cond]
  782. npanel = len(components)
  783. fig, axes = plt.subplots(npanel, 1, facecolor='w',
  784. figsize=(9, 3 * npanel))
  785. artists = []
  786. for ax, plot in zip(axes, components):
  787. if plot == 'trend':
  788. artists += self.plot_trend(
  789. fcst, ax=ax, uncertainty=uncertainty, plot_cap=plot_cap)
  790. elif plot == 'holidays':
  791. artists += self.plot_holidays(fcst, ax=ax,
  792. uncertainty=uncertainty)
  793. elif plot == 'weekly':
  794. artists += self.plot_weekly(ax=ax, uncertainty=uncertainty)
  795. elif plot == 'yearly':
  796. artists += self.plot_yearly(ax=ax, uncertainty=uncertainty)
  797. fig.tight_layout()
  798. return artists
  799. def plot_trend(self, fcst, ax=None, uncertainty=True, plot_cap=True):
  800. """Plot the trend component of the forecast.
  801. Parameters
  802. ----------
  803. fcst: pd.DataFrame output of self.predict.
  804. ax: Optional matplotlib Axes to plot on.
  805. uncertainty: Optional boolean to plot uncertainty intervals.
  806. plot_cap: Optional boolean indicating if the capacity should be shown
  807. in the figure, if available.
  808. Returns
  809. -------
  810. a list of matplotlib artists
  811. """
  812. artists = []
  813. if not ax:
  814. fig = plt.figure(facecolor='w', figsize=(10, 6))
  815. ax = fig.add_subplot(111)
  816. artists += ax.plot(fcst['ds'].values, fcst['trend'], ls='-',
  817. c='#0072B2')
  818. if 'cap' in fcst and plot_cap:
  819. artists += ax.plot(fcst['ds'].values, fcst['cap'], ls='--', c='k')
  820. if uncertainty:
  821. artists += [ax.fill_between(
  822. fcst['ds'].values, fcst['trend_lower'], fcst['trend_upper'],
  823. color='#0072B2', alpha=0.2)]
  824. ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
  825. ax.set_xlabel('ds')
  826. ax.set_ylabel('trend')
  827. return artists
  828. def plot_holidays(self, fcst, ax=None, uncertainty=True):
  829. """Plot the holidays component of the forecast.
  830. Parameters
  831. ----------
  832. fcst: pd.DataFrame output of self.predict.
  833. ax: Optional matplotlib Axes to plot on. One will be created if this
  834. is not provided.
  835. uncertainty: Optional boolean to plot uncertainty intervals.
  836. Returns
  837. -------
  838. a list of matplotlib artists
  839. """
  840. artists = []
  841. if not ax:
  842. fig = plt.figure(facecolor='w', figsize=(10, 6))
  843. ax = fig.add_subplot(111)
  844. holiday_comps = self.holidays['holiday'].unique()
  845. y_holiday = fcst[holiday_comps].sum(1)
  846. y_holiday_l = fcst[[h + '_lower' for h in holiday_comps]].sum(1)
  847. y_holiday_u = fcst[[h + '_upper' for h in holiday_comps]].sum(1)
  848. # NOTE the above CI calculation is incorrect if holidays overlap
  849. # in time. Since it is just for the visualization we will not
  850. # worry about it now.
  851. artists += ax.plot(fcst['ds'].values, y_holiday, ls='-',
  852. c='#0072B2')
  853. if uncertainty:
  854. artists += [ax.fill_between(fcst['ds'].values,
  855. y_holiday_l, y_holiday_u,
  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('holidays')
  860. return artists
  861. def plot_weekly(self, ax=None, uncertainty=True):
  862. """Plot the weekly component of the forecast.
  863. Parameters
  864. ----------
  865. ax: Optional matplotlib Axes to plot on. One will be created if this
  866. is not provided.
  867. uncertainty: Optional boolean to plot uncertainty intervals.
  868. Returns
  869. -------
  870. a list of matplotlib artists
  871. """
  872. artists = []
  873. if not ax:
  874. fig = plt.figure(facecolor='w', figsize=(10, 6))
  875. ax = fig.add_subplot(111)
  876. # Compute weekly seasonality for a Sun-Sat sequence of dates.
  877. days = pd.date_range(start='2017-01-01', periods=7)
  878. df_w = pd.DataFrame({'ds': days, 'cap': 1.})
  879. df_w = self.setup_dataframe(df_w)
  880. seas = self.predict_seasonal_components(df_w)
  881. days = days.weekday_name
  882. artists += ax.plot(range(len(days)), seas['weekly'], ls='-',
  883. c='#0072B2')
  884. if uncertainty:
  885. artists += [ax.fill_between(range(len(days)),
  886. seas['weekly_lower'], seas['weekly_upper'],
  887. color='#0072B2', alpha=0.2)]
  888. ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
  889. ax.set_xticks(range(len(days)))
  890. ax.set_xticklabels(days)
  891. ax.set_xlabel('Day of week')
  892. ax.set_ylabel('weekly')
  893. return artists
  894. def plot_yearly(self, ax=None, uncertainty=True):
  895. """Plot the yearly component of the forecast.
  896. Parameters
  897. ----------
  898. ax: Optional matplotlib Axes to plot on. One will be created if
  899. this is not provided.
  900. uncertainty: Optional boolean to plot uncertainty intervals.
  901. Returns
  902. -------
  903. a list of matplotlib artists
  904. """
  905. artists = []
  906. if not ax:
  907. fig = plt.figure(facecolor='w', figsize=(10, 6))
  908. ax = fig.add_subplot(111)
  909. # Compute yearly seasonality for a Jan 1 - Dec 31 sequence of dates.
  910. df_y = pd.DataFrame(
  911. {'ds': pd.date_range(start='2017-01-01', periods=365), 'cap': 1.})
  912. df_y = self.setup_dataframe(df_y)
  913. seas = self.predict_seasonal_components(df_y)
  914. artists += ax.plot(df_y['ds'], seas['yearly'], ls='-',
  915. c='#0072B2')
  916. if uncertainty:
  917. artists += [ax.fill_between(
  918. df_y['ds'].values, seas['yearly_lower'],
  919. seas['yearly_upper'], color='#0072B2', alpha=0.2)]
  920. ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
  921. months = MonthLocator(range(1, 13), bymonthday=1, interval=2)
  922. ax.xaxis.set_major_formatter(FuncFormatter(
  923. lambda x, pos=None: '{dt:%B} {dt.day}'.format(dt=num2date(x))))
  924. ax.xaxis.set_major_locator(months)
  925. ax.set_xlabel('Day of year')
  926. ax.set_ylabel('yearly')
  927. return artists
  928. # fb-block 9