forecaster.py 53 KB

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