forecaster.py 57 KB

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