forecaster.py 55 KB

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