forecaster.py 57 KB

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