forecaster.py 54 KB

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