forecaster.py 49 KB

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