forecaster.py 54 KB

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