forecaster.py 57 KB

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