forecaster.py 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518
  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. dataframe of holiday dates, in holiday dataframe format used in
  395. initialization.
  396. """
  397. all_holidays = pd.DataFrame()
  398. if self.holidays is not None:
  399. all_holidays = self.holidays.copy()
  400. if self.country_holidays is not None:
  401. year_list = list({x.year for x in dates})
  402. country_holidays_df = make_holidays_df(
  403. year_list=year_list, country=self.country_holidays
  404. )
  405. all_holidays = pd.concat((all_holidays, country_holidays_df), sort=False)
  406. all_holidays.reset_index(drop=True, inplace=True)
  407. # If the model has already been fit with a certain set of holidays,
  408. # make sure we are using those same ones.
  409. if self.train_holiday_names is not None:
  410. # Remove holiday names didn't show up in fit
  411. index_to_drop = all_holidays.index[
  412. np.logical_not(
  413. all_holidays.holiday.isin(self.train_holiday_names)
  414. )
  415. ]
  416. all_holidays = all_holidays.drop(index_to_drop)
  417. # Add holiday names in fit but not in predict with ds as NA
  418. holidays_to_add = pd.DataFrame({
  419. 'holiday': self.train_holiday_names[
  420. np.logical_not(self.train_holiday_names.isin(all_holidays.holiday))
  421. ]
  422. })
  423. all_holidays = pd.concat((all_holidays, holidays_to_add), sort=False)
  424. all_holidays.reset_index(drop=True, inplace=True)
  425. return all_holidays
  426. def make_holiday_features(self, dates, holidays):
  427. """Construct a dataframe of holiday features.
  428. Parameters
  429. ----------
  430. dates: pd.Series containing timestamps used for computing seasonality.
  431. holidays: pd.Dataframe containing holidays, as returned by
  432. construct_holiday_dataframe.
  433. Returns
  434. -------
  435. holiday_features: pd.DataFrame with a column for each holiday.
  436. prior_scale_list: List of prior scales for each holiday column.
  437. holiday_names: List of names of holidays
  438. """
  439. # Holds columns of our future matrix.
  440. expanded_holidays = defaultdict(lambda: np.zeros(dates.shape[0]))
  441. prior_scales = {}
  442. # Makes an index so we can perform `get_loc` below.
  443. # Strip to just dates.
  444. row_index = pd.DatetimeIndex(dates.apply(lambda x: x.date()))
  445. for _ix, row in holidays.iterrows():
  446. dt = row.ds.date()
  447. try:
  448. lw = int(row.get('lower_window', 0))
  449. uw = int(row.get('upper_window', 0))
  450. except ValueError:
  451. lw = 0
  452. uw = 0
  453. ps = float(row.get('prior_scale', self.holidays_prior_scale))
  454. if np.isnan(ps):
  455. ps = float(self.holidays_prior_scale)
  456. if (
  457. row.holiday in prior_scales and prior_scales[row.holiday] != ps
  458. ):
  459. raise ValueError(
  460. 'Holiday {} does not have consistent prior scale '
  461. 'specification.'.format(row.holiday))
  462. if ps <= 0:
  463. raise ValueError('Prior scale must be > 0')
  464. prior_scales[row.holiday] = ps
  465. for offset in range(lw, uw + 1):
  466. occurrence = dt + timedelta(days=offset)
  467. try:
  468. loc = row_index.get_loc(occurrence)
  469. except KeyError:
  470. loc = None
  471. key = '{}_delim_{}{}'.format(
  472. row.holiday,
  473. '+' if offset >= 0 else '-',
  474. abs(offset)
  475. )
  476. if loc is not None:
  477. expanded_holidays[key][loc] = 1.
  478. else:
  479. # Access key to generate value
  480. expanded_holidays[key]
  481. holiday_features = pd.DataFrame(expanded_holidays)
  482. # Make sure column order is consistent
  483. holiday_features = holiday_features[sorted(holiday_features.columns.tolist())]
  484. prior_scale_list = [
  485. prior_scales[h.split('_delim_')[0]]
  486. for h in holiday_features.columns
  487. ]
  488. holiday_names = list(prior_scales.keys())
  489. # Store holiday names used in fit
  490. if self.train_holiday_names is None:
  491. self.train_holiday_names = pd.Series(holiday_names)
  492. return holiday_features, prior_scale_list, holiday_names
  493. def add_regressor(
  494. self, name, prior_scale=None, standardize='auto', mode=None
  495. ):
  496. """Add an additional regressor to be used for fitting and predicting.
  497. The dataframe passed to `fit` and `predict` will have a column with the
  498. specified name to be used as a regressor. When standardize='auto', the
  499. regressor will be standardized unless it is binary. The regression
  500. coefficient is given a prior with the specified scale parameter.
  501. Decreasing the prior scale will add additional regularization. If no
  502. prior scale is provided, self.holidays_prior_scale will be used.
  503. Mode can be specified as either 'additive' or 'multiplicative'. If not
  504. specified, self.seasonality_mode will be used. 'additive' means the
  505. effect of the regressor will be added to the trend, 'multiplicative'
  506. means it will multiply the trend.
  507. Parameters
  508. ----------
  509. name: string name of the regressor.
  510. prior_scale: optional float scale for the normal prior. If not
  511. provided, self.holidays_prior_scale will be used.
  512. standardize: optional, specify whether this regressor will be
  513. standardized prior to fitting. Can be 'auto' (standardize if not
  514. binary), True, or False.
  515. mode: optional, 'additive' or 'multiplicative'. Defaults to
  516. self.seasonality_mode.
  517. Returns
  518. -------
  519. The prophet object.
  520. """
  521. if self.history is not None:
  522. raise Exception(
  523. "Regressors must be added prior to model fitting.")
  524. self.validate_column_name(name, check_regressors=False)
  525. if prior_scale is None:
  526. prior_scale = float(self.holidays_prior_scale)
  527. if mode is None:
  528. mode = self.seasonality_mode
  529. if prior_scale <= 0:
  530. raise ValueError('Prior scale must be > 0')
  531. if mode not in ['additive', 'multiplicative']:
  532. raise ValueError("mode must be 'additive' or 'multiplicative'")
  533. self.extra_regressors[name] = {
  534. 'prior_scale': prior_scale,
  535. 'standardize': standardize,
  536. 'mu': 0.,
  537. 'std': 1.,
  538. 'mode': mode,
  539. }
  540. return self
  541. def add_seasonality(
  542. self, name, period, fourier_order, prior_scale=None, mode=None
  543. ):
  544. """Add a seasonal component with specified period, number of Fourier
  545. components, and prior scale.
  546. Increasing the number of Fourier components allows the seasonality to
  547. change more quickly (at risk of overfitting). Default values for yearly
  548. and weekly seasonalities are 10 and 3 respectively.
  549. Increasing prior scale will allow this seasonality component more
  550. flexibility, decreasing will dampen it. If not provided, will use the
  551. seasonality_prior_scale provided on Prophet initialization (defaults
  552. to 10).
  553. Mode can be specified as either 'additive' or 'multiplicative'. If not
  554. specified, self.seasonality_mode will be used (defaults to additive).
  555. Additive means the seasonality will be added to the trend,
  556. multiplicative means it will multiply the trend.
  557. Parameters
  558. ----------
  559. name: string name of the seasonality component.
  560. period: float number of days in one period.
  561. fourier_order: int number of Fourier components to use.
  562. prior_scale: optional float prior scale for this component.
  563. mode: optional 'additive' or 'multiplicative'
  564. Returns
  565. -------
  566. The prophet object.
  567. """
  568. if self.history is not None:
  569. raise Exception(
  570. "Seasonality must be added prior to model fitting.")
  571. if name not in ['daily', 'weekly', 'yearly']:
  572. # Allow overwriting built-in seasonalities
  573. self.validate_column_name(name, check_seasonalities=False)
  574. if prior_scale is None:
  575. ps = self.seasonality_prior_scale
  576. else:
  577. ps = float(prior_scale)
  578. if ps <= 0:
  579. raise ValueError('Prior scale must be > 0')
  580. if mode is None:
  581. mode = self.seasonality_mode
  582. if mode not in ['additive', 'multiplicative']:
  583. raise ValueError("mode must be 'additive' or 'multiplicative'")
  584. self.seasonalities[name] = {
  585. 'period': period,
  586. 'fourier_order': fourier_order,
  587. 'prior_scale': ps,
  588. 'mode': mode,
  589. }
  590. return self
  591. def add_country_holidays(self, country_name):
  592. """Add in built-in holidays for the specified country.
  593. These holidays will be included in addition to any specified on model
  594. initialization.
  595. Holidays will be calculated for arbitrary date ranges in the history
  596. and future. See the online documentation for the list of countries with
  597. built-in holidays.
  598. Built-in country holidays can only be set for a single country.
  599. Parameters
  600. ----------
  601. country_name: Name of the country, like 'UnitedStates' or 'US'
  602. Returns
  603. -------
  604. The prophet object.
  605. """
  606. if self.history is not None:
  607. raise Exception(
  608. "Country holidays must be added prior to model fitting."
  609. )
  610. # Validate names.
  611. for name in get_holiday_names(country_name):
  612. # Allow merging with existing holidays
  613. self.validate_column_name(name, check_holidays=False)
  614. # Set the holidays.
  615. if self.country_holidays is not None:
  616. logger.warning(
  617. 'Changing country holidays from {} to {}'.format(
  618. self.country_holidays, country_name
  619. )
  620. )
  621. self.country_holidays = country_name
  622. return self
  623. def make_all_seasonality_features(self, df):
  624. """Dataframe with seasonality features.
  625. Includes seasonality features, holiday features, and added regressors.
  626. Parameters
  627. ----------
  628. df: pd.DataFrame with dates for computing seasonality features and any
  629. added regressors.
  630. Returns
  631. -------
  632. pd.DataFrame with regression features.
  633. list of prior scales for each column of the features dataframe.
  634. Dataframe with indicators for which regression components correspond to
  635. which columns.
  636. Dictionary with keys 'additive' and 'multiplicative' listing the
  637. component names for each mode of seasonality.
  638. """
  639. seasonal_features = []
  640. prior_scales = []
  641. modes = {'additive': [], 'multiplicative': []}
  642. # Seasonality features
  643. for name, props in self.seasonalities.items():
  644. features = self.make_seasonality_features(
  645. df['ds'],
  646. props['period'],
  647. props['fourier_order'],
  648. name,
  649. )
  650. seasonal_features.append(features)
  651. prior_scales.extend(
  652. [props['prior_scale']] * features.shape[1])
  653. modes[props['mode']].append(name)
  654. # Holiday features
  655. holidays = self.construct_holiday_dataframe(df['ds'])
  656. if len(holidays) > 0:
  657. features, holiday_priors, holiday_names = (
  658. self.make_holiday_features(df['ds'], holidays)
  659. )
  660. seasonal_features.append(features)
  661. prior_scales.extend(holiday_priors)
  662. modes[self.seasonality_mode].extend(holiday_names)
  663. # Additional regressors
  664. for name, props in self.extra_regressors.items():
  665. seasonal_features.append(pd.DataFrame(df[name]))
  666. prior_scales.append(props['prior_scale'])
  667. modes[props['mode']].append(name)
  668. # Dummy to prevent empty X
  669. if len(seasonal_features) == 0:
  670. seasonal_features.append(
  671. pd.DataFrame({'zeros': np.zeros(df.shape[0])}))
  672. prior_scales.append(1.)
  673. seasonal_features = pd.concat(seasonal_features, axis=1)
  674. component_cols, modes = self.regressor_column_matrix(
  675. seasonal_features, modes
  676. )
  677. return seasonal_features, prior_scales, component_cols, modes
  678. def regressor_column_matrix(self, seasonal_features, modes):
  679. """Dataframe indicating which columns of the feature matrix correspond
  680. to which seasonality/regressor components.
  681. Includes combination components, like 'additive_terms'. These
  682. combination components will be added to the 'modes' input.
  683. Parameters
  684. ----------
  685. seasonal_features: Constructed seasonal features dataframe
  686. modes: Dictionary with keys 'additive' and 'multiplicative' listing the
  687. component names for each mode of seasonality.
  688. Returns
  689. -------
  690. component_cols: A binary indicator dataframe with columns seasonal
  691. components and rows columns in seasonal_features. Entry is 1 if
  692. that columns is used in that component.
  693. modes: Updated input with combination components.
  694. """
  695. components = pd.DataFrame({
  696. 'col': np.arange(seasonal_features.shape[1]),
  697. 'component': [
  698. x.split('_delim_')[0] for x in seasonal_features.columns
  699. ],
  700. })
  701. # Add total for holidays
  702. if self.train_holiday_names is not None:
  703. components = self.add_group_component(
  704. components, 'holidays', self.train_holiday_names.unique())
  705. # Add totals additive and multiplicative components, and regressors
  706. for mode in ['additive', 'multiplicative']:
  707. components = self.add_group_component(
  708. components, mode + '_terms', modes[mode]
  709. )
  710. regressors_by_mode = [
  711. r for r, props in self.extra_regressors.items()
  712. if props['mode'] == mode
  713. ]
  714. components = self.add_group_component(
  715. components, 'extra_regressors_' + mode, regressors_by_mode)
  716. # Add combination components to modes
  717. modes[mode].append(mode + '_terms')
  718. modes[mode].append('extra_regressors_' + mode)
  719. # After all of the additive/multiplicative groups have been added,
  720. modes[self.seasonality_mode].append('holidays')
  721. # Convert to a binary matrix
  722. component_cols = pd.crosstab(
  723. components['col'], components['component'],
  724. ).sort_index(level='col')
  725. # Add columns for additive and multiplicative terms, if missing
  726. for name in ['additive_terms', 'multiplicative_terms']:
  727. if name not in component_cols:
  728. component_cols[name] = 0
  729. # Remove the placeholder
  730. component_cols.drop('zeros', axis=1, inplace=True, errors='ignore')
  731. # Validation
  732. if (
  733. max(component_cols['additive_terms']
  734. + component_cols['multiplicative_terms']) > 1
  735. ):
  736. raise Exception('A bug occurred in seasonal components.')
  737. # Compare to the training, if set.
  738. if self.train_component_cols is not None:
  739. component_cols = component_cols[self.train_component_cols.columns]
  740. if not component_cols.equals(self.train_component_cols):
  741. raise Exception('A bug occurred in constructing regressors.')
  742. return component_cols, modes
  743. def add_group_component(self, components, name, group):
  744. """Adds a component with given name that contains all of the components
  745. in group.
  746. Parameters
  747. ----------
  748. components: Dataframe with components.
  749. name: Name of new group component.
  750. group: List of components that form the group.
  751. Returns
  752. -------
  753. Dataframe with components.
  754. """
  755. new_comp = components[components['component'].isin(set(group))].copy()
  756. group_cols = new_comp['col'].unique()
  757. if len(group_cols) > 0:
  758. new_comp = pd.DataFrame({'col': group_cols, 'component': name})
  759. components = components.append(new_comp)
  760. return components
  761. def parse_seasonality_args(self, name, arg, auto_disable, default_order):
  762. """Get number of fourier components for built-in seasonalities.
  763. Parameters
  764. ----------
  765. name: string name of the seasonality component.
  766. arg: 'auto', True, False, or number of fourier components as provided.
  767. auto_disable: bool if seasonality should be disabled when 'auto'.
  768. default_order: int default fourier order
  769. Returns
  770. -------
  771. Number of fourier components, or 0 for disabled.
  772. """
  773. if arg == 'auto':
  774. fourier_order = 0
  775. if name in self.seasonalities:
  776. logger.info(
  777. 'Found custom seasonality named "{name}", '
  778. 'disabling built-in {name} seasonality.'.format(name=name)
  779. )
  780. elif auto_disable:
  781. logger.info(
  782. 'Disabling {name} seasonality. Run prophet with '
  783. '{name}_seasonality=True to override this.'.format(
  784. name=name)
  785. )
  786. else:
  787. fourier_order = default_order
  788. elif arg is True:
  789. fourier_order = default_order
  790. elif arg is False:
  791. fourier_order = 0
  792. else:
  793. fourier_order = int(arg)
  794. return fourier_order
  795. def set_auto_seasonalities(self):
  796. """Set seasonalities that were left on auto.
  797. Turns on yearly seasonality if there is >=2 years of history.
  798. Turns on weekly seasonality if there is >=2 weeks of history, and the
  799. spacing between dates in the history is <7 days.
  800. Turns on daily seasonality if there is >=2 days of history, and the
  801. spacing between dates in the history is <1 day.
  802. """
  803. first = self.history['ds'].min()
  804. last = self.history['ds'].max()
  805. dt = self.history['ds'].diff()
  806. min_dt = dt.iloc[dt.nonzero()[0]].min()
  807. # Yearly seasonality
  808. yearly_disable = last - first < pd.Timedelta(days=730)
  809. fourier_order = self.parse_seasonality_args(
  810. 'yearly', self.yearly_seasonality, yearly_disable, 10)
  811. if fourier_order > 0:
  812. self.seasonalities['yearly'] = {
  813. 'period': 365.25,
  814. 'fourier_order': fourier_order,
  815. 'prior_scale': self.seasonality_prior_scale,
  816. 'mode': self.seasonality_mode,
  817. }
  818. # Weekly seasonality
  819. weekly_disable = ((last - first < pd.Timedelta(weeks=2)) or
  820. (min_dt >= pd.Timedelta(weeks=1)))
  821. fourier_order = self.parse_seasonality_args(
  822. 'weekly', self.weekly_seasonality, weekly_disable, 3)
  823. if fourier_order > 0:
  824. self.seasonalities['weekly'] = {
  825. 'period': 7,
  826. 'fourier_order': fourier_order,
  827. 'prior_scale': self.seasonality_prior_scale,
  828. 'mode': self.seasonality_mode,
  829. }
  830. # Daily seasonality
  831. daily_disable = ((last - first < pd.Timedelta(days=2)) or
  832. (min_dt >= pd.Timedelta(days=1)))
  833. fourier_order = self.parse_seasonality_args(
  834. 'daily', self.daily_seasonality, daily_disable, 4)
  835. if fourier_order > 0:
  836. self.seasonalities['daily'] = {
  837. 'period': 1,
  838. 'fourier_order': fourier_order,
  839. 'prior_scale': self.seasonality_prior_scale,
  840. 'mode': self.seasonality_mode,
  841. }
  842. @staticmethod
  843. def linear_growth_init(df):
  844. """Initialize linear growth.
  845. Provides a strong initialization for linear growth by calculating the
  846. growth and offset parameters that pass the function through the first
  847. and last points in the time series.
  848. Parameters
  849. ----------
  850. df: pd.DataFrame with columns ds (date), y_scaled (scaled time series),
  851. and t (scaled time).
  852. Returns
  853. -------
  854. A tuple (k, m) with the rate (k) and offset (m) of the linear growth
  855. function.
  856. """
  857. i0, i1 = df['ds'].idxmin(), df['ds'].idxmax()
  858. T = df['t'].iloc[i1] - df['t'].iloc[i0]
  859. k = (df['y_scaled'].iloc[i1] - df['y_scaled'].iloc[i0]) / T
  860. m = df['y_scaled'].iloc[i0] - k * df['t'].iloc[i0]
  861. return (k, m)
  862. @staticmethod
  863. def logistic_growth_init(df):
  864. """Initialize logistic growth.
  865. Provides a strong initialization for logistic growth by calculating the
  866. growth and offset parameters that pass the function through the first
  867. and last points in the time series.
  868. Parameters
  869. ----------
  870. df: pd.DataFrame with columns ds (date), cap_scaled (scaled capacity),
  871. y_scaled (scaled time series), and t (scaled time).
  872. Returns
  873. -------
  874. A tuple (k, m) with the rate (k) and offset (m) of the logistic growth
  875. function.
  876. """
  877. i0, i1 = df['ds'].idxmin(), df['ds'].idxmax()
  878. T = df['t'].iloc[i1] - df['t'].iloc[i0]
  879. # Force valid values, in case y > cap or y < 0
  880. C0 = df['cap_scaled'].iloc[i0]
  881. C1 = df['cap_scaled'].iloc[i1]
  882. y0 = max(0.01 * C0, min(0.99 * C0, df['y_scaled'].iloc[i0]))
  883. y1 = max(0.01 * C1, min(0.99 * C1, df['y_scaled'].iloc[i1]))
  884. r0 = C0 / y0
  885. r1 = C1 / y1
  886. if abs(r0 - r1) <= 0.01:
  887. r0 = 1.05 * r0
  888. L0 = np.log(r0 - 1)
  889. L1 = np.log(r1 - 1)
  890. # Initialize the offset
  891. m = L0 * T / (L0 - L1)
  892. # And the rate
  893. k = (L0 - L1) / T
  894. return (k, m)
  895. def fit(self, df, **kwargs):
  896. """Fit the Prophet model.
  897. This sets self.params to contain the fitted model parameters. It is a
  898. dictionary parameter names as keys and the following items:
  899. k (Mx1 array): M posterior samples of the initial slope.
  900. m (Mx1 array): The initial intercept.
  901. delta (MxN array): The slope change at each of N changepoints.
  902. beta (MxK matrix): Coefficients for K seasonality features.
  903. sigma_obs (Mx1 array): Noise level.
  904. Note that M=1 if MAP estimation.
  905. Parameters
  906. ----------
  907. df: pd.DataFrame containing the history. Must have columns ds (date
  908. type) and y, the time series. If self.growth is 'logistic', then
  909. df must also have a column cap that specifies the capacity at
  910. each ds.
  911. kwargs: Additional arguments passed to the optimizing or sampling
  912. functions in Stan.
  913. Returns
  914. -------
  915. The fitted Prophet object.
  916. """
  917. if self.history is not None:
  918. raise Exception('Prophet object can only be fit once. '
  919. 'Instantiate a new object.')
  920. if ('ds' not in df) or ('y' not in df):
  921. raise ValueError(
  922. "Dataframe must have columns 'ds' and 'y' with the dates and "
  923. "values respectively."
  924. )
  925. history = df[df['y'].notnull()].copy()
  926. if history.shape[0] < 2:
  927. raise ValueError('Dataframe has less than 2 non-NaN rows.')
  928. self.history_dates = pd.to_datetime(df['ds']).sort_values()
  929. history = self.setup_dataframe(history, initialize_scales=True)
  930. self.history = history
  931. self.set_auto_seasonalities()
  932. seasonal_features, prior_scales, component_cols, modes = (
  933. self.make_all_seasonality_features(history))
  934. self.train_component_cols = component_cols
  935. self.component_modes = modes
  936. self.set_changepoints()
  937. dat = {
  938. 'T': history.shape[0],
  939. 'K': seasonal_features.shape[1],
  940. 'S': len(self.changepoints_t),
  941. 'y': history['y_scaled'],
  942. 't': history['t'],
  943. 't_change': self.changepoints_t,
  944. 'X': seasonal_features,
  945. 'sigmas': prior_scales,
  946. 'tau': self.changepoint_prior_scale,
  947. 'trend_indicator': int(self.growth == 'logistic'),
  948. 's_a': component_cols['additive_terms'],
  949. 's_m': component_cols['multiplicative_terms'],
  950. }
  951. if self.growth == 'linear':
  952. dat['cap'] = np.zeros(self.history.shape[0])
  953. kinit = self.linear_growth_init(history)
  954. else:
  955. dat['cap'] = history['cap_scaled']
  956. kinit = self.logistic_growth_init(history)
  957. model = prophet_stan_model
  958. def stan_init():
  959. return {
  960. 'k': kinit[0],
  961. 'm': kinit[1],
  962. 'delta': np.zeros(len(self.changepoints_t)),
  963. 'beta': np.zeros(seasonal_features.shape[1]),
  964. 'sigma_obs': 1,
  965. }
  966. if (
  967. (history['y'].min() == history['y'].max())
  968. and self.growth == 'linear'
  969. ):
  970. # Nothing to fit.
  971. self.params = stan_init()
  972. self.params['sigma_obs'] = 1e-9
  973. for par in self.params:
  974. self.params[par] = np.array([self.params[par]])
  975. elif self.mcmc_samples > 0:
  976. stan_fit = model.sampling(
  977. dat,
  978. init=stan_init,
  979. iter=self.mcmc_samples,
  980. **kwargs
  981. )
  982. for par in stan_fit.model_pars:
  983. self.params[par] = stan_fit[par]
  984. else:
  985. try:
  986. params = model.optimizing(
  987. dat, init=stan_init, iter=1e4, **kwargs)
  988. except RuntimeError:
  989. kwargs.pop('algorithm', None)
  990. params = model.optimizing(
  991. dat, init=stan_init, iter=1e4, algorithm='Newton',
  992. **kwargs
  993. )
  994. for par in params:
  995. self.params[par] = params[par].reshape((1, -1))
  996. # If no changepoints were requested, replace delta with 0s
  997. if len(self.changepoints) == 0:
  998. # Fold delta into the base rate k
  999. self.params['k'] = self.params['k'] + self.params['delta']
  1000. self.params['delta'] = np.zeros(self.params['delta'].shape)
  1001. return self
  1002. def predict(self, df=None):
  1003. """Predict using the prophet model.
  1004. Parameters
  1005. ----------
  1006. df: pd.DataFrame with dates for predictions (column ds), and capacity
  1007. (column cap) if logistic growth. If not provided, predictions are
  1008. made on the history.
  1009. Returns
  1010. -------
  1011. A pd.DataFrame with the forecast components.
  1012. """
  1013. if df is None:
  1014. df = self.history.copy()
  1015. else:
  1016. if df.shape[0] == 0:
  1017. raise ValueError('Dataframe has no rows.')
  1018. df = self.setup_dataframe(df.copy())
  1019. df['trend'] = self.predict_trend(df)
  1020. seasonal_components = self.predict_seasonal_components(df)
  1021. intervals = self.predict_uncertainty(df)
  1022. # Drop columns except ds, cap, floor, and trend
  1023. cols = ['ds', 'trend']
  1024. if 'cap' in df:
  1025. cols.append('cap')
  1026. if self.logistic_floor:
  1027. cols.append('floor')
  1028. # Add in forecast components
  1029. df2 = pd.concat((df[cols], intervals, seasonal_components), axis=1)
  1030. df2['yhat'] = (
  1031. df2['trend'] * (1 + df2['multiplicative_terms'])
  1032. + df2['additive_terms']
  1033. )
  1034. return df2
  1035. @staticmethod
  1036. def piecewise_linear(t, deltas, k, m, changepoint_ts):
  1037. """Evaluate the piecewise linear function.
  1038. Parameters
  1039. ----------
  1040. t: np.array of times on which the function is evaluated.
  1041. deltas: np.array of rate changes at each changepoint.
  1042. k: Float initial rate.
  1043. m: Float initial offset.
  1044. changepoint_ts: np.array of changepoint times.
  1045. Returns
  1046. -------
  1047. Vector y(t).
  1048. """
  1049. # Intercept changes
  1050. gammas = -changepoint_ts * deltas
  1051. # Get cumulative slope and intercept at each t
  1052. k_t = k * np.ones_like(t)
  1053. m_t = m * np.ones_like(t)
  1054. for s, t_s in enumerate(changepoint_ts):
  1055. indx = t >= t_s
  1056. k_t[indx] += deltas[s]
  1057. m_t[indx] += gammas[s]
  1058. return k_t * t + m_t
  1059. @staticmethod
  1060. def piecewise_logistic(t, cap, deltas, k, m, changepoint_ts):
  1061. """Evaluate the piecewise logistic function.
  1062. Parameters
  1063. ----------
  1064. t: np.array of times on which the function is evaluated.
  1065. cap: np.array of capacities at each t.
  1066. deltas: np.array of rate changes at each changepoint.
  1067. k: Float initial rate.
  1068. m: Float initial offset.
  1069. changepoint_ts: np.array of changepoint times.
  1070. Returns
  1071. -------
  1072. Vector y(t).
  1073. """
  1074. # Compute offset changes
  1075. k_cum = np.concatenate((np.atleast_1d(k), np.cumsum(deltas) + k))
  1076. gammas = np.zeros(len(changepoint_ts))
  1077. for i, t_s in enumerate(changepoint_ts):
  1078. gammas[i] = (
  1079. (t_s - m - np.sum(gammas))
  1080. * (1 - k_cum[i] / k_cum[i + 1]) # noqa W503
  1081. )
  1082. # Get cumulative rate and offset at each t
  1083. k_t = k * np.ones_like(t)
  1084. m_t = m * np.ones_like(t)
  1085. for s, t_s in enumerate(changepoint_ts):
  1086. indx = t >= t_s
  1087. k_t[indx] += deltas[s]
  1088. m_t[indx] += gammas[s]
  1089. return cap / (1 + np.exp(-k_t * (t - m_t)))
  1090. def predict_trend(self, df):
  1091. """Predict trend using the prophet model.
  1092. Parameters
  1093. ----------
  1094. df: Prediction dataframe.
  1095. Returns
  1096. -------
  1097. Vector with trend on prediction dates.
  1098. """
  1099. k = np.nanmean(self.params['k'])
  1100. m = np.nanmean(self.params['m'])
  1101. deltas = np.nanmean(self.params['delta'], axis=0)
  1102. t = np.array(df['t'])
  1103. if self.growth == 'linear':
  1104. trend = self.piecewise_linear(t, deltas, k, m, self.changepoints_t)
  1105. else:
  1106. cap = df['cap_scaled']
  1107. trend = self.piecewise_logistic(
  1108. t, cap, deltas, k, m, self.changepoints_t)
  1109. return trend * self.y_scale + df['floor']
  1110. def predict_seasonal_components(self, df):
  1111. """Predict seasonality components, holidays, and added regressors.
  1112. Parameters
  1113. ----------
  1114. df: Prediction dataframe.
  1115. Returns
  1116. -------
  1117. Dataframe with seasonal components.
  1118. """
  1119. seasonal_features, _, component_cols, _ = (
  1120. self.make_all_seasonality_features(df)
  1121. )
  1122. lower_p = 100 * (1.0 - self.interval_width) / 2
  1123. upper_p = 100 * (1.0 + self.interval_width) / 2
  1124. X = seasonal_features.values
  1125. data = {}
  1126. for component in component_cols.columns:
  1127. beta_c = self.params['beta'] * component_cols[component].values
  1128. comp = np.matmul(X, beta_c.transpose())
  1129. if component in self.component_modes['additive']:
  1130. comp *= self.y_scale
  1131. data[component] = np.nanmean(comp, axis=1)
  1132. data[component + '_lower'] = np.nanpercentile(
  1133. comp, lower_p, axis=1,
  1134. )
  1135. data[component + '_upper'] = np.nanpercentile(
  1136. comp, upper_p, axis=1,
  1137. )
  1138. return pd.DataFrame(data)
  1139. def sample_posterior_predictive(self, df):
  1140. """Prophet posterior predictive samples.
  1141. Parameters
  1142. ----------
  1143. df: Prediction dataframe.
  1144. Returns
  1145. -------
  1146. Dictionary with posterior predictive samples for the forecast yhat and
  1147. for the trend component.
  1148. """
  1149. n_iterations = self.params['k'].shape[0]
  1150. samp_per_iter = max(1, int(np.ceil(
  1151. self.uncertainty_samples / float(n_iterations)
  1152. )))
  1153. # Generate seasonality features once so we can re-use them.
  1154. seasonal_features, _, component_cols, _ = (
  1155. self.make_all_seasonality_features(df)
  1156. )
  1157. sim_values = {'yhat': [], 'trend': []}
  1158. for i in range(n_iterations):
  1159. for _j in range(samp_per_iter):
  1160. sim = self.sample_model(
  1161. df=df,
  1162. seasonal_features=seasonal_features,
  1163. iteration=i,
  1164. s_a=component_cols['additive_terms'],
  1165. s_m=component_cols['multiplicative_terms'],
  1166. )
  1167. for key in sim_values:
  1168. sim_values[key].append(sim[key])
  1169. for k, v in sim_values.items():
  1170. sim_values[k] = np.column_stack(v)
  1171. return sim_values
  1172. def predictive_samples(self, df):
  1173. """Sample from the posterior predictive distribution.
  1174. Parameters
  1175. ----------
  1176. df: Dataframe with dates for predictions (column ds), and capacity
  1177. (column cap) if logistic growth.
  1178. Returns
  1179. -------
  1180. Dictionary with keys "trend" and "yhat" containing
  1181. posterior predictive samples for that component.
  1182. """
  1183. df = self.setup_dataframe(df.copy())
  1184. sim_values = self.sample_posterior_predictive(df)
  1185. return sim_values
  1186. def predict_uncertainty(self, df):
  1187. """Prediction intervals for yhat and trend.
  1188. Parameters
  1189. ----------
  1190. df: Prediction dataframe.
  1191. Returns
  1192. -------
  1193. Dataframe with uncertainty intervals.
  1194. """
  1195. sim_values = self.sample_posterior_predictive(df)
  1196. lower_p = 100 * (1.0 - self.interval_width) / 2
  1197. upper_p = 100 * (1.0 + self.interval_width) / 2
  1198. series = {}
  1199. for key in ['yhat', 'trend']:
  1200. series['{}_lower'.format(key)] = np.nanpercentile(
  1201. sim_values[key], lower_p, axis=1)
  1202. series['{}_upper'.format(key)] = np.nanpercentile(
  1203. sim_values[key], upper_p, axis=1)
  1204. return pd.DataFrame(series)
  1205. def sample_model(self, df, seasonal_features, iteration, s_a, s_m):
  1206. """Simulate observations from the extrapolated generative model.
  1207. Parameters
  1208. ----------
  1209. df: Prediction dataframe.
  1210. seasonal_features: pd.DataFrame of seasonal features.
  1211. iteration: Int sampling iteration to use parameters from.
  1212. s_a: Indicator vector for additive components
  1213. s_m: Indicator vector for multiplicative components
  1214. Returns
  1215. -------
  1216. Dataframe with trend and yhat, each like df['t'].
  1217. """
  1218. trend = self.sample_predictive_trend(df, iteration)
  1219. beta = self.params['beta'][iteration]
  1220. Xb_a = np.matmul(seasonal_features.values, beta * s_a) * self.y_scale
  1221. Xb_m = np.matmul(seasonal_features.values, beta * s_m)
  1222. sigma = self.params['sigma_obs'][iteration]
  1223. noise = np.random.normal(0, sigma, df.shape[0]) * self.y_scale
  1224. return pd.DataFrame({
  1225. 'yhat': trend * (1 + Xb_m) + Xb_a + noise,
  1226. 'trend': trend
  1227. })
  1228. def sample_predictive_trend(self, df, iteration):
  1229. """Simulate the trend using the extrapolated generative model.
  1230. Parameters
  1231. ----------
  1232. df: Prediction dataframe.
  1233. iteration: Int sampling iteration to use parameters from.
  1234. Returns
  1235. -------
  1236. np.array of simulated trend over df['t'].
  1237. """
  1238. k = self.params['k'][iteration]
  1239. m = self.params['m'][iteration]
  1240. deltas = self.params['delta'][iteration]
  1241. t = np.array(df['t'])
  1242. T = t.max()
  1243. # New changepoints from a Poisson process with rate S on [1, T]
  1244. if T > 1:
  1245. S = len(self.changepoints_t)
  1246. n_changes = np.random.poisson(S * (T - 1))
  1247. else:
  1248. n_changes = 0
  1249. if n_changes > 0:
  1250. changepoint_ts_new = 1 + np.random.rand(n_changes) * (T - 1)
  1251. changepoint_ts_new.sort()
  1252. else:
  1253. changepoint_ts_new = []
  1254. # Get the empirical scale of the deltas, plus epsilon to avoid NaNs.
  1255. lambda_ = np.mean(np.abs(deltas)) + 1e-8
  1256. # Sample deltas
  1257. deltas_new = np.random.laplace(0, lambda_, n_changes)
  1258. # Prepend the times and deltas from the history
  1259. changepoint_ts = np.concatenate((self.changepoints_t,
  1260. changepoint_ts_new))
  1261. deltas = np.concatenate((deltas, deltas_new))
  1262. if self.growth == 'linear':
  1263. trend = self.piecewise_linear(t, deltas, k, m, changepoint_ts)
  1264. else:
  1265. cap = df['cap_scaled']
  1266. trend = self.piecewise_logistic(t, cap, deltas, k, m,
  1267. changepoint_ts)
  1268. return trend * self.y_scale + df['floor']
  1269. def make_future_dataframe(self, periods, freq='D', include_history=True):
  1270. """Simulate the trend using the extrapolated generative model.
  1271. Parameters
  1272. ----------
  1273. periods: Int number of periods to forecast forward.
  1274. freq: Any valid frequency for pd.date_range, such as 'D' or 'M'.
  1275. include_history: Boolean to include the historical dates in the data
  1276. frame for predictions.
  1277. Returns
  1278. -------
  1279. pd.Dataframe that extends forward from the end of self.history for the
  1280. requested number of periods.
  1281. """
  1282. if self.history_dates is None:
  1283. raise Exception('Model must be fit before this can be used.')
  1284. last_date = self.history_dates.max()
  1285. dates = pd.date_range(
  1286. start=last_date,
  1287. periods=periods + 1, # An extra in case we include start
  1288. freq=freq)
  1289. dates = dates[dates > last_date] # Drop start if equals last_date
  1290. dates = dates[:periods] # Return correct number of periods
  1291. if include_history:
  1292. dates = np.concatenate((np.array(self.history_dates), dates))
  1293. return pd.DataFrame({'ds': dates})
  1294. def plot(self, fcst, ax=None, uncertainty=True, plot_cap=True, xlabel='ds',
  1295. ylabel='y'):
  1296. """Plot the Prophet forecast.
  1297. Parameters
  1298. ----------
  1299. fcst: pd.DataFrame output of self.predict.
  1300. ax: Optional matplotlib axes on which to plot.
  1301. uncertainty: Optional boolean to plot uncertainty intervals.
  1302. plot_cap: Optional boolean indicating if the capacity should be shown
  1303. in the figure, if available.
  1304. xlabel: Optional label name on X-axis
  1305. ylabel: Optional label name on Y-axis
  1306. Returns
  1307. -------
  1308. A matplotlib figure.
  1309. """
  1310. return plot(
  1311. m=self, fcst=fcst, ax=ax, uncertainty=uncertainty,
  1312. plot_cap=plot_cap, xlabel=xlabel, ylabel=ylabel,
  1313. )
  1314. def plot_components(self, fcst, uncertainty=True, plot_cap=True,
  1315. weekly_start=0, yearly_start=0):
  1316. """Plot the Prophet forecast components.
  1317. Will plot whichever are available of: trend, holidays, weekly
  1318. seasonality, and yearly seasonality.
  1319. Parameters
  1320. ----------
  1321. fcst: pd.DataFrame output of self.predict.
  1322. uncertainty: Optional boolean to plot uncertainty intervals.
  1323. plot_cap: Optional boolean indicating if the capacity should be shown
  1324. in the figure, if available.
  1325. weekly_start: Optional int specifying the start day of the weekly
  1326. seasonality plot. 0 (default) starts the week on Sunday. 1 shifts
  1327. by 1 day to Monday, and so on.
  1328. yearly_start: Optional int specifying the start day of the yearly
  1329. seasonality plot. 0 (default) starts the year on Jan 1. 1 shifts
  1330. by 1 day to Jan 2, and so on.
  1331. Returns
  1332. -------
  1333. A matplotlib figure.
  1334. """
  1335. return plot_components(
  1336. m=self, fcst=fcst, uncertainty=uncertainty, plot_cap=plot_cap,
  1337. weekly_start=weekly_start, yearly_start=yearly_start,
  1338. )