forecaster.py 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480
  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. # fb-block 1 start
  18. from fbprophet.models import prophet_stan_model
  19. from fbprophet.plot import (
  20. plot,
  21. plot_components,
  22. plot_forecast_component,
  23. seasonality_plot_df,
  24. plot_weekly,
  25. plot_yearly,
  26. plot_seasonality,
  27. )
  28. from fbprophet.diagnostics import prophet_copy
  29. # fb-block 1 end
  30. logging.basicConfig()
  31. logger = logging.getLogger(__name__)
  32. warnings.filterwarnings("default", category=DeprecationWarning)
  33. try:
  34. import pystan # noqa F401
  35. except ImportError:
  36. logger.error('You cannot run prophet without pystan installed')
  37. raise
  38. # fb-block 2
  39. class Prophet(object):
  40. """Prophet forecaster.
  41. Parameters
  42. ----------
  43. growth: String 'linear' or 'logistic' to specify a linear or logistic
  44. trend.
  45. changepoints: List of dates at which to include potential changepoints. If
  46. not specified, potential changepoints are selected automatically.
  47. n_changepoints: Number of potential changepoints to include. Not used
  48. if input `changepoints` is supplied. If `changepoints` is not supplied,
  49. then n_changepoints potential changepoints are selected uniformly from
  50. the first `changepoint_range` proportion of the history.
  51. changepoint_range: Proportion of history in which trend changepoints will
  52. be estimated. Defaults to 0.8 for the first 80%. Not used if
  53. `changepoints` is specified.
  54. Not used if input `changepoints` is supplied.
  55. yearly_seasonality: Fit yearly seasonality.
  56. Can be 'auto', True, False, or a number of Fourier terms to generate.
  57. weekly_seasonality: Fit weekly seasonality.
  58. Can be 'auto', True, False, or a number of Fourier terms to generate.
  59. daily_seasonality: Fit daily seasonality.
  60. Can be 'auto', True, False, or a number of Fourier terms to generate.
  61. holidays: pd.DataFrame with columns holiday (string) and ds (date type)
  62. and optionally columns lower_window and upper_window which specify a
  63. range of days around the date to be included as holidays.
  64. lower_window=-2 will include 2 days prior to the date as holidays. Also
  65. optionally can have a column prior_scale specifying the prior scale for
  66. that holiday.
  67. seasonality_mode: 'additive' (default) or 'multiplicative'.
  68. seasonality_prior_scale: Parameter modulating the strength of the
  69. seasonality model. Larger values allow the model to fit larger seasonal
  70. fluctuations, smaller values dampen the seasonality. Can be specified
  71. for individual seasonalities using add_seasonality.
  72. holidays_prior_scale: Parameter modulating the strength of the holiday
  73. components model, unless overridden in the holidays input.
  74. changepoint_prior_scale: Parameter modulating the flexibility of the
  75. automatic changepoint selection. Large values will allow many
  76. changepoints, small values will allow few changepoints.
  77. mcmc_samples: Integer, if greater than 0, will do full Bayesian inference
  78. with the specified number of MCMC samples. If 0, will do MAP
  79. estimation.
  80. interval_width: Float, width of the uncertainty intervals provided
  81. for the forecast. If mcmc_samples=0, this will be only the uncertainty
  82. in the trend using the MAP estimate of the extrapolated generative
  83. model. If mcmc.samples>0, this will be integrated over all model
  84. parameters, which will include uncertainty in seasonality.
  85. uncertainty_samples: Number of simulated draws used to estimate
  86. uncertainty intervals.
  87. """
  88. def __init__(
  89. self,
  90. growth='linear',
  91. changepoints=None,
  92. n_changepoints=25,
  93. changepoint_range=0.8,
  94. yearly_seasonality='auto',
  95. weekly_seasonality='auto',
  96. daily_seasonality='auto',
  97. holidays=None,
  98. seasonality_mode='additive',
  99. seasonality_prior_scale=10.0,
  100. holidays_prior_scale=10.0,
  101. changepoint_prior_scale=0.05,
  102. mcmc_samples=0,
  103. interval_width=0.80,
  104. uncertainty_samples=1000,
  105. ):
  106. self.growth = growth
  107. self.changepoints = pd.to_datetime(changepoints)
  108. if self.changepoints is not None:
  109. self.n_changepoints = len(self.changepoints)
  110. self.specified_changepoints = True
  111. else:
  112. self.n_changepoints = n_changepoints
  113. self.specified_changepoints = False
  114. self.changepoint_range = changepoint_range
  115. self.yearly_seasonality = yearly_seasonality
  116. self.weekly_seasonality = weekly_seasonality
  117. self.daily_seasonality = daily_seasonality
  118. if holidays is not None:
  119. if not (
  120. isinstance(holidays, pd.DataFrame)
  121. and 'ds' in holidays # noqa W503
  122. and 'holiday' in holidays # noqa W503
  123. ):
  124. raise ValueError("holidays must be a DataFrame with 'ds' and "
  125. "'holiday' columns.")
  126. holidays['ds'] = pd.to_datetime(holidays['ds'])
  127. self.holidays = holidays
  128. self.seasonality_mode = seasonality_mode
  129. self.seasonality_prior_scale = float(seasonality_prior_scale)
  130. self.changepoint_prior_scale = float(changepoint_prior_scale)
  131. self.holidays_prior_scale = float(holidays_prior_scale)
  132. self.mcmc_samples = mcmc_samples
  133. self.interval_width = interval_width
  134. self.uncertainty_samples = uncertainty_samples
  135. # Set during fitting
  136. self.start = None
  137. self.y_scale = None
  138. self.logistic_floor = False
  139. self.t_scale = None
  140. self.changepoints_t = None
  141. self.seasonalities = {}
  142. self.extra_regressors = {}
  143. self.stan_fit = None
  144. self.params = {}
  145. self.history = None
  146. self.history_dates = None
  147. self.train_component_cols = None
  148. self.component_modes = None
  149. self.validate_inputs()
  150. def validate_inputs(self):
  151. """Validates the inputs to Prophet."""
  152. if self.growth not in ('linear', 'logistic'):
  153. raise ValueError(
  154. "Parameter 'growth' should be 'linear' or 'logistic'.")
  155. if ((self.changepoint_range < 0) or (self.changepoint_range > 1)):
  156. raise ValueError("Parameter 'changepoint_range' must be in [0, 1]")
  157. if self.holidays is not None:
  158. has_lower = 'lower_window' in self.holidays
  159. has_upper = 'upper_window' in self.holidays
  160. if has_lower + has_upper == 1:
  161. raise ValueError('Holidays must have both lower_window and ' +
  162. 'upper_window, or neither')
  163. if has_lower:
  164. if self.holidays['lower_window'].max() > 0:
  165. raise ValueError('Holiday lower_window should be <= 0')
  166. if self.holidays['upper_window'].min() < 0:
  167. raise ValueError('Holiday upper_window should be >= 0')
  168. for h in self.holidays['holiday'].unique():
  169. self.validate_column_name(h, check_holidays=False)
  170. if self.seasonality_mode not in ['additive', 'multiplicative']:
  171. raise ValueError(
  172. "seasonality_mode must be 'additive' or 'multiplicative'"
  173. )
  174. def validate_column_name(self, name, check_holidays=True,
  175. check_seasonalities=True, check_regressors=True):
  176. """Validates the name of a seasonality, holiday, or regressor.
  177. Parameters
  178. ----------
  179. name: string
  180. check_holidays: bool check if name already used for holiday
  181. check_seasonalities: bool check if name already used for seasonality
  182. check_regressors: bool check if name already used for regressor
  183. """
  184. if '_delim_' in name:
  185. raise ValueError('Name cannot contain "_delim_"')
  186. reserved_names = [
  187. 'trend', 'additive_terms', 'daily', 'weekly', 'yearly',
  188. 'holidays', 'zeros', 'extra_regressors_additive','yhat',
  189. 'extra_regressors_multiplicative', 'multiplicative_terms',
  190. ]
  191. rn_l = [n + '_lower' for n in reserved_names]
  192. rn_u = [n + '_upper' for n in reserved_names]
  193. reserved_names.extend(rn_l)
  194. reserved_names.extend(rn_u)
  195. reserved_names.extend([
  196. 'ds', 'y', 'cap', 'floor', 'y_scaled', 'cap_scaled'])
  197. if name in reserved_names:
  198. raise ValueError('Name "{}" is reserved.'.format(name))
  199. if (check_holidays and self.holidays is not None and
  200. name in self.holidays['holiday'].unique()):
  201. raise ValueError(
  202. 'Name "{}" already used for a holiday.'.format(name))
  203. if check_seasonalities and name in self.seasonalities:
  204. raise ValueError(
  205. 'Name "{}" already used for a seasonality.'.format(name))
  206. if check_regressors and name in self.extra_regressors:
  207. raise ValueError(
  208. 'Name "{}" already used for an added regressor.'.format(name))
  209. def setup_dataframe(self, df, initialize_scales=False):
  210. """Prepare dataframe for fitting or predicting.
  211. Adds a time index and scales y. Creates auxiliary columns 't', 't_ix',
  212. 'y_scaled', and 'cap_scaled'. These columns are used during both
  213. fitting and predicting.
  214. Parameters
  215. ----------
  216. df: pd.DataFrame with columns ds, y, and cap if logistic growth. Any
  217. specified additional regressors must also be present.
  218. initialize_scales: Boolean set scaling factors in self from df.
  219. Returns
  220. -------
  221. pd.DataFrame prepared for fitting or predicting.
  222. """
  223. if 'y' in df:
  224. df['y'] = pd.to_numeric(df['y'])
  225. if np.isinf(df['y'].values).any():
  226. raise ValueError('Found infinity in column y.')
  227. df['ds'] = pd.to_datetime(df['ds'])
  228. if df['ds'].isnull().any():
  229. raise ValueError('Found NaN in column ds.')
  230. for name in self.extra_regressors:
  231. if name not in df:
  232. raise ValueError(
  233. 'Regressor "{}" missing from dataframe'.format(name))
  234. df = df.sort_values('ds')
  235. df.reset_index(inplace=True, drop=True)
  236. self.initialize_scales(initialize_scales, df)
  237. if self.logistic_floor:
  238. if 'floor' not in df:
  239. raise ValueError("Expected column 'floor'.")
  240. else:
  241. df['floor'] = 0
  242. if self.growth == 'logistic':
  243. assert 'cap' in df
  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. raise ValueError('Regressor {} is constant.'.format(name))
  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. assert prior_scale > 0
  476. if mode not in ['additive', 'multiplicative']:
  477. raise ValueError("mode must be 'additive' or 'multiplicative'")
  478. self.extra_regressors[name] = {
  479. 'prior_scale': prior_scale,
  480. 'standardize': standardize,
  481. 'mu': 0.,
  482. 'std': 1.,
  483. 'mode': mode,
  484. }
  485. return self
  486. def add_seasonality(
  487. self, name, period, fourier_order, prior_scale=None, mode=None
  488. ):
  489. """Add a seasonal component with specified period, number of Fourier
  490. components, and prior scale.
  491. Increasing the number of Fourier components allows the seasonality to
  492. change more quickly (at risk of overfitting). Default values for yearly
  493. and weekly seasonalities are 10 and 3 respectively.
  494. Increasing prior scale will allow this seasonality component more
  495. flexibility, decreasing will dampen it. If not provided, will use the
  496. seasonality_prior_scale provided on Prophet initialization (defaults
  497. to 10).
  498. Mode can be specified as either 'additive' or 'multiplicative'. If not
  499. specified, self.seasonality_mode will be used (defaults to additive).
  500. Additive means the seasonality will be added to the trend,
  501. multiplicative means it will multiply the trend.
  502. Parameters
  503. ----------
  504. name: string name of the seasonality component.
  505. period: float number of days in one period.
  506. fourier_order: int number of Fourier components to use.
  507. prior_scale: optional float prior scale for this component.
  508. mode: optional 'additive' or 'multiplicative'
  509. Returns
  510. -------
  511. The prophet object.
  512. """
  513. if self.history is not None:
  514. raise Exception(
  515. "Seasonality must be added prior to model fitting.")
  516. if name not in ['daily', 'weekly', 'yearly']:
  517. # Allow overwriting built-in seasonalities
  518. self.validate_column_name(name, check_seasonalities=False)
  519. if prior_scale is None:
  520. ps = self.seasonality_prior_scale
  521. else:
  522. ps = float(prior_scale)
  523. if ps <= 0:
  524. raise ValueError('Prior scale must be > 0')
  525. if mode is None:
  526. mode = self.seasonality_mode
  527. if mode not in ['additive', 'multiplicative']:
  528. raise ValueError("mode must be 'additive' or 'multiplicative'")
  529. self.seasonalities[name] = {
  530. 'period': period,
  531. 'fourier_order': fourier_order,
  532. 'prior_scale': ps,
  533. 'mode': mode,
  534. }
  535. return self
  536. def make_all_seasonality_features(self, df):
  537. """Dataframe with seasonality features.
  538. Includes seasonality features, holiday features, and added regressors.
  539. Parameters
  540. ----------
  541. df: pd.DataFrame with dates for computing seasonality features and any
  542. added regressors.
  543. Returns
  544. -------
  545. pd.DataFrame with regression features.
  546. list of prior scales for each column of the features dataframe.
  547. Dataframe with indicators for which regression components correspond to
  548. which columns.
  549. Dictionary with keys 'additive' and 'multiplicative' listing the
  550. component names for each mode of seasonality.
  551. """
  552. seasonal_features = []
  553. prior_scales = []
  554. modes = {'additive': [], 'multiplicative': []}
  555. # Seasonality features
  556. for name, props in self.seasonalities.items():
  557. features = self.make_seasonality_features(
  558. df['ds'],
  559. props['period'],
  560. props['fourier_order'],
  561. name,
  562. )
  563. seasonal_features.append(features)
  564. prior_scales.extend(
  565. [props['prior_scale']] * features.shape[1])
  566. modes[props['mode']].append(name)
  567. # Holiday features
  568. if self.holidays is not None:
  569. features, holiday_priors, holiday_names = (
  570. self.make_holiday_features(df['ds'])
  571. )
  572. seasonal_features.append(features)
  573. prior_scales.extend(holiday_priors)
  574. modes[self.seasonality_mode].extend(holiday_names)
  575. # Additional regressors
  576. for name, props in self.extra_regressors.items():
  577. seasonal_features.append(pd.DataFrame(df[name]))
  578. prior_scales.append(props['prior_scale'])
  579. modes[props['mode']].append(name)
  580. # Dummy to prevent empty X
  581. if len(seasonal_features) == 0:
  582. seasonal_features.append(
  583. pd.DataFrame({'zeros': np.zeros(df.shape[0])}))
  584. prior_scales.append(1.)
  585. seasonal_features = pd.concat(seasonal_features, axis=1)
  586. component_cols, modes = self.regressor_column_matrix(
  587. seasonal_features, modes
  588. )
  589. return seasonal_features, prior_scales, component_cols, modes
  590. def regressor_column_matrix(self, seasonal_features, modes):
  591. """Dataframe indicating which columns of the feature matrix correspond
  592. to which seasonality/regressor components.
  593. Includes combination components, like 'additive_terms'. These
  594. combination components will be added to the 'modes' input.
  595. Parameters
  596. ----------
  597. seasonal_features: Constructed seasonal features dataframe
  598. modes: Dictionary with keys 'additive' and 'multiplicative' listing the
  599. component names for each mode of seasonality.
  600. Returns
  601. -------
  602. component_cols: A binary indicator dataframe with columns seasonal
  603. components and rows columns in seasonal_features. Entry is 1 if
  604. that columns is used in that component.
  605. modes: Updated input with combination components.
  606. """
  607. components = pd.DataFrame({
  608. 'col': np.arange(seasonal_features.shape[1]),
  609. 'component': [
  610. x.split('_delim_')[0] for x in seasonal_features.columns
  611. ],
  612. })
  613. # Add total for holidays
  614. if self.holidays is not None:
  615. components = self.add_group_component(
  616. components, 'holidays', self.holidays['holiday'].unique())
  617. # Add totals additive and multiplicative components, and regressors
  618. for mode in ['additive', 'multiplicative']:
  619. components = self.add_group_component(
  620. components, mode + '_terms', modes[mode]
  621. )
  622. regressors_by_mode = [
  623. r for r, props in self.extra_regressors.items()
  624. if props['mode'] == mode
  625. ]
  626. components = self.add_group_component(
  627. components, 'extra_regressors_' + mode, regressors_by_mode)
  628. # Add combination components to modes
  629. modes[mode].append(mode + '_terms')
  630. modes[mode].append('extra_regressors_' + mode)
  631. # After all of the additive/multiplicative groups have been added,
  632. modes[self.seasonality_mode].append('holidays')
  633. # Convert to a binary matrix
  634. component_cols = pd.crosstab(
  635. components['col'], components['component'],
  636. ).sort_index(level='col')
  637. # Add columns for additive and multiplicative terms, if missing
  638. for name in ['additive_terms', 'multiplicative_terms']:
  639. if name not in component_cols:
  640. component_cols[name] = 0
  641. # Remove the placeholder
  642. component_cols.drop('zeros', axis=1, inplace=True, errors='ignore')
  643. # Validation
  644. if (
  645. max(component_cols['additive_terms']
  646. + component_cols['multiplicative_terms']) > 1
  647. ):
  648. raise Exception('A bug occurred in seasonal components.')
  649. # Compare to the training, if set.
  650. if self.train_component_cols is not None:
  651. component_cols = component_cols[self.train_component_cols.columns]
  652. if not component_cols.equals(self.train_component_cols):
  653. raise Exception('A bug occurred in constructing regressors.')
  654. return component_cols, modes
  655. def add_group_component(self, components, name, group):
  656. """Adds a component with given name that contains all of the components
  657. in group.
  658. Parameters
  659. ----------
  660. components: Dataframe with components.
  661. name: Name of new group component.
  662. group: List of components that form the group.
  663. Returns
  664. -------
  665. Dataframe with components.
  666. """
  667. new_comp = components[components['component'].isin(set(group))].copy()
  668. group_cols = new_comp['col'].unique()
  669. if len(group_cols) > 0:
  670. new_comp = pd.DataFrame({'col': group_cols, 'component': name})
  671. components = components.append(new_comp)
  672. return components
  673. def parse_seasonality_args(self, name, arg, auto_disable, default_order):
  674. """Get number of fourier components for built-in seasonalities.
  675. Parameters
  676. ----------
  677. name: string name of the seasonality component.
  678. arg: 'auto', True, False, or number of fourier components as provided.
  679. auto_disable: bool if seasonality should be disabled when 'auto'.
  680. default_order: int default fourier order
  681. Returns
  682. -------
  683. Number of fourier components, or 0 for disabled.
  684. """
  685. if arg == 'auto':
  686. fourier_order = 0
  687. if name in self.seasonalities:
  688. logger.info(
  689. 'Found custom seasonality named "{name}", '
  690. 'disabling built-in {name} seasonality.'.format(name=name)
  691. )
  692. elif auto_disable:
  693. logger.info(
  694. 'Disabling {name} seasonality. Run prophet with '
  695. '{name}_seasonality=True to override this.'.format(
  696. name=name)
  697. )
  698. else:
  699. fourier_order = default_order
  700. elif arg is True:
  701. fourier_order = default_order
  702. elif arg is False:
  703. fourier_order = 0
  704. else:
  705. fourier_order = int(arg)
  706. return fourier_order
  707. def set_auto_seasonalities(self):
  708. """Set seasonalities that were left on auto.
  709. Turns on yearly seasonality if there is >=2 years of history.
  710. Turns on weekly seasonality if there is >=2 weeks of history, and the
  711. spacing between dates in the history is <7 days.
  712. Turns on daily seasonality if there is >=2 days of history, and the
  713. spacing between dates in the history is <1 day.
  714. """
  715. first = self.history['ds'].min()
  716. last = self.history['ds'].max()
  717. dt = self.history['ds'].diff()
  718. min_dt = dt.iloc[dt.nonzero()[0]].min()
  719. # Yearly seasonality
  720. yearly_disable = last - first < pd.Timedelta(days=730)
  721. fourier_order = self.parse_seasonality_args(
  722. 'yearly', self.yearly_seasonality, yearly_disable, 10)
  723. if fourier_order > 0:
  724. self.seasonalities['yearly'] = {
  725. 'period': 365.25,
  726. 'fourier_order': fourier_order,
  727. 'prior_scale': self.seasonality_prior_scale,
  728. 'mode': self.seasonality_mode,
  729. }
  730. # Weekly seasonality
  731. weekly_disable = ((last - first < pd.Timedelta(weeks=2)) or
  732. (min_dt >= pd.Timedelta(weeks=1)))
  733. fourier_order = self.parse_seasonality_args(
  734. 'weekly', self.weekly_seasonality, weekly_disable, 3)
  735. if fourier_order > 0:
  736. self.seasonalities['weekly'] = {
  737. 'period': 7,
  738. 'fourier_order': fourier_order,
  739. 'prior_scale': self.seasonality_prior_scale,
  740. 'mode': self.seasonality_mode,
  741. }
  742. # Daily seasonality
  743. daily_disable = ((last - first < pd.Timedelta(days=2)) or
  744. (min_dt >= pd.Timedelta(days=1)))
  745. fourier_order = self.parse_seasonality_args(
  746. 'daily', self.daily_seasonality, daily_disable, 4)
  747. if fourier_order > 0:
  748. self.seasonalities['daily'] = {
  749. 'period': 1,
  750. 'fourier_order': fourier_order,
  751. 'prior_scale': self.seasonality_prior_scale,
  752. 'mode': self.seasonality_mode,
  753. }
  754. @staticmethod
  755. def linear_growth_init(df):
  756. """Initialize linear growth.
  757. Provides a strong initialization for linear growth by calculating the
  758. growth and offset parameters that pass the function through the first
  759. and last points in the time series.
  760. Parameters
  761. ----------
  762. df: pd.DataFrame with columns ds (date), y_scaled (scaled time series),
  763. and t (scaled time).
  764. Returns
  765. -------
  766. A tuple (k, m) with the rate (k) and offset (m) of the linear growth
  767. function.
  768. """
  769. i0, i1 = df['ds'].idxmin(), df['ds'].idxmax()
  770. T = df['t'].iloc[i1] - df['t'].iloc[i0]
  771. k = (df['y_scaled'].iloc[i1] - df['y_scaled'].iloc[i0]) / T
  772. m = df['y_scaled'].iloc[i0] - k * df['t'].iloc[i0]
  773. return (k, m)
  774. @staticmethod
  775. def logistic_growth_init(df):
  776. """Initialize logistic growth.
  777. Provides a strong initialization for logistic growth by calculating the
  778. growth and offset parameters that pass the function through the first
  779. and last points in the time series.
  780. Parameters
  781. ----------
  782. df: pd.DataFrame with columns ds (date), cap_scaled (scaled capacity),
  783. y_scaled (scaled time series), and t (scaled time).
  784. Returns
  785. -------
  786. A tuple (k, m) with the rate (k) and offset (m) of the logistic growth
  787. function.
  788. """
  789. i0, i1 = df['ds'].idxmin(), df['ds'].idxmax()
  790. T = df['t'].iloc[i1] - df['t'].iloc[i0]
  791. # Force valid values, in case y > cap or y < 0
  792. C0 = df['cap_scaled'].iloc[i0]
  793. C1 = df['cap_scaled'].iloc[i1]
  794. y0 = max(0.01 * C0, min(0.99 * C0, df['y_scaled'].iloc[i0]))
  795. y1 = max(0.01 * C1, min(0.99 * C1, df['y_scaled'].iloc[i1]))
  796. r0 = C0 / y0
  797. r1 = C1 / y1
  798. if abs(r0 - r1) <= 0.01:
  799. r0 = 1.05 * r0
  800. L0 = np.log(r0 - 1)
  801. L1 = np.log(r1 - 1)
  802. # Initialize the offset
  803. m = L0 * T / (L0 - L1)
  804. # And the rate
  805. k = (L0 - L1) / T
  806. return (k, m)
  807. # fb-block 7
  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. # fb-block 8
  915. def predict(self, df=None):
  916. """Predict using the prophet model.
  917. Parameters
  918. ----------
  919. df: pd.DataFrame with dates for predictions (column ds), and capacity
  920. (column cap) if logistic growth. If not provided, predictions are
  921. made on the history.
  922. Returns
  923. -------
  924. A pd.DataFrame with the forecast components.
  925. """
  926. if df is None:
  927. df = self.history.copy()
  928. else:
  929. if df.shape[0] == 0:
  930. raise ValueError('Dataframe has no rows.')
  931. df = self.setup_dataframe(df.copy())
  932. df['trend'] = self.predict_trend(df)
  933. seasonal_components = self.predict_seasonal_components(df)
  934. intervals = self.predict_uncertainty(df)
  935. # Drop columns except ds, cap, floor, and trend
  936. cols = ['ds', 'trend']
  937. if 'cap' in df:
  938. cols.append('cap')
  939. if self.logistic_floor:
  940. cols.append('floor')
  941. # Add in forecast components
  942. df2 = pd.concat((df[cols], intervals, seasonal_components), axis=1)
  943. df2['yhat'] = (
  944. df2['trend'] * (1 + df2['multiplicative_terms'])
  945. + df2['additive_terms']
  946. )
  947. return df2
  948. @staticmethod
  949. def piecewise_linear(t, deltas, k, m, changepoint_ts):
  950. """Evaluate the piecewise linear function.
  951. Parameters
  952. ----------
  953. t: np.array of times on which the function is evaluated.
  954. deltas: np.array of rate changes at each changepoint.
  955. k: Float initial rate.
  956. m: Float initial offset.
  957. changepoint_ts: np.array of changepoint times.
  958. Returns
  959. -------
  960. Vector y(t).
  961. """
  962. # Intercept changes
  963. gammas = -changepoint_ts * deltas
  964. # Get cumulative slope and intercept at each t
  965. k_t = k * np.ones_like(t)
  966. m_t = m * np.ones_like(t)
  967. for s, t_s in enumerate(changepoint_ts):
  968. indx = t >= t_s
  969. k_t[indx] += deltas[s]
  970. m_t[indx] += gammas[s]
  971. return k_t * t + m_t
  972. @staticmethod
  973. def piecewise_logistic(t, cap, deltas, k, m, changepoint_ts):
  974. """Evaluate the piecewise logistic function.
  975. Parameters
  976. ----------
  977. t: np.array of times on which the function is evaluated.
  978. cap: np.array of capacities at each t.
  979. deltas: np.array of rate changes at each changepoint.
  980. k: Float initial rate.
  981. m: Float initial offset.
  982. changepoint_ts: np.array of changepoint times.
  983. Returns
  984. -------
  985. Vector y(t).
  986. """
  987. # Compute offset changes
  988. k_cum = np.concatenate((np.atleast_1d(k), np.cumsum(deltas) + k))
  989. gammas = np.zeros(len(changepoint_ts))
  990. for i, t_s in enumerate(changepoint_ts):
  991. gammas[i] = (
  992. (t_s - m - np.sum(gammas))
  993. * (1 - k_cum[i] / k_cum[i + 1]) # noqa W503
  994. )
  995. # Get cumulative rate and offset at each t
  996. k_t = k * np.ones_like(t)
  997. m_t = m * np.ones_like(t)
  998. for s, t_s in enumerate(changepoint_ts):
  999. indx = t >= t_s
  1000. k_t[indx] += deltas[s]
  1001. m_t[indx] += gammas[s]
  1002. return cap / (1 + np.exp(-k_t * (t - m_t)))
  1003. def predict_trend(self, df):
  1004. """Predict trend using the prophet model.
  1005. Parameters
  1006. ----------
  1007. df: Prediction dataframe.
  1008. Returns
  1009. -------
  1010. Vector with trend on prediction dates.
  1011. """
  1012. k = np.nanmean(self.params['k'])
  1013. m = np.nanmean(self.params['m'])
  1014. deltas = np.nanmean(self.params['delta'], axis=0)
  1015. t = np.array(df['t'])
  1016. if self.growth == 'linear':
  1017. trend = self.piecewise_linear(t, deltas, k, m, self.changepoints_t)
  1018. else:
  1019. cap = df['cap_scaled']
  1020. trend = self.piecewise_logistic(
  1021. t, cap, deltas, k, m, self.changepoints_t)
  1022. return trend * self.y_scale + df['floor']
  1023. def predict_seasonal_components(self, df):
  1024. """Predict seasonality components, holidays, and added regressors.
  1025. Parameters
  1026. ----------
  1027. df: Prediction dataframe.
  1028. Returns
  1029. -------
  1030. Dataframe with seasonal components.
  1031. """
  1032. seasonal_features, _, component_cols, _ = (
  1033. self.make_all_seasonality_features(df)
  1034. )
  1035. lower_p = 100 * (1.0 - self.interval_width) / 2
  1036. upper_p = 100 * (1.0 + self.interval_width) / 2
  1037. X = seasonal_features.values
  1038. data = {}
  1039. for component in component_cols.columns:
  1040. beta_c = self.params['beta'] * component_cols[component].values
  1041. comp = np.matmul(X, beta_c.transpose())
  1042. if component in self.component_modes['additive']:
  1043. comp *= self.y_scale
  1044. data[component] = np.nanmean(comp, axis=1)
  1045. data[component + '_lower'] = np.nanpercentile(
  1046. comp, lower_p, axis=1,
  1047. )
  1048. data[component + '_upper'] = np.nanpercentile(
  1049. comp, upper_p, axis=1,
  1050. )
  1051. return pd.DataFrame(data)
  1052. def sample_posterior_predictive(self, df):
  1053. """Prophet posterior predictive samples.
  1054. Parameters
  1055. ----------
  1056. df: Prediction dataframe.
  1057. Returns
  1058. -------
  1059. Dictionary with posterior predictive samples for the forecast yhat and
  1060. for the trend component.
  1061. """
  1062. n_iterations = self.params['k'].shape[0]
  1063. samp_per_iter = max(1, int(np.ceil(
  1064. self.uncertainty_samples / float(n_iterations)
  1065. )))
  1066. # Generate seasonality features once so we can re-use them.
  1067. seasonal_features, _, component_cols, _ = (
  1068. self.make_all_seasonality_features(df)
  1069. )
  1070. sim_values = {'yhat': [], 'trend': []}
  1071. for i in range(n_iterations):
  1072. for _j in range(samp_per_iter):
  1073. sim = self.sample_model(
  1074. df=df,
  1075. seasonal_features=seasonal_features,
  1076. iteration=i,
  1077. s_a=component_cols['additive_terms'],
  1078. s_m=component_cols['multiplicative_terms'],
  1079. )
  1080. for key in sim_values:
  1081. sim_values[key].append(sim[key])
  1082. for k, v in sim_values.items():
  1083. sim_values[k] = np.column_stack(v)
  1084. return sim_values
  1085. def predictive_samples(self, df):
  1086. """Sample from the posterior predictive distribution.
  1087. Parameters
  1088. ----------
  1089. df: Dataframe with dates for predictions (column ds), and capacity
  1090. (column cap) if logistic growth.
  1091. Returns
  1092. -------
  1093. Dictionary with keys "trend" and "yhat" containing
  1094. posterior predictive samples for that component.
  1095. """
  1096. df = self.setup_dataframe(df.copy())
  1097. sim_values = self.sample_posterior_predictive(df)
  1098. return sim_values
  1099. def predict_uncertainty(self, df):
  1100. """Prediction intervals for yhat and trend.
  1101. Parameters
  1102. ----------
  1103. df: Prediction dataframe.
  1104. Returns
  1105. -------
  1106. Dataframe with uncertainty intervals.
  1107. """
  1108. sim_values = self.sample_posterior_predictive(df)
  1109. lower_p = 100 * (1.0 - self.interval_width) / 2
  1110. upper_p = 100 * (1.0 + self.interval_width) / 2
  1111. series = {}
  1112. for key in ['yhat', 'trend']:
  1113. series['{}_lower'.format(key)] = np.nanpercentile(
  1114. sim_values[key], lower_p, axis=1)
  1115. series['{}_upper'.format(key)] = np.nanpercentile(
  1116. sim_values[key], upper_p, axis=1)
  1117. return pd.DataFrame(series)
  1118. def sample_model(self, df, seasonal_features, iteration, s_a, s_m):
  1119. """Simulate observations from the extrapolated generative model.
  1120. Parameters
  1121. ----------
  1122. df: Prediction dataframe.
  1123. seasonal_features: pd.DataFrame of seasonal features.
  1124. iteration: Int sampling iteration to use parameters from.
  1125. s_a: Indicator vector for additive components
  1126. s_m: Indicator vector for multiplicative components
  1127. Returns
  1128. -------
  1129. Dataframe with trend and yhat, each like df['t'].
  1130. """
  1131. trend = self.sample_predictive_trend(df, iteration)
  1132. beta = self.params['beta'][iteration]
  1133. Xb_a = np.matmul(seasonal_features.values, beta * s_a) * self.y_scale
  1134. Xb_m = np.matmul(seasonal_features.values, beta * s_m)
  1135. sigma = self.params['sigma_obs'][iteration]
  1136. noise = np.random.normal(0, sigma, df.shape[0]) * self.y_scale
  1137. return pd.DataFrame({
  1138. 'yhat': trend * (1 + Xb_m) + Xb_a + noise,
  1139. 'trend': trend
  1140. })
  1141. def sample_predictive_trend(self, df, iteration):
  1142. """Simulate the trend using the extrapolated generative model.
  1143. Parameters
  1144. ----------
  1145. df: Prediction dataframe.
  1146. iteration: Int sampling iteration to use parameters from.
  1147. Returns
  1148. -------
  1149. np.array of simulated trend over df['t'].
  1150. """
  1151. k = self.params['k'][iteration]
  1152. m = self.params['m'][iteration]
  1153. deltas = self.params['delta'][iteration]
  1154. t = np.array(df['t'])
  1155. T = t.max()
  1156. # New changepoints from a Poisson process with rate S on [1, T]
  1157. if T > 1:
  1158. S = len(self.changepoints_t)
  1159. n_changes = np.random.poisson(S * (T - 1))
  1160. else:
  1161. n_changes = 0
  1162. if n_changes > 0:
  1163. changepoint_ts_new = 1 + np.random.rand(n_changes) * (T - 1)
  1164. changepoint_ts_new.sort()
  1165. else:
  1166. changepoint_ts_new = []
  1167. # Get the empirical scale of the deltas, plus epsilon to avoid NaNs.
  1168. lambda_ = np.mean(np.abs(deltas)) + 1e-8
  1169. # Sample deltas
  1170. deltas_new = np.random.laplace(0, lambda_, n_changes)
  1171. # Prepend the times and deltas from the history
  1172. changepoint_ts = np.concatenate((self.changepoints_t,
  1173. changepoint_ts_new))
  1174. deltas = np.concatenate((deltas, deltas_new))
  1175. if self.growth == 'linear':
  1176. trend = self.piecewise_linear(t, deltas, k, m, changepoint_ts)
  1177. else:
  1178. cap = df['cap_scaled']
  1179. trend = self.piecewise_logistic(t, cap, deltas, k, m,
  1180. changepoint_ts)
  1181. return trend * self.y_scale + df['floor']
  1182. def make_future_dataframe(self, periods, freq='D', include_history=True):
  1183. """Simulate the trend using the extrapolated generative model.
  1184. Parameters
  1185. ----------
  1186. periods: Int number of periods to forecast forward.
  1187. freq: Any valid frequency for pd.date_range, such as 'D' or 'M'.
  1188. include_history: Boolean to include the historical dates in the data
  1189. frame for predictions.
  1190. Returns
  1191. -------
  1192. pd.Dataframe that extends forward from the end of self.history for the
  1193. requested number of periods.
  1194. """
  1195. if self.history_dates is None:
  1196. raise Exception('Model must be fit before this can be used.')
  1197. last_date = self.history_dates.max()
  1198. dates = pd.date_range(
  1199. start=last_date,
  1200. periods=periods + 1, # An extra in case we include start
  1201. freq=freq)
  1202. dates = dates[dates > last_date] # Drop start if equals last_date
  1203. dates = dates[:periods] # Return correct number of periods
  1204. if include_history:
  1205. dates = np.concatenate((np.array(self.history_dates), dates))
  1206. return pd.DataFrame({'ds': dates})
  1207. def plot(self, fcst, ax=None, uncertainty=True, plot_cap=True, xlabel='ds',
  1208. ylabel='y'):
  1209. """Plot the Prophet forecast.
  1210. Parameters
  1211. ----------
  1212. fcst: pd.DataFrame output of self.predict.
  1213. ax: Optional matplotlib axes on which to plot.
  1214. uncertainty: Optional boolean to plot uncertainty intervals.
  1215. plot_cap: Optional boolean indicating if the capacity should be shown
  1216. in the figure, if available.
  1217. xlabel: Optional label name on X-axis
  1218. ylabel: Optional label name on Y-axis
  1219. Returns
  1220. -------
  1221. A matplotlib figure.
  1222. """
  1223. return plot(
  1224. m=self, fcst=fcst, ax=ax, uncertainty=uncertainty,
  1225. plot_cap=plot_cap, xlabel=xlabel, ylabel=ylabel,
  1226. )
  1227. def plot_components(self, fcst, uncertainty=True, plot_cap=True,
  1228. weekly_start=0, yearly_start=0):
  1229. """Plot the Prophet forecast components.
  1230. Will plot whichever are available of: trend, holidays, weekly
  1231. seasonality, and yearly seasonality.
  1232. Parameters
  1233. ----------
  1234. fcst: pd.DataFrame output of self.predict.
  1235. uncertainty: Optional boolean to plot uncertainty intervals.
  1236. plot_cap: Optional boolean indicating if the capacity should be shown
  1237. in the figure, if available.
  1238. weekly_start: Optional int specifying the start day of the weekly
  1239. seasonality plot. 0 (default) starts the week on Sunday. 1 shifts
  1240. by 1 day to Monday, and so on.
  1241. yearly_start: Optional int specifying the start day of the yearly
  1242. seasonality plot. 0 (default) starts the year on Jan 1. 1 shifts
  1243. by 1 day to Jan 2, and so on.
  1244. Returns
  1245. -------
  1246. A matplotlib figure.
  1247. """
  1248. return plot_components(
  1249. m=self, fcst=fcst, uncertainty=uncertainty, plot_cap=plot_cap,
  1250. weekly_start=weekly_start, yearly_start=yearly_start,
  1251. )
  1252. def plot_forecast_component(
  1253. self, fcst, name, ax=None, uncertainty=True, plot_cap=False):
  1254. warnings.warn(
  1255. 'This method will be removed in the next version. '
  1256. 'Please use fbprophet.plot.plot_forecast_component. ',
  1257. DeprecationWarning,
  1258. )
  1259. return plot_forecast_component(
  1260. self, fcst=fcst, name=name, ax=ax, uncertainty=uncertainty,
  1261. plot_cap=plot_cap,
  1262. )
  1263. def seasonality_plot_df(self, ds):
  1264. warnings.warn(
  1265. 'This method will be removed in the next version. '
  1266. 'Please use fbprophet.plot.seasonality_plot_df. ',
  1267. DeprecationWarning,
  1268. )
  1269. return seasonality_plot_df(self, ds=ds)
  1270. def plot_weekly(self, ax=None, uncertainty=True, weekly_start=0):
  1271. warnings.warn(
  1272. 'This method will be removed in the next version. '
  1273. 'Please use fbprophet.plot.plot_weekly. ',
  1274. DeprecationWarning,
  1275. )
  1276. return plot_weekly(
  1277. self, ax=ax, uncertainty=uncertainty, weekly_start=weekly_start,
  1278. )
  1279. def plot_yearly(self, ax=None, uncertainty=True, yearly_start=0):
  1280. warnings.warn(
  1281. 'This method will be removed in the next version. '
  1282. 'Please use fbprophet.plot.plot_yearly. ',
  1283. DeprecationWarning,
  1284. )
  1285. return plot_yearly(
  1286. self, ax=ax, uncertainty=uncertainty, yearly_start=yearly_start,
  1287. )
  1288. def plot_seasonality(self, name, ax=None, uncertainty=True):
  1289. warnings.warn(
  1290. 'This method will be removed in the next version. '
  1291. 'Please use fbprophet.plot.plot_seasonality. ',
  1292. DeprecationWarning,
  1293. )
  1294. return plot_seasonality(
  1295. self, name=name, ax=ax, uncertainty=uncertainty,
  1296. )
  1297. def copy(self, cutoff=None):
  1298. warnings.warn(
  1299. 'This method will be removed in the next version. '
  1300. 'Please use fbprophet.diagnostics.prophet_copy. ',
  1301. DeprecationWarning,
  1302. )
  1303. return prophet_copy(m=self, cutoff=cutoff)