forecaster.py 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477
  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. import warnings
  15. import numpy as np
  16. import pandas as pd
  17. try:
  18. import pystan # noqa F401
  19. except ImportError:
  20. logger.exception('You cannot run fbprophet without pystan installed')
  21. from fbprophet.diagnostics import prophet_copy
  22. from fbprophet.models import prophet_stan_model
  23. from fbprophet.plot import (
  24. plot,
  25. plot_components,
  26. plot_forecast_component,
  27. seasonality_plot_df,
  28. plot_weekly,
  29. plot_yearly,
  30. plot_seasonality,
  31. )
  32. logging.basicConfig()
  33. logger = logging.getLogger(__name__)
  34. warnings.filterwarnings("default", category=DeprecationWarning)
  35. class Prophet(object):
  36. """Prophet forecaster.
  37. Parameters
  38. ----------
  39. growth: String 'linear' or 'logistic' to specify a linear or logistic
  40. trend.
  41. changepoints: List of dates at which to include potential changepoints. If
  42. not specified, potential changepoints are selected automatically.
  43. n_changepoints: Number of potential changepoints to include. Not used
  44. if input `changepoints` is supplied. If `changepoints` is not supplied,
  45. then n_changepoints potential changepoints are selected uniformly from
  46. the first `changepoint_range` proportion of the history.
  47. changepoint_range: Proportion of history in which trend changepoints will
  48. be estimated. Defaults to 0.8 for the first 80%. Not used if
  49. `changepoints` is specified.
  50. Not used if input `changepoints` is supplied.
  51. yearly_seasonality: Fit yearly seasonality.
  52. Can be 'auto', True, False, or a number of Fourier terms to generate.
  53. weekly_seasonality: Fit weekly seasonality.
  54. Can be 'auto', True, False, or a number of Fourier terms to generate.
  55. daily_seasonality: Fit daily seasonality.
  56. Can be 'auto', True, False, or a number of Fourier terms to generate.
  57. holidays: pd.DataFrame with columns holiday (string) and ds (date type)
  58. and optionally columns lower_window and upper_window which specify a
  59. range of days around the date to be included as holidays.
  60. lower_window=-2 will include 2 days prior to the date as holidays. Also
  61. optionally can have a column prior_scale specifying the prior scale for
  62. that holiday.
  63. seasonality_mode: 'additive' (default) or 'multiplicative'.
  64. seasonality_prior_scale: Parameter modulating the strength of the
  65. seasonality model. Larger values allow the model to fit larger seasonal
  66. fluctuations, smaller values dampen the seasonality. Can be specified
  67. for individual seasonalities using add_seasonality.
  68. holidays_prior_scale: Parameter modulating the strength of the holiday
  69. components model, unless overridden in the holidays input.
  70. changepoint_prior_scale: Parameter modulating the flexibility of the
  71. automatic changepoint selection. Large values will allow many
  72. changepoints, small values will allow few changepoints.
  73. mcmc_samples: Integer, if greater than 0, will do full Bayesian inference
  74. with the specified number of MCMC samples. If 0, will do MAP
  75. estimation.
  76. interval_width: Float, width of the uncertainty intervals provided
  77. for the forecast. If mcmc_samples=0, this will be only the uncertainty
  78. in the trend using the MAP estimate of the extrapolated generative
  79. model. If mcmc.samples>0, this will be integrated over all model
  80. parameters, which will include uncertainty in seasonality.
  81. uncertainty_samples: Number of simulated draws used to estimate
  82. uncertainty intervals.
  83. """
  84. def __init__(
  85. self,
  86. growth='linear',
  87. changepoints=None,
  88. n_changepoints=25,
  89. changepoint_range=0.8,
  90. yearly_seasonality='auto',
  91. weekly_seasonality='auto',
  92. daily_seasonality='auto',
  93. holidays=None,
  94. seasonality_mode='additive',
  95. seasonality_prior_scale=10.0,
  96. holidays_prior_scale=10.0,
  97. changepoint_prior_scale=0.05,
  98. mcmc_samples=0,
  99. interval_width=0.80,
  100. uncertainty_samples=1000,
  101. ):
  102. self.growth = growth
  103. self.changepoints = pd.to_datetime(changepoints)
  104. if self.changepoints is not None:
  105. self.n_changepoints = len(self.changepoints)
  106. self.specified_changepoints = True
  107. else:
  108. self.n_changepoints = n_changepoints
  109. self.specified_changepoints = False
  110. self.changepoint_range = changepoint_range
  111. self.yearly_seasonality = yearly_seasonality
  112. self.weekly_seasonality = weekly_seasonality
  113. self.daily_seasonality = daily_seasonality
  114. if holidays is not None:
  115. if not (
  116. isinstance(holidays, pd.DataFrame)
  117. and 'ds' in holidays # noqa W503
  118. and 'holiday' in holidays # noqa W503
  119. ):
  120. raise ValueError("holidays must be a DataFrame with 'ds' and "
  121. "'holiday' columns.")
  122. holidays['ds'] = pd.to_datetime(holidays['ds'])
  123. self.holidays = holidays
  124. self.seasonality_mode = seasonality_mode
  125. self.seasonality_prior_scale = float(seasonality_prior_scale)
  126. self.changepoint_prior_scale = float(changepoint_prior_scale)
  127. self.holidays_prior_scale = float(holidays_prior_scale)
  128. self.mcmc_samples = mcmc_samples
  129. self.interval_width = interval_width
  130. self.uncertainty_samples = uncertainty_samples
  131. # Set during fitting
  132. self.start = None
  133. self.y_scale = None
  134. self.logistic_floor = False
  135. self.t_scale = None
  136. self.changepoints_t = None
  137. self.seasonalities = {}
  138. self.extra_regressors = {}
  139. self.stan_fit = None
  140. self.params = {}
  141. self.history = None
  142. self.history_dates = None
  143. self.train_component_cols = None
  144. self.component_modes = None
  145. self.validate_inputs()
  146. def validate_inputs(self):
  147. """Validates the inputs to Prophet."""
  148. if self.growth not in ('linear', 'logistic'):
  149. raise ValueError(
  150. "Parameter 'growth' should be 'linear' or 'logistic'.")
  151. if ((self.changepoint_range < 0) or (self.changepoint_range > 1)):
  152. raise ValueError("Parameter 'changepoint_range' must be in [0, 1]")
  153. if self.holidays is not None:
  154. has_lower = 'lower_window' in self.holidays
  155. has_upper = 'upper_window' in self.holidays
  156. if has_lower + has_upper == 1:
  157. raise ValueError('Holidays must have both lower_window and ' +
  158. 'upper_window, or neither')
  159. if has_lower:
  160. if self.holidays['lower_window'].max() > 0:
  161. raise ValueError('Holiday lower_window should be <= 0')
  162. if self.holidays['upper_window'].min() < 0:
  163. raise ValueError('Holiday upper_window should be >= 0')
  164. for h in self.holidays['holiday'].unique():
  165. self.validate_column_name(h, check_holidays=False)
  166. if self.seasonality_mode not in ['additive', 'multiplicative']:
  167. raise ValueError(
  168. "seasonality_mode must be 'additive' or 'multiplicative'"
  169. )
  170. def validate_column_name(self, name, check_holidays=True,
  171. check_seasonalities=True, check_regressors=True):
  172. """Validates the name of a seasonality, holiday, or regressor.
  173. Parameters
  174. ----------
  175. name: string
  176. check_holidays: bool check if name already used for holiday
  177. check_seasonalities: bool check if name already used for seasonality
  178. check_regressors: bool check if name already used for regressor
  179. """
  180. if '_delim_' in name:
  181. raise ValueError('Name cannot contain "_delim_"')
  182. reserved_names = [
  183. 'trend', 'additive_terms', 'daily', 'weekly', 'yearly',
  184. 'holidays', 'zeros', 'extra_regressors_additive','yhat',
  185. 'extra_regressors_multiplicative', 'multiplicative_terms',
  186. ]
  187. rn_l = [n + '_lower' for n in reserved_names]
  188. rn_u = [n + '_upper' for n in reserved_names]
  189. reserved_names.extend(rn_l)
  190. reserved_names.extend(rn_u)
  191. reserved_names.extend([
  192. 'ds', 'y', 'cap', 'floor', 'y_scaled', 'cap_scaled'])
  193. if name in reserved_names:
  194. raise ValueError('Name "{}" is reserved.'.format(name))
  195. if (check_holidays and self.holidays is not None and
  196. name in self.holidays['holiday'].unique()):
  197. raise ValueError(
  198. 'Name "{}" already used for a holiday.'.format(name))
  199. if check_seasonalities and name in self.seasonalities:
  200. raise ValueError(
  201. 'Name "{}" already used for a seasonality.'.format(name))
  202. if check_regressors and name in self.extra_regressors:
  203. raise ValueError(
  204. 'Name "{}" already used for an added regressor.'.format(name))
  205. def setup_dataframe(self, df, initialize_scales=False):
  206. """Prepare dataframe for fitting or predicting.
  207. Adds a time index and scales y. Creates auxiliary columns 't', 't_ix',
  208. 'y_scaled', and 'cap_scaled'. These columns are used during both
  209. fitting and predicting.
  210. Parameters
  211. ----------
  212. df: pd.DataFrame with columns ds, y, and cap if logistic growth. Any
  213. specified additional regressors must also be present.
  214. initialize_scales: Boolean set scaling factors in self from df.
  215. Returns
  216. -------
  217. pd.DataFrame prepared for fitting or predicting.
  218. """
  219. if 'y' in df:
  220. df['y'] = pd.to_numeric(df['y'])
  221. if np.isinf(df['y'].values).any():
  222. raise ValueError('Found infinity in column y.')
  223. df['ds'] = pd.to_datetime(df['ds'])
  224. if df['ds'].isnull().any():
  225. raise ValueError('Found NaN in column ds.')
  226. for name in self.extra_regressors:
  227. if name not in df:
  228. raise ValueError(
  229. 'Regressor "{}" missing from dataframe'.format(name))
  230. df = df.sort_values('ds')
  231. df.reset_index(inplace=True, drop=True)
  232. self.initialize_scales(initialize_scales, df)
  233. if self.logistic_floor:
  234. if 'floor' not in df:
  235. raise ValueError("Expected column 'floor'.")
  236. else:
  237. df['floor'] = 0
  238. if self.growth == 'logistic':
  239. if 'cap' not in df:
  240. raise ValueError(
  241. "Capacities must be supplied for logistic growth in "
  242. "column 'cap'"
  243. )
  244. df['cap_scaled'] = (df['cap'] - df['floor']) / self.y_scale
  245. df['t'] = (df['ds'] - self.start) / self.t_scale
  246. if 'y' in df:
  247. df['y_scaled'] = (df['y'] - df['floor']) / self.y_scale
  248. for name, props in self.extra_regressors.items():
  249. df[name] = pd.to_numeric(df[name])
  250. df[name] = ((df[name] - props['mu']) / props['std'])
  251. if df[name].isnull().any():
  252. raise ValueError('Found NaN in column ' + name)
  253. return df
  254. def initialize_scales(self, initialize_scales, df):
  255. """Initialize model scales.
  256. Sets model scaling factors using df.
  257. Parameters
  258. ----------
  259. initialize_scales: Boolean set the scales or not.
  260. df: pd.DataFrame for setting scales.
  261. """
  262. if not initialize_scales:
  263. return
  264. if self.growth == 'logistic' and 'floor' in df:
  265. self.logistic_floor = True
  266. floor = df['floor']
  267. else:
  268. floor = 0.
  269. self.y_scale = (df['y'] - floor).abs().max()
  270. if self.y_scale == 0:
  271. self.y_scale = 1
  272. self.start = df['ds'].min()
  273. self.t_scale = df['ds'].max() - self.start
  274. for name, props in self.extra_regressors.items():
  275. standardize = props['standardize']
  276. n_vals = len(df[name].unique())
  277. if n_vals < 2:
  278. standardize = False
  279. if standardize == 'auto':
  280. if set(df[name].unique()) == set([1, 0]):
  281. # Don't standardize binary variables.
  282. standardize = False
  283. else:
  284. standardize = True
  285. if standardize:
  286. mu = df[name].mean()
  287. std = df[name].std()
  288. self.extra_regressors[name]['mu'] = mu
  289. self.extra_regressors[name]['std'] = std
  290. def set_changepoints(self):
  291. """Set changepoints
  292. Sets m$changepoints to the dates of changepoints. Either:
  293. 1) The changepoints were passed in explicitly.
  294. A) They are empty.
  295. B) They are not empty, and need validation.
  296. 2) We are generating a grid of them.
  297. 3) The user prefers no changepoints be used.
  298. """
  299. if self.changepoints is not None:
  300. if len(self.changepoints) == 0:
  301. pass
  302. else:
  303. too_low = min(self.changepoints) < self.history['ds'].min()
  304. too_high = max(self.changepoints) > self.history['ds'].max()
  305. if too_low or too_high:
  306. raise ValueError(
  307. 'Changepoints must fall within training data.')
  308. else:
  309. # Place potential changepoints evenly through first
  310. # changepoint_range proportion of the history
  311. hist_size = np.floor(
  312. self.history.shape[0] * self.changepoint_range)
  313. if self.n_changepoints + 1 > hist_size:
  314. self.n_changepoints = hist_size - 1
  315. logger.info(
  316. 'n_changepoints greater than number of observations.'
  317. 'Using {}.'.format(self.n_changepoints)
  318. )
  319. if self.n_changepoints > 0:
  320. cp_indexes = (
  321. np.linspace(0, hist_size - 1, self.n_changepoints + 1)
  322. .round()
  323. .astype(np.int)
  324. )
  325. self.changepoints = (
  326. self.history.iloc[cp_indexes]['ds'].tail(-1)
  327. )
  328. else:
  329. # set empty changepoints
  330. self.changepoints = []
  331. if len(self.changepoints) > 0:
  332. self.changepoints_t = np.sort(np.array(
  333. (self.changepoints - self.start) / self.t_scale))
  334. else:
  335. self.changepoints_t = np.array([0]) # dummy changepoint
  336. @staticmethod
  337. def fourier_series(dates, period, series_order):
  338. """Provides Fourier series components with the specified frequency
  339. and order.
  340. Parameters
  341. ----------
  342. dates: pd.Series containing timestamps.
  343. period: Number of days of the period.
  344. series_order: Number of components.
  345. Returns
  346. -------
  347. Matrix with seasonality features.
  348. """
  349. # convert to days since epoch
  350. t = np.array(
  351. (dates - pd.datetime(1970, 1, 1))
  352. .dt.total_seconds()
  353. .astype(np.float)
  354. ) / (3600 * 24.)
  355. return np.column_stack([
  356. fun((2.0 * (i + 1) * np.pi * t / period))
  357. for i in range(series_order)
  358. for fun in (np.sin, np.cos)
  359. ])
  360. @classmethod
  361. def make_seasonality_features(cls, dates, period, series_order, prefix):
  362. """Data frame with seasonality features.
  363. Parameters
  364. ----------
  365. cls: Prophet class.
  366. dates: pd.Series containing timestamps.
  367. period: Number of days of the period.
  368. series_order: Number of components.
  369. prefix: Column name prefix.
  370. Returns
  371. -------
  372. pd.DataFrame with seasonality features.
  373. """
  374. features = cls.fourier_series(dates, period, series_order)
  375. columns = [
  376. '{}_delim_{}'.format(prefix, i + 1)
  377. for i in range(features.shape[1])
  378. ]
  379. return pd.DataFrame(features, columns=columns)
  380. def make_holiday_features(self, dates):
  381. """Construct a dataframe of holiday features.
  382. Parameters
  383. ----------
  384. dates: pd.Series containing timestamps used for computing seasonality.
  385. Returns
  386. -------
  387. holiday_features: pd.DataFrame with a column for each holiday.
  388. prior_scale_list: List of prior scales for each holiday column.
  389. holiday_names: List of names of holidays
  390. """
  391. # Holds columns of our future matrix.
  392. expanded_holidays = defaultdict(lambda: np.zeros(dates.shape[0]))
  393. prior_scales = {}
  394. # Makes an index so we can perform `get_loc` below.
  395. # Strip to just dates.
  396. row_index = pd.DatetimeIndex(dates.apply(lambda x: x.date()))
  397. for _ix, row in self.holidays.iterrows():
  398. dt = row.ds.date()
  399. try:
  400. lw = int(row.get('lower_window', 0))
  401. uw = int(row.get('upper_window', 0))
  402. except ValueError:
  403. lw = 0
  404. uw = 0
  405. ps = float(row.get('prior_scale', self.holidays_prior_scale))
  406. if np.isnan(ps):
  407. ps = float(self.holidays_prior_scale)
  408. if (
  409. row.holiday in prior_scales and prior_scales[row.holiday] != ps
  410. ):
  411. raise ValueError(
  412. 'Holiday {} does not have consistent prior scale '
  413. 'specification.'.format(row.holiday))
  414. if ps <= 0:
  415. raise ValueError('Prior scale must be > 0')
  416. prior_scales[row.holiday] = ps
  417. for offset in range(lw, uw + 1):
  418. occurrence = dt + timedelta(days=offset)
  419. try:
  420. loc = row_index.get_loc(occurrence)
  421. except KeyError:
  422. loc = None
  423. key = '{}_delim_{}{}'.format(
  424. row.holiday,
  425. '+' if offset >= 0 else '-',
  426. abs(offset)
  427. )
  428. if loc is not None:
  429. expanded_holidays[key][loc] = 1.
  430. else:
  431. # Access key to generate value
  432. expanded_holidays[key]
  433. holiday_features = pd.DataFrame(expanded_holidays)
  434. prior_scale_list = [
  435. prior_scales[h.split('_delim_')[0]]
  436. for h in holiday_features.columns
  437. ]
  438. return holiday_features, prior_scale_list, list(prior_scales.keys())
  439. def add_regressor(
  440. self, name, prior_scale=None, standardize='auto', mode=None
  441. ):
  442. """Add an additional regressor to be used for fitting and predicting.
  443. The dataframe passed to `fit` and `predict` will have a column with the
  444. specified name to be used as a regressor. When standardize='auto', the
  445. regressor will be standardized unless it is binary. The regression
  446. coefficient is given a prior with the specified scale parameter.
  447. Decreasing the prior scale will add additional regularization. If no
  448. prior scale is provided, self.holidays_prior_scale will be used.
  449. Mode can be specified as either 'additive' or 'multiplicative'. If not
  450. specified, self.seasonality_mode will be used. 'additive' means the
  451. effect of the regressor will be added to the trend, 'multiplicative'
  452. means it will multiply the trend.
  453. Parameters
  454. ----------
  455. name: string name of the regressor.
  456. prior_scale: optional float scale for the normal prior. If not
  457. provided, self.holidays_prior_scale will be used.
  458. standardize: optional, specify whether this regressor will be
  459. standardized prior to fitting. Can be 'auto' (standardize if not
  460. binary), True, or False.
  461. mode: optional, 'additive' or 'multiplicative'. Defaults to
  462. self.seasonality_mode.
  463. Returns
  464. -------
  465. The prophet object.
  466. """
  467. if self.history is not None:
  468. raise Exception(
  469. "Regressors must be added prior to model fitting.")
  470. self.validate_column_name(name, check_regressors=False)
  471. if prior_scale is None:
  472. prior_scale = float(self.holidays_prior_scale)
  473. if mode is None:
  474. mode = self.seasonality_mode
  475. if prior_scale <= 0:
  476. raise ValueError('Prior scale must be > 0')
  477. if mode not in ['additive', 'multiplicative']:
  478. raise ValueError("mode must be 'additive' or 'multiplicative'")
  479. self.extra_regressors[name] = {
  480. 'prior_scale': prior_scale,
  481. 'standardize': standardize,
  482. 'mu': 0.,
  483. 'std': 1.,
  484. 'mode': mode,
  485. }
  486. return self
  487. def add_seasonality(
  488. self, name, period, fourier_order, prior_scale=None, mode=None
  489. ):
  490. """Add a seasonal component with specified period, number of Fourier
  491. components, and prior scale.
  492. Increasing the number of Fourier components allows the seasonality to
  493. change more quickly (at risk of overfitting). Default values for yearly
  494. and weekly seasonalities are 10 and 3 respectively.
  495. Increasing prior scale will allow this seasonality component more
  496. flexibility, decreasing will dampen it. If not provided, will use the
  497. seasonality_prior_scale provided on Prophet initialization (defaults
  498. to 10).
  499. Mode can be specified as either 'additive' or 'multiplicative'. If not
  500. specified, self.seasonality_mode will be used (defaults to additive).
  501. Additive means the seasonality will be added to the trend,
  502. multiplicative means it will multiply the trend.
  503. Parameters
  504. ----------
  505. name: string name of the seasonality component.
  506. period: float number of days in one period.
  507. fourier_order: int number of Fourier components to use.
  508. prior_scale: optional float prior scale for this component.
  509. mode: optional 'additive' or 'multiplicative'
  510. Returns
  511. -------
  512. The prophet object.
  513. """
  514. if self.history is not None:
  515. raise Exception(
  516. "Seasonality must be added prior to model fitting.")
  517. if name not in ['daily', 'weekly', 'yearly']:
  518. # Allow overwriting built-in seasonalities
  519. self.validate_column_name(name, check_seasonalities=False)
  520. if prior_scale is None:
  521. ps = self.seasonality_prior_scale
  522. else:
  523. ps = float(prior_scale)
  524. if ps <= 0:
  525. raise ValueError('Prior scale must be > 0')
  526. if mode is None:
  527. mode = self.seasonality_mode
  528. if mode not in ['additive', 'multiplicative']:
  529. raise ValueError("mode must be 'additive' or 'multiplicative'")
  530. self.seasonalities[name] = {
  531. 'period': period,
  532. 'fourier_order': fourier_order,
  533. 'prior_scale': ps,
  534. 'mode': mode,
  535. }
  536. return self
  537. def make_all_seasonality_features(self, df):
  538. """Dataframe with seasonality features.
  539. Includes seasonality features, holiday features, and added regressors.
  540. Parameters
  541. ----------
  542. df: pd.DataFrame with dates for computing seasonality features and any
  543. added regressors.
  544. Returns
  545. -------
  546. pd.DataFrame with regression features.
  547. list of prior scales for each column of the features dataframe.
  548. Dataframe with indicators for which regression components correspond to
  549. which columns.
  550. Dictionary with keys 'additive' and 'multiplicative' listing the
  551. component names for each mode of seasonality.
  552. """
  553. seasonal_features = []
  554. prior_scales = []
  555. modes = {'additive': [], 'multiplicative': []}
  556. # Seasonality features
  557. for name, props in self.seasonalities.items():
  558. features = self.make_seasonality_features(
  559. df['ds'],
  560. props['period'],
  561. props['fourier_order'],
  562. name,
  563. )
  564. seasonal_features.append(features)
  565. prior_scales.extend(
  566. [props['prior_scale']] * features.shape[1])
  567. modes[props['mode']].append(name)
  568. # Holiday features
  569. if self.holidays is not None:
  570. features, holiday_priors, holiday_names = (
  571. self.make_holiday_features(df['ds'])
  572. )
  573. seasonal_features.append(features)
  574. prior_scales.extend(holiday_priors)
  575. modes[self.seasonality_mode].extend(holiday_names)
  576. # Additional regressors
  577. for name, props in self.extra_regressors.items():
  578. seasonal_features.append(pd.DataFrame(df[name]))
  579. prior_scales.append(props['prior_scale'])
  580. modes[props['mode']].append(name)
  581. # Dummy to prevent empty X
  582. if len(seasonal_features) == 0:
  583. seasonal_features.append(
  584. pd.DataFrame({'zeros': np.zeros(df.shape[0])}))
  585. prior_scales.append(1.)
  586. seasonal_features = pd.concat(seasonal_features, axis=1)
  587. component_cols, modes = self.regressor_column_matrix(
  588. seasonal_features, modes
  589. )
  590. return seasonal_features, prior_scales, component_cols, modes
  591. def regressor_column_matrix(self, seasonal_features, modes):
  592. """Dataframe indicating which columns of the feature matrix correspond
  593. to which seasonality/regressor components.
  594. Includes combination components, like 'additive_terms'. These
  595. combination components will be added to the 'modes' input.
  596. Parameters
  597. ----------
  598. seasonal_features: Constructed seasonal features dataframe
  599. modes: Dictionary with keys 'additive' and 'multiplicative' listing the
  600. component names for each mode of seasonality.
  601. Returns
  602. -------
  603. component_cols: A binary indicator dataframe with columns seasonal
  604. components and rows columns in seasonal_features. Entry is 1 if
  605. that columns is used in that component.
  606. modes: Updated input with combination components.
  607. """
  608. components = pd.DataFrame({
  609. 'col': np.arange(seasonal_features.shape[1]),
  610. 'component': [
  611. x.split('_delim_')[0] for x in seasonal_features.columns
  612. ],
  613. })
  614. # Add total for holidays
  615. if self.holidays is not None:
  616. components = self.add_group_component(
  617. components, 'holidays', self.holidays['holiday'].unique())
  618. # Add totals additive and multiplicative components, and regressors
  619. for mode in ['additive', 'multiplicative']:
  620. components = self.add_group_component(
  621. components, mode + '_terms', modes[mode]
  622. )
  623. regressors_by_mode = [
  624. r for r, props in self.extra_regressors.items()
  625. if props['mode'] == mode
  626. ]
  627. components = self.add_group_component(
  628. components, 'extra_regressors_' + mode, regressors_by_mode)
  629. # Add combination components to modes
  630. modes[mode].append(mode + '_terms')
  631. modes[mode].append('extra_regressors_' + mode)
  632. # After all of the additive/multiplicative groups have been added,
  633. modes[self.seasonality_mode].append('holidays')
  634. # Convert to a binary matrix
  635. component_cols = pd.crosstab(
  636. components['col'], components['component'],
  637. ).sort_index(level='col')
  638. # Add columns for additive and multiplicative terms, if missing
  639. for name in ['additive_terms', 'multiplicative_terms']:
  640. if name not in component_cols:
  641. component_cols[name] = 0
  642. # Remove the placeholder
  643. component_cols.drop('zeros', axis=1, inplace=True, errors='ignore')
  644. # Validation
  645. if (
  646. max(component_cols['additive_terms']
  647. + component_cols['multiplicative_terms']) > 1
  648. ):
  649. raise Exception('A bug occurred in seasonal components.')
  650. # Compare to the training, if set.
  651. if self.train_component_cols is not None:
  652. component_cols = component_cols[self.train_component_cols.columns]
  653. if not component_cols.equals(self.train_component_cols):
  654. raise Exception('A bug occurred in constructing regressors.')
  655. return component_cols, modes
  656. def add_group_component(self, components, name, group):
  657. """Adds a component with given name that contains all of the components
  658. in group.
  659. Parameters
  660. ----------
  661. components: Dataframe with components.
  662. name: Name of new group component.
  663. group: List of components that form the group.
  664. Returns
  665. -------
  666. Dataframe with components.
  667. """
  668. new_comp = components[components['component'].isin(set(group))].copy()
  669. group_cols = new_comp['col'].unique()
  670. if len(group_cols) > 0:
  671. new_comp = pd.DataFrame({'col': group_cols, 'component': name})
  672. components = components.append(new_comp)
  673. return components
  674. def parse_seasonality_args(self, name, arg, auto_disable, default_order):
  675. """Get number of fourier components for built-in seasonalities.
  676. Parameters
  677. ----------
  678. name: string name of the seasonality component.
  679. arg: 'auto', True, False, or number of fourier components as provided.
  680. auto_disable: bool if seasonality should be disabled when 'auto'.
  681. default_order: int default fourier order
  682. Returns
  683. -------
  684. Number of fourier components, or 0 for disabled.
  685. """
  686. if arg == 'auto':
  687. fourier_order = 0
  688. if name in self.seasonalities:
  689. logger.info(
  690. 'Found custom seasonality named "{name}", '
  691. 'disabling built-in {name} seasonality.'.format(name=name)
  692. )
  693. elif auto_disable:
  694. logger.info(
  695. 'Disabling {name} seasonality. Run prophet with '
  696. '{name}_seasonality=True to override this.'.format(
  697. name=name)
  698. )
  699. else:
  700. fourier_order = default_order
  701. elif arg is True:
  702. fourier_order = default_order
  703. elif arg is False:
  704. fourier_order = 0
  705. else:
  706. fourier_order = int(arg)
  707. return fourier_order
  708. def set_auto_seasonalities(self):
  709. """Set seasonalities that were left on auto.
  710. Turns on yearly seasonality if there is >=2 years of history.
  711. Turns on weekly seasonality if there is >=2 weeks of history, and the
  712. spacing between dates in the history is <7 days.
  713. Turns on daily seasonality if there is >=2 days of history, and the
  714. spacing between dates in the history is <1 day.
  715. """
  716. first = self.history['ds'].min()
  717. last = self.history['ds'].max()
  718. dt = self.history['ds'].diff()
  719. min_dt = dt.iloc[dt.nonzero()[0]].min()
  720. # Yearly seasonality
  721. yearly_disable = last - first < pd.Timedelta(days=730)
  722. fourier_order = self.parse_seasonality_args(
  723. 'yearly', self.yearly_seasonality, yearly_disable, 10)
  724. if fourier_order > 0:
  725. self.seasonalities['yearly'] = {
  726. 'period': 365.25,
  727. 'fourier_order': fourier_order,
  728. 'prior_scale': self.seasonality_prior_scale,
  729. 'mode': self.seasonality_mode,
  730. }
  731. # Weekly seasonality
  732. weekly_disable = ((last - first < pd.Timedelta(weeks=2)) or
  733. (min_dt >= pd.Timedelta(weeks=1)))
  734. fourier_order = self.parse_seasonality_args(
  735. 'weekly', self.weekly_seasonality, weekly_disable, 3)
  736. if fourier_order > 0:
  737. self.seasonalities['weekly'] = {
  738. 'period': 7,
  739. 'fourier_order': fourier_order,
  740. 'prior_scale': self.seasonality_prior_scale,
  741. 'mode': self.seasonality_mode,
  742. }
  743. # Daily seasonality
  744. daily_disable = ((last - first < pd.Timedelta(days=2)) or
  745. (min_dt >= pd.Timedelta(days=1)))
  746. fourier_order = self.parse_seasonality_args(
  747. 'daily', self.daily_seasonality, daily_disable, 4)
  748. if fourier_order > 0:
  749. self.seasonalities['daily'] = {
  750. 'period': 1,
  751. 'fourier_order': fourier_order,
  752. 'prior_scale': self.seasonality_prior_scale,
  753. 'mode': self.seasonality_mode,
  754. }
  755. @staticmethod
  756. def linear_growth_init(df):
  757. """Initialize linear growth.
  758. Provides a strong initialization for linear growth by calculating the
  759. growth and offset parameters that pass the function through the first
  760. and last points in the time series.
  761. Parameters
  762. ----------
  763. df: pd.DataFrame with columns ds (date), y_scaled (scaled time series),
  764. and t (scaled time).
  765. Returns
  766. -------
  767. A tuple (k, m) with the rate (k) and offset (m) of the linear growth
  768. function.
  769. """
  770. i0, i1 = df['ds'].idxmin(), df['ds'].idxmax()
  771. T = df['t'].iloc[i1] - df['t'].iloc[i0]
  772. k = (df['y_scaled'].iloc[i1] - df['y_scaled'].iloc[i0]) / T
  773. m = df['y_scaled'].iloc[i0] - k * df['t'].iloc[i0]
  774. return (k, m)
  775. @staticmethod
  776. def logistic_growth_init(df):
  777. """Initialize logistic growth.
  778. Provides a strong initialization for logistic growth by calculating the
  779. growth and offset parameters that pass the function through the first
  780. and last points in the time series.
  781. Parameters
  782. ----------
  783. df: pd.DataFrame with columns ds (date), cap_scaled (scaled capacity),
  784. y_scaled (scaled time series), and t (scaled time).
  785. Returns
  786. -------
  787. A tuple (k, m) with the rate (k) and offset (m) of the logistic growth
  788. function.
  789. """
  790. i0, i1 = df['ds'].idxmin(), df['ds'].idxmax()
  791. T = df['t'].iloc[i1] - df['t'].iloc[i0]
  792. # Force valid values, in case y > cap or y < 0
  793. C0 = df['cap_scaled'].iloc[i0]
  794. C1 = df['cap_scaled'].iloc[i1]
  795. y0 = max(0.01 * C0, min(0.99 * C0, df['y_scaled'].iloc[i0]))
  796. y1 = max(0.01 * C1, min(0.99 * C1, df['y_scaled'].iloc[i1]))
  797. r0 = C0 / y0
  798. r1 = C1 / y1
  799. if abs(r0 - r1) <= 0.01:
  800. r0 = 1.05 * r0
  801. L0 = np.log(r0 - 1)
  802. L1 = np.log(r1 - 1)
  803. # Initialize the offset
  804. m = L0 * T / (L0 - L1)
  805. # And the rate
  806. k = (L0 - L1) / T
  807. return (k, m)
  808. def fit(self, df, **kwargs):
  809. """Fit the Prophet model.
  810. This sets self.params to contain the fitted model parameters. It is a
  811. dictionary parameter names as keys and the following items:
  812. k (Mx1 array): M posterior samples of the initial slope.
  813. m (Mx1 array): The initial intercept.
  814. delta (MxN array): The slope change at each of N changepoints.
  815. beta (MxK matrix): Coefficients for K seasonality features.
  816. sigma_obs (Mx1 array): Noise level.
  817. Note that M=1 if MAP estimation.
  818. Parameters
  819. ----------
  820. df: pd.DataFrame containing the history. Must have columns ds (date
  821. type) and y, the time series. If self.growth is 'logistic', then
  822. df must also have a column cap that specifies the capacity at
  823. each ds.
  824. kwargs: Additional arguments passed to the optimizing or sampling
  825. functions in Stan.
  826. Returns
  827. -------
  828. The fitted Prophet object.
  829. """
  830. if self.history is not None:
  831. raise Exception('Prophet object can only be fit once. '
  832. 'Instantiate a new object.')
  833. if ('ds' not in df) or ('y' not in df):
  834. raise ValueError(
  835. "Dataframe must have columns 'ds' and 'y' with the dates and "
  836. "values respectively."
  837. )
  838. history = df[df['y'].notnull()].copy()
  839. if history.shape[0] < 2:
  840. raise ValueError('Dataframe has less than 2 non-NaN rows.')
  841. self.history_dates = pd.to_datetime(df['ds']).sort_values()
  842. history = self.setup_dataframe(history, initialize_scales=True)
  843. self.history = history
  844. self.set_auto_seasonalities()
  845. seasonal_features, prior_scales, component_cols, modes = (
  846. self.make_all_seasonality_features(history))
  847. self.train_component_cols = component_cols
  848. self.component_modes = modes
  849. self.set_changepoints()
  850. dat = {
  851. 'T': history.shape[0],
  852. 'K': seasonal_features.shape[1],
  853. 'S': len(self.changepoints_t),
  854. 'y': history['y_scaled'],
  855. 't': history['t'],
  856. 't_change': self.changepoints_t,
  857. 'X': seasonal_features,
  858. 'sigmas': prior_scales,
  859. 'tau': self.changepoint_prior_scale,
  860. 'trend_indicator': int(self.growth == 'logistic'),
  861. 's_a': component_cols['additive_terms'],
  862. 's_m': component_cols['multiplicative_terms'],
  863. }
  864. if self.growth == 'linear':
  865. dat['cap'] = np.zeros(self.history.shape[0])
  866. kinit = self.linear_growth_init(history)
  867. else:
  868. dat['cap'] = history['cap_scaled']
  869. kinit = self.logistic_growth_init(history)
  870. model = prophet_stan_model
  871. def stan_init():
  872. return {
  873. 'k': kinit[0],
  874. 'm': kinit[1],
  875. 'delta': np.zeros(len(self.changepoints_t)),
  876. 'beta': np.zeros(seasonal_features.shape[1]),
  877. 'sigma_obs': 1,
  878. }
  879. if (
  880. (history['y'].min() == history['y'].max())
  881. and self.growth == 'linear'
  882. ):
  883. # Nothing to fit.
  884. self.params = stan_init()
  885. self.params['sigma_obs'] = 1e-9
  886. for par in self.params:
  887. self.params[par] = np.array([self.params[par]])
  888. elif self.mcmc_samples > 0:
  889. stan_fit = model.sampling(
  890. dat,
  891. init=stan_init,
  892. iter=self.mcmc_samples,
  893. **kwargs
  894. )
  895. for par in stan_fit.model_pars:
  896. self.params[par] = stan_fit[par]
  897. else:
  898. try:
  899. params = model.optimizing(
  900. dat, init=stan_init, iter=1e4, **kwargs)
  901. except RuntimeError:
  902. params = model.optimizing(
  903. dat, init=stan_init, iter=1e4, algorithm='Newton',
  904. **kwargs
  905. )
  906. for par in params:
  907. self.params[par] = params[par].reshape((1, -1))
  908. # If no changepoints were requested, replace delta with 0s
  909. if len(self.changepoints) == 0:
  910. # Fold delta into the base rate k
  911. self.params['k'] = self.params['k'] + self.params['delta']
  912. self.params['delta'] = np.zeros(self.params['delta'].shape)
  913. return self
  914. def predict(self, df=None):
  915. """Predict using the prophet model.
  916. Parameters
  917. ----------
  918. df: pd.DataFrame with dates for predictions (column ds), and capacity
  919. (column cap) if logistic growth. If not provided, predictions are
  920. made on the history.
  921. Returns
  922. -------
  923. A pd.DataFrame with the forecast components.
  924. """
  925. if df is None:
  926. df = self.history.copy()
  927. else:
  928. if df.shape[0] == 0:
  929. raise ValueError('Dataframe has no rows.')
  930. df = self.setup_dataframe(df.copy())
  931. df['trend'] = self.predict_trend(df)
  932. seasonal_components = self.predict_seasonal_components(df)
  933. intervals = self.predict_uncertainty(df)
  934. # Drop columns except ds, cap, floor, and trend
  935. cols = ['ds', 'trend']
  936. if 'cap' in df:
  937. cols.append('cap')
  938. if self.logistic_floor:
  939. cols.append('floor')
  940. # Add in forecast components
  941. df2 = pd.concat((df[cols], intervals, seasonal_components), axis=1)
  942. df2['yhat'] = (
  943. df2['trend'] * (1 + df2['multiplicative_terms'])
  944. + df2['additive_terms']
  945. )
  946. return df2
  947. @staticmethod
  948. def piecewise_linear(t, deltas, k, m, changepoint_ts):
  949. """Evaluate the piecewise linear function.
  950. Parameters
  951. ----------
  952. t: np.array of times on which the function is evaluated.
  953. deltas: np.array of rate changes at each changepoint.
  954. k: Float initial rate.
  955. m: Float initial offset.
  956. changepoint_ts: np.array of changepoint times.
  957. Returns
  958. -------
  959. Vector y(t).
  960. """
  961. # Intercept changes
  962. gammas = -changepoint_ts * deltas
  963. # Get cumulative slope and intercept at each t
  964. k_t = k * np.ones_like(t)
  965. m_t = m * np.ones_like(t)
  966. for s, t_s in enumerate(changepoint_ts):
  967. indx = t >= t_s
  968. k_t[indx] += deltas[s]
  969. m_t[indx] += gammas[s]
  970. return k_t * t + m_t
  971. @staticmethod
  972. def piecewise_logistic(t, cap, deltas, k, m, changepoint_ts):
  973. """Evaluate the piecewise logistic function.
  974. Parameters
  975. ----------
  976. t: np.array of times on which the function is evaluated.
  977. cap: np.array of capacities at each t.
  978. deltas: np.array of rate changes at each changepoint.
  979. k: Float initial rate.
  980. m: Float initial offset.
  981. changepoint_ts: np.array of changepoint times.
  982. Returns
  983. -------
  984. Vector y(t).
  985. """
  986. # Compute offset changes
  987. k_cum = np.concatenate((np.atleast_1d(k), np.cumsum(deltas) + k))
  988. gammas = np.zeros(len(changepoint_ts))
  989. for i, t_s in enumerate(changepoint_ts):
  990. gammas[i] = (
  991. (t_s - m - np.sum(gammas))
  992. * (1 - k_cum[i] / k_cum[i + 1]) # noqa W503
  993. )
  994. # Get cumulative rate and offset at each t
  995. k_t = k * np.ones_like(t)
  996. m_t = m * np.ones_like(t)
  997. for s, t_s in enumerate(changepoint_ts):
  998. indx = t >= t_s
  999. k_t[indx] += deltas[s]
  1000. m_t[indx] += gammas[s]
  1001. return cap / (1 + np.exp(-k_t * (t - m_t)))
  1002. def predict_trend(self, df):
  1003. """Predict trend using the prophet model.
  1004. Parameters
  1005. ----------
  1006. df: Prediction dataframe.
  1007. Returns
  1008. -------
  1009. Vector with trend on prediction dates.
  1010. """
  1011. k = np.nanmean(self.params['k'])
  1012. m = np.nanmean(self.params['m'])
  1013. deltas = np.nanmean(self.params['delta'], axis=0)
  1014. t = np.array(df['t'])
  1015. if self.growth == 'linear':
  1016. trend = self.piecewise_linear(t, deltas, k, m, self.changepoints_t)
  1017. else:
  1018. cap = df['cap_scaled']
  1019. trend = self.piecewise_logistic(
  1020. t, cap, deltas, k, m, self.changepoints_t)
  1021. return trend * self.y_scale + df['floor']
  1022. def predict_seasonal_components(self, df):
  1023. """Predict seasonality components, holidays, and added regressors.
  1024. Parameters
  1025. ----------
  1026. df: Prediction dataframe.
  1027. Returns
  1028. -------
  1029. Dataframe with seasonal components.
  1030. """
  1031. seasonal_features, _, component_cols, _ = (
  1032. self.make_all_seasonality_features(df)
  1033. )
  1034. lower_p = 100 * (1.0 - self.interval_width) / 2
  1035. upper_p = 100 * (1.0 + self.interval_width) / 2
  1036. X = seasonal_features.values
  1037. data = {}
  1038. for component in component_cols.columns:
  1039. beta_c = self.params['beta'] * component_cols[component].values
  1040. comp = np.matmul(X, beta_c.transpose())
  1041. if component in self.component_modes['additive']:
  1042. comp *= self.y_scale
  1043. data[component] = np.nanmean(comp, axis=1)
  1044. data[component + '_lower'] = np.nanpercentile(
  1045. comp, lower_p, axis=1,
  1046. )
  1047. data[component + '_upper'] = np.nanpercentile(
  1048. comp, upper_p, axis=1,
  1049. )
  1050. return pd.DataFrame(data)
  1051. def sample_posterior_predictive(self, df):
  1052. """Prophet posterior predictive samples.
  1053. Parameters
  1054. ----------
  1055. df: Prediction dataframe.
  1056. Returns
  1057. -------
  1058. Dictionary with posterior predictive samples for the forecast yhat and
  1059. for the trend component.
  1060. """
  1061. n_iterations = self.params['k'].shape[0]
  1062. samp_per_iter = max(1, int(np.ceil(
  1063. self.uncertainty_samples / float(n_iterations)
  1064. )))
  1065. # Generate seasonality features once so we can re-use them.
  1066. seasonal_features, _, component_cols, _ = (
  1067. self.make_all_seasonality_features(df)
  1068. )
  1069. sim_values = {'yhat': [], 'trend': []}
  1070. for i in range(n_iterations):
  1071. for _j in range(samp_per_iter):
  1072. sim = self.sample_model(
  1073. df=df,
  1074. seasonal_features=seasonal_features,
  1075. iteration=i,
  1076. s_a=component_cols['additive_terms'],
  1077. s_m=component_cols['multiplicative_terms'],
  1078. )
  1079. for key in sim_values:
  1080. sim_values[key].append(sim[key])
  1081. for k, v in sim_values.items():
  1082. sim_values[k] = np.column_stack(v)
  1083. return sim_values
  1084. def predictive_samples(self, df):
  1085. """Sample from the posterior predictive distribution.
  1086. Parameters
  1087. ----------
  1088. df: Dataframe with dates for predictions (column ds), and capacity
  1089. (column cap) if logistic growth.
  1090. Returns
  1091. -------
  1092. Dictionary with keys "trend" and "yhat" containing
  1093. posterior predictive samples for that component.
  1094. """
  1095. df = self.setup_dataframe(df.copy())
  1096. sim_values = self.sample_posterior_predictive(df)
  1097. return sim_values
  1098. def predict_uncertainty(self, df):
  1099. """Prediction intervals for yhat and trend.
  1100. Parameters
  1101. ----------
  1102. df: Prediction dataframe.
  1103. Returns
  1104. -------
  1105. Dataframe with uncertainty intervals.
  1106. """
  1107. sim_values = self.sample_posterior_predictive(df)
  1108. lower_p = 100 * (1.0 - self.interval_width) / 2
  1109. upper_p = 100 * (1.0 + self.interval_width) / 2
  1110. series = {}
  1111. for key in ['yhat', 'trend']:
  1112. series['{}_lower'.format(key)] = np.nanpercentile(
  1113. sim_values[key], lower_p, axis=1)
  1114. series['{}_upper'.format(key)] = np.nanpercentile(
  1115. sim_values[key], upper_p, axis=1)
  1116. return pd.DataFrame(series)
  1117. def sample_model(self, df, seasonal_features, iteration, s_a, s_m):
  1118. """Simulate observations from the extrapolated generative model.
  1119. Parameters
  1120. ----------
  1121. df: Prediction dataframe.
  1122. seasonal_features: pd.DataFrame of seasonal features.
  1123. iteration: Int sampling iteration to use parameters from.
  1124. s_a: Indicator vector for additive components
  1125. s_m: Indicator vector for multiplicative components
  1126. Returns
  1127. -------
  1128. Dataframe with trend and yhat, each like df['t'].
  1129. """
  1130. trend = self.sample_predictive_trend(df, iteration)
  1131. beta = self.params['beta'][iteration]
  1132. Xb_a = np.matmul(seasonal_features.values, beta * s_a) * self.y_scale
  1133. Xb_m = np.matmul(seasonal_features.values, beta * s_m)
  1134. sigma = self.params['sigma_obs'][iteration]
  1135. noise = np.random.normal(0, sigma, df.shape[0]) * self.y_scale
  1136. return pd.DataFrame({
  1137. 'yhat': trend * (1 + Xb_m) + Xb_a + noise,
  1138. 'trend': trend
  1139. })
  1140. def sample_predictive_trend(self, df, iteration):
  1141. """Simulate the trend using the extrapolated generative model.
  1142. Parameters
  1143. ----------
  1144. df: Prediction dataframe.
  1145. iteration: Int sampling iteration to use parameters from.
  1146. Returns
  1147. -------
  1148. np.array of simulated trend over df['t'].
  1149. """
  1150. k = self.params['k'][iteration]
  1151. m = self.params['m'][iteration]
  1152. deltas = self.params['delta'][iteration]
  1153. t = np.array(df['t'])
  1154. T = t.max()
  1155. # New changepoints from a Poisson process with rate S on [1, T]
  1156. if T > 1:
  1157. S = len(self.changepoints_t)
  1158. n_changes = np.random.poisson(S * (T - 1))
  1159. else:
  1160. n_changes = 0
  1161. if n_changes > 0:
  1162. changepoint_ts_new = 1 + np.random.rand(n_changes) * (T - 1)
  1163. changepoint_ts_new.sort()
  1164. else:
  1165. changepoint_ts_new = []
  1166. # Get the empirical scale of the deltas, plus epsilon to avoid NaNs.
  1167. lambda_ = np.mean(np.abs(deltas)) + 1e-8
  1168. # Sample deltas
  1169. deltas_new = np.random.laplace(0, lambda_, n_changes)
  1170. # Prepend the times and deltas from the history
  1171. changepoint_ts = np.concatenate((self.changepoints_t,
  1172. changepoint_ts_new))
  1173. deltas = np.concatenate((deltas, deltas_new))
  1174. if self.growth == 'linear':
  1175. trend = self.piecewise_linear(t, deltas, k, m, changepoint_ts)
  1176. else:
  1177. cap = df['cap_scaled']
  1178. trend = self.piecewise_logistic(t, cap, deltas, k, m,
  1179. changepoint_ts)
  1180. return trend * self.y_scale + df['floor']
  1181. def make_future_dataframe(self, periods, freq='D', include_history=True):
  1182. """Simulate the trend using the extrapolated generative model.
  1183. Parameters
  1184. ----------
  1185. periods: Int number of periods to forecast forward.
  1186. freq: Any valid frequency for pd.date_range, such as 'D' or 'M'.
  1187. include_history: Boolean to include the historical dates in the data
  1188. frame for predictions.
  1189. Returns
  1190. -------
  1191. pd.Dataframe that extends forward from the end of self.history for the
  1192. requested number of periods.
  1193. """
  1194. if self.history_dates is None:
  1195. raise Exception('Model must be fit before this can be used.')
  1196. last_date = self.history_dates.max()
  1197. dates = pd.date_range(
  1198. start=last_date,
  1199. periods=periods + 1, # An extra in case we include start
  1200. freq=freq)
  1201. dates = dates[dates > last_date] # Drop start if equals last_date
  1202. dates = dates[:periods] # Return correct number of periods
  1203. if include_history:
  1204. dates = np.concatenate((np.array(self.history_dates), dates))
  1205. return pd.DataFrame({'ds': dates})
  1206. def plot(self, fcst, ax=None, uncertainty=True, plot_cap=True, xlabel='ds',
  1207. ylabel='y'):
  1208. """Plot the Prophet forecast.
  1209. Parameters
  1210. ----------
  1211. fcst: pd.DataFrame output of self.predict.
  1212. ax: Optional matplotlib axes on which to plot.
  1213. uncertainty: Optional boolean to plot uncertainty intervals.
  1214. plot_cap: Optional boolean indicating if the capacity should be shown
  1215. in the figure, if available.
  1216. xlabel: Optional label name on X-axis
  1217. ylabel: Optional label name on Y-axis
  1218. Returns
  1219. -------
  1220. A matplotlib figure.
  1221. """
  1222. return plot(
  1223. m=self, fcst=fcst, ax=ax, uncertainty=uncertainty,
  1224. plot_cap=plot_cap, xlabel=xlabel, ylabel=ylabel,
  1225. )
  1226. def plot_components(self, fcst, uncertainty=True, plot_cap=True,
  1227. weekly_start=0, yearly_start=0):
  1228. """Plot the Prophet forecast components.
  1229. Will plot whichever are available of: trend, holidays, weekly
  1230. seasonality, and yearly seasonality.
  1231. Parameters
  1232. ----------
  1233. fcst: pd.DataFrame output of self.predict.
  1234. uncertainty: Optional boolean to plot uncertainty intervals.
  1235. plot_cap: Optional boolean indicating if the capacity should be shown
  1236. in the figure, if available.
  1237. weekly_start: Optional int specifying the start day of the weekly
  1238. seasonality plot. 0 (default) starts the week on Sunday. 1 shifts
  1239. by 1 day to Monday, and so on.
  1240. yearly_start: Optional int specifying the start day of the yearly
  1241. seasonality plot. 0 (default) starts the year on Jan 1. 1 shifts
  1242. by 1 day to Jan 2, and so on.
  1243. Returns
  1244. -------
  1245. A matplotlib figure.
  1246. """
  1247. return plot_components(
  1248. m=self, fcst=fcst, uncertainty=uncertainty, plot_cap=plot_cap,
  1249. weekly_start=weekly_start, yearly_start=yearly_start,
  1250. )
  1251. def plot_forecast_component(
  1252. self, fcst, name, ax=None, uncertainty=True, plot_cap=False):
  1253. warnings.warn(
  1254. 'This method will be removed in the next version. '
  1255. 'Please use fbprophet.plot.plot_forecast_component. ',
  1256. DeprecationWarning,
  1257. )
  1258. return plot_forecast_component(
  1259. self, fcst=fcst, name=name, ax=ax, uncertainty=uncertainty,
  1260. plot_cap=plot_cap,
  1261. )
  1262. def seasonality_plot_df(self, ds):
  1263. warnings.warn(
  1264. 'This method will be removed in the next version. '
  1265. 'Please use fbprophet.plot.seasonality_plot_df. ',
  1266. DeprecationWarning,
  1267. )
  1268. return seasonality_plot_df(self, ds=ds)
  1269. def plot_weekly(self, ax=None, uncertainty=True, weekly_start=0):
  1270. warnings.warn(
  1271. 'This method will be removed in the next version. '
  1272. 'Please use fbprophet.plot.plot_weekly. ',
  1273. DeprecationWarning,
  1274. )
  1275. return plot_weekly(
  1276. self, ax=ax, uncertainty=uncertainty, weekly_start=weekly_start,
  1277. )
  1278. def plot_yearly(self, ax=None, uncertainty=True, yearly_start=0):
  1279. warnings.warn(
  1280. 'This method will be removed in the next version. '
  1281. 'Please use fbprophet.plot.plot_yearly. ',
  1282. DeprecationWarning,
  1283. )
  1284. return plot_yearly(
  1285. self, ax=ax, uncertainty=uncertainty, yearly_start=yearly_start,
  1286. )
  1287. def plot_seasonality(self, name, ax=None, uncertainty=True):
  1288. warnings.warn(
  1289. 'This method will be removed in the next version. '
  1290. 'Please use fbprophet.plot.plot_seasonality. ',
  1291. DeprecationWarning,
  1292. )
  1293. return plot_seasonality(
  1294. self, name=name, ax=ax, uncertainty=uncertainty,
  1295. )
  1296. def copy(self, cutoff=None):
  1297. warnings.warn(
  1298. 'This method will be removed in the next version. '
  1299. 'Please use fbprophet.diagnostics.prophet_copy. ',
  1300. DeprecationWarning,
  1301. )
  1302. return prophet_copy(m=self, cutoff=cutoff)