forecaster.py 51 KB

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