forecaster.py 57 KB

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