forecaster.py 49 KB

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