forecaster.py 57 KB

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