forecaster.py 46 KB

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