forecaster.py 53 KB

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