test_prophet.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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. import numpy as np
  12. import pandas as pd
  13. # fb-block 1 start
  14. import os
  15. import itertools
  16. from unittest import TestCase
  17. from fbprophet import Prophet
  18. DATA = pd.read_csv(
  19. os.path.join(os.path.dirname(__file__), 'data.csv'),
  20. parse_dates=['ds'],
  21. )
  22. DATA2 = pd.read_csv(
  23. os.path.join(os.path.dirname(__file__), 'data2.csv'),
  24. parse_dates=['ds'],
  25. )
  26. # fb-block 1 end
  27. # fb-block 2
  28. class TestProphet(TestCase):
  29. def test_fit_predict(self):
  30. N = DATA.shape[0]
  31. train = DATA.head(N // 2)
  32. future = DATA.tail(N // 2)
  33. forecaster = Prophet()
  34. forecaster.fit(train)
  35. forecaster.predict(future)
  36. def test_fit_predict_no_seasons(self):
  37. N = DATA.shape[0]
  38. train = DATA.head(N // 2)
  39. future = DATA.tail(N // 2)
  40. forecaster = Prophet(weekly_seasonality=False, yearly_seasonality=False)
  41. forecaster.fit(train)
  42. forecaster.predict(future)
  43. def test_fit_predict_no_changepoints(self):
  44. N = DATA.shape[0]
  45. train = DATA.head(N // 2)
  46. future = DATA.tail(N // 2)
  47. forecaster = Prophet(n_changepoints=0)
  48. forecaster.fit(train)
  49. forecaster.predict(future)
  50. def test_fit_changepoint_not_in_history(self):
  51. train = DATA[(DATA['ds'] < '2013-01-01') | (DATA['ds'] > '2014-01-01')]
  52. train[(train['ds'] > '2014-01-01')] += 20
  53. future = pd.DataFrame({'ds': DATA['ds']})
  54. forecaster = Prophet(changepoints=['2013-06-06'])
  55. forecaster.fit(train)
  56. forecaster.predict(future)
  57. def test_fit_predict_duplicates(self):
  58. N = DATA.shape[0]
  59. train1 = DATA.head(N // 2).copy()
  60. train2 = DATA.head(N // 2).copy()
  61. train2['y'] += 10
  62. train = train1.append(train2)
  63. future = pd.DataFrame({'ds': DATA['ds'].tail(N // 2)})
  64. forecaster = Prophet()
  65. forecaster.fit(train)
  66. forecaster.predict(future)
  67. def test_setup_dataframe(self):
  68. m = Prophet()
  69. N = DATA.shape[0]
  70. history = DATA.head(N // 2).copy()
  71. history = m.setup_dataframe(history, initialize_scales=True)
  72. self.assertTrue('t' in history)
  73. self.assertEqual(history['t'].min(), 0.0)
  74. self.assertEqual(history['t'].max(), 1.0)
  75. self.assertTrue('y_scaled' in history)
  76. self.assertEqual(history['y_scaled'].max(), 1.0)
  77. def test_get_changepoints(self):
  78. m = Prophet()
  79. N = DATA.shape[0]
  80. history = DATA.head(N // 2).copy()
  81. history = m.setup_dataframe(history, initialize_scales=True)
  82. m.history = history
  83. m.set_changepoints()
  84. cp = m.changepoints_t
  85. self.assertEqual(cp.shape[0], m.n_changepoints)
  86. self.assertEqual(len(cp.shape), 1)
  87. self.assertTrue(cp.min() > 0)
  88. self.assertTrue(cp.max() < N)
  89. mat = m.get_changepoint_matrix()
  90. self.assertEqual(mat.shape[0], N // 2)
  91. self.assertEqual(mat.shape[1], m.n_changepoints)
  92. def test_get_zero_changepoints(self):
  93. m = Prophet(n_changepoints=0)
  94. N = DATA.shape[0]
  95. history = DATA.head(N // 2).copy()
  96. history = m.setup_dataframe(history, initialize_scales=True)
  97. m.history = history
  98. m.set_changepoints()
  99. cp = m.changepoints_t
  100. self.assertEqual(cp.shape[0], 1)
  101. self.assertEqual(cp[0], 0)
  102. mat = m.get_changepoint_matrix()
  103. self.assertEqual(mat.shape[0], N // 2)
  104. self.assertEqual(mat.shape[1], 1)
  105. def test_override_n_changepoints(self):
  106. m = Prophet()
  107. history = DATA.head(20).copy()
  108. history = m.setup_dataframe(history, initialize_scales=True)
  109. m.history = history
  110. m.set_changepoints()
  111. self.assertEqual(m.n_changepoints, 15)
  112. cp = m.changepoints_t
  113. self.assertEqual(cp.shape[0], 15)
  114. def test_fourier_series_weekly(self):
  115. mat = Prophet.fourier_series(DATA['ds'], 7, 3)
  116. # These are from the R forecast package directly.
  117. true_values = np.array([
  118. 0.7818315, 0.6234898, 0.9749279, -0.2225209, 0.4338837, -0.9009689,
  119. ])
  120. self.assertAlmostEqual(np.sum((mat[0] - true_values)**2), 0.0)
  121. def test_fourier_series_yearly(self):
  122. mat = Prophet.fourier_series(DATA['ds'], 365.25, 3)
  123. # These are from the R forecast package directly.
  124. true_values = np.array([
  125. 0.7006152, -0.7135393, -0.9998330, 0.01827656, 0.7262249, 0.6874572,
  126. ])
  127. self.assertAlmostEqual(np.sum((mat[0] - true_values)**2), 0.0)
  128. def test_growth_init(self):
  129. model = Prophet(growth='logistic')
  130. history = DATA.iloc[:468].copy()
  131. history['cap'] = history['y'].max()
  132. history = model.setup_dataframe(history, initialize_scales=True)
  133. k, m = model.linear_growth_init(history)
  134. self.assertAlmostEqual(k, 0.3055671)
  135. self.assertAlmostEqual(m, 0.5307511)
  136. k, m = model.logistic_growth_init(history)
  137. self.assertAlmostEqual(k, 1.507925, places=4)
  138. self.assertAlmostEqual(m, -0.08167497, places=4)
  139. def test_piecewise_linear(self):
  140. model = Prophet()
  141. t = np.arange(11.)
  142. m = 0
  143. k = 1.0
  144. deltas = np.array([0.5])
  145. changepoint_ts = np.array([5])
  146. y = model.piecewise_linear(t, deltas, k, m, changepoint_ts)
  147. y_true = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0,
  148. 6.5, 8.0, 9.5, 11.0, 12.5])
  149. self.assertEqual((y - y_true).sum(), 0.0)
  150. t = t[8:]
  151. y_true = y_true[8:]
  152. y = model.piecewise_linear(t, deltas, k, m, changepoint_ts)
  153. self.assertEqual((y - y_true).sum(), 0.0)
  154. def test_piecewise_logistic(self):
  155. model = Prophet()
  156. t = np.arange(11.)
  157. cap = np.ones(11) * 10
  158. m = 0
  159. k = 1.0
  160. deltas = np.array([0.5])
  161. changepoint_ts = np.array([5])
  162. y = model.piecewise_logistic(t, cap, deltas, k, m, changepoint_ts)
  163. y_true = np.array([5.000000, 7.310586, 8.807971, 9.525741, 9.820138,
  164. 9.933071, 9.984988, 9.996646, 9.999252, 9.999833,
  165. 9.999963])
  166. self.assertAlmostEqual((y - y_true).sum(), 0.0, places=5)
  167. t = t[8:]
  168. y_true = y_true[8:]
  169. cap = cap[8:]
  170. y = model.piecewise_logistic(t, cap, deltas, k, m, changepoint_ts)
  171. self.assertAlmostEqual((y - y_true).sum(), 0.0, places=5)
  172. def test_holidays(self):
  173. holidays = pd.DataFrame({
  174. 'ds': pd.to_datetime(['2016-12-25']),
  175. 'holiday': ['xmas'],
  176. 'lower_window': [-1],
  177. 'upper_window': [0],
  178. })
  179. model = Prophet(holidays=holidays)
  180. df = pd.DataFrame({
  181. 'ds': pd.date_range('2016-12-20', '2016-12-31')
  182. })
  183. feats = model.make_holiday_features(df['ds'])
  184. # 11 columns generated even though only 8 overlap
  185. self.assertEqual(feats.shape, (df.shape[0], 2))
  186. self.assertEqual((feats.sum(0) - np.array([1.0, 1.0])).sum(), 0)
  187. holidays = pd.DataFrame({
  188. 'ds': pd.to_datetime(['2016-12-25']),
  189. 'holiday': ['xmas'],
  190. 'lower_window': [-1],
  191. 'upper_window': [10],
  192. })
  193. feats = Prophet(holidays=holidays).make_holiday_features(df['ds'])
  194. # 12 columns generated even though only 8 overlap
  195. self.assertEqual(feats.shape, (df.shape[0], 12))
  196. def test_fit_with_holidays(self):
  197. holidays = pd.DataFrame({
  198. 'ds': pd.to_datetime(['2012-06-06', '2013-06-06']),
  199. 'holiday': ['seans-bday'] * 2,
  200. 'lower_window': [0] * 2,
  201. 'upper_window': [1] * 2,
  202. })
  203. model = Prophet(holidays=holidays, uncertainty_samples=0)
  204. model.fit(DATA).predict()
  205. def test_make_future_dataframe(self):
  206. N = 468
  207. train = DATA.head(N // 2)
  208. forecaster = Prophet()
  209. forecaster.fit(train)
  210. future = forecaster.make_future_dataframe(periods=3, freq='D',
  211. include_history=False)
  212. correct = pd.DatetimeIndex(['2013-04-26', '2013-04-27', '2013-04-28'])
  213. self.assertEqual(len(future), 3)
  214. for i in range(3):
  215. self.assertEqual(future.iloc[i]['ds'], correct[i])
  216. future = forecaster.make_future_dataframe(periods=3, freq='M',
  217. include_history=False)
  218. correct = pd.DatetimeIndex(['2013-04-30', '2013-05-31', '2013-06-30'])
  219. self.assertEqual(len(future), 3)
  220. for i in range(3):
  221. self.assertEqual(future.iloc[i]['ds'], correct[i])
  222. def test_auto_weekly_seasonality(self):
  223. # Should be enabled
  224. N = 15
  225. train = DATA.head(N)
  226. m = Prophet()
  227. self.assertEqual(m.weekly_seasonality, 'auto')
  228. m.fit(train)
  229. self.assertIn('weekly', m.seasonalities)
  230. self.assertEqual(m.seasonalities['weekly'], (7, 3))
  231. # Should be disabled due to too short history
  232. N = 9
  233. train = DATA.head(N)
  234. m = Prophet()
  235. m.fit(train)
  236. self.assertNotIn('weekly', m.seasonalities)
  237. m = Prophet(weekly_seasonality=True)
  238. m.fit(train)
  239. self.assertIn('weekly', m.seasonalities)
  240. # Should be False due to weekly spacing
  241. train = DATA.iloc[::7, :]
  242. m = Prophet()
  243. m.fit(train)
  244. self.assertNotIn('weekly', m.seasonalities)
  245. m = Prophet(weekly_seasonality=2)
  246. m.fit(DATA)
  247. self.assertEqual(m.seasonalities['weekly'], (7, 2))
  248. def test_auto_yearly_seasonality(self):
  249. # Should be enabled
  250. m = Prophet()
  251. self.assertEqual(m.yearly_seasonality, 'auto')
  252. m.fit(DATA)
  253. self.assertIn('yearly', m.seasonalities)
  254. self.assertEqual(m.seasonalities['yearly'], (365.25, 10))
  255. # Should be disabled due to too short history
  256. N = 240
  257. train = DATA.head(N)
  258. m = Prophet()
  259. m.fit(train)
  260. self.assertNotIn('yearly', m.seasonalities)
  261. m = Prophet(yearly_seasonality=True)
  262. m.fit(train)
  263. self.assertIn('yearly', m.seasonalities)
  264. m = Prophet(yearly_seasonality=7)
  265. m.fit(DATA)
  266. self.assertEqual(m.seasonalities['yearly'], (365.25, 7))
  267. def test_auto_daily_seasonality(self):
  268. # Should be enabled
  269. m = Prophet()
  270. self.assertEqual(m.daily_seasonality, 'auto')
  271. m.fit(DATA2)
  272. self.assertIn('daily', m.seasonalities)
  273. self.assertEqual(m.seasonalities['daily'], (1, 4))
  274. # Should be disabled due to too short history
  275. N = 430
  276. train = DATA2.head(N)
  277. m = Prophet()
  278. m.fit(train)
  279. self.assertNotIn('daily', m.seasonalities)
  280. m = Prophet(daily_seasonality=True)
  281. m.fit(train)
  282. self.assertIn('daily', m.seasonalities)
  283. m = Prophet(daily_seasonality=7)
  284. m.fit(DATA2)
  285. self.assertEqual(m.seasonalities['daily'], (1, 7))
  286. m = Prophet()
  287. m.fit(DATA)
  288. self.assertNotIn('daily', m.seasonalities)
  289. def test_subdaily_holidays(self):
  290. holidays = pd.DataFrame({
  291. 'ds': pd.to_datetime(['2017-01-02']),
  292. 'holiday': ['special_day'],
  293. })
  294. m = Prophet(holidays=holidays)
  295. m.fit(DATA2)
  296. fcst = m.predict()
  297. self.assertEqual(sum(fcst['special_day'] == 0), 575)
  298. def test_custom_seasonality(self):
  299. holidays = pd.DataFrame({
  300. 'ds': pd.to_datetime(['2017-01-02']),
  301. 'holiday': ['special_day'],
  302. })
  303. m = Prophet(holidays=holidays)
  304. m.add_seasonality(name='monthly', period=30, fourier_order=5)
  305. self.assertEqual(m.seasonalities['monthly'], (30, 5))
  306. with self.assertRaises(ValueError):
  307. m.add_seasonality(name='special_day', period=30, fourier_order=5)
  308. with self.assertRaises(ValueError):
  309. m.add_seasonality(name='trend', period=30, fourier_order=5)
  310. m.add_seasonality(name='weekly', period=30, fourier_order=5)
  311. def test_added_regressors(self):
  312. m = Prophet()
  313. m.add_regressor('binary_feature', prior_scale=0.2)
  314. m.add_regressor('numeric_feature', prior_scale=0.5)
  315. m.add_regressor('binary_feature2', standardize=True)
  316. df = DATA.copy()
  317. df['binary_feature'] = [0] * 255 + [1] * 255
  318. df['numeric_feature'] = range(510)
  319. with self.assertRaises(ValueError):
  320. # Require all regressors in df
  321. m.fit(df)
  322. df['binary_feature2'] = [1] * 100 + [0] * 410
  323. m.fit(df)
  324. # Check that standardizations are correctly set
  325. self.assertEqual(
  326. m.extra_regressors['binary_feature'],
  327. {'prior_scale': 0.2, 'mu': 0, 'std': 1, 'standardize': 'auto'},
  328. )
  329. self.assertEqual(
  330. m.extra_regressors['numeric_feature']['prior_scale'], 0.5)
  331. self.assertEqual(
  332. m.extra_regressors['numeric_feature']['mu'], 254.5)
  333. self.assertAlmostEqual(
  334. m.extra_regressors['numeric_feature']['std'], 147.368585, places=5)
  335. self.assertEqual(
  336. m.extra_regressors['binary_feature2']['prior_scale'], 10.)
  337. self.assertAlmostEqual(
  338. m.extra_regressors['binary_feature2']['mu'], 0.1960784, places=5)
  339. self.assertAlmostEqual(
  340. m.extra_regressors['binary_feature2']['std'], 0.3974183, places=5)
  341. # Check that standardization is done correctly
  342. df2 = m.setup_dataframe(df.copy())
  343. self.assertEqual(df2['binary_feature'][0], 0)
  344. self.assertAlmostEqual(df2['numeric_feature'][0], -1.726962, places=4)
  345. self.assertAlmostEqual(df2['binary_feature2'][0], 2.022859, places=4)
  346. # Check that feature matrix and prior scales are correctly constructed
  347. seasonal_features, prior_scales = m.make_all_seasonality_features(df2)
  348. self.assertIn('binary_feature', seasonal_features)
  349. self.assertIn('numeric_feature', seasonal_features)
  350. self.assertIn('binary_feature2', seasonal_features)
  351. self.assertEqual(seasonal_features.shape[1], 29)
  352. self.assertEqual(set(prior_scales[26:]), set([0.2, 0.5, 10.]))
  353. # Check that forecast components are reasonable
  354. future = pd.DataFrame({
  355. 'ds': ['2014-06-01'],
  356. 'binary_feature': [0],
  357. 'numeric_feature': [10],
  358. })
  359. with self.assertRaises(ValueError):
  360. m.predict(future)
  361. future['binary_feature2'] = 0
  362. fcst = m.predict(future)
  363. self.assertEqual(fcst.shape[1], 31)
  364. self.assertEqual(fcst['binary_feature'][0], 0)
  365. self.assertEqual(
  366. fcst['extra_regressors'][0],
  367. fcst['numeric_feature'][0] + fcst['binary_feature2'][0],
  368. )
  369. self.assertEqual(
  370. fcst['seasonalities'][0],
  371. fcst['yearly'][0] + fcst['weekly'][0],
  372. )
  373. self.assertEqual(
  374. fcst['seasonal'][0],
  375. fcst['seasonalities'][0] + fcst['extra_regressors'][0],
  376. )
  377. self.assertEqual(
  378. fcst['yhat'][0],
  379. fcst['trend'][0] + fcst['seasonal'][0],
  380. )
  381. def test_copy(self):
  382. # These values are created except for its default values
  383. products = itertools.product(
  384. ['linear', 'logistic'], # growth
  385. [None, pd.to_datetime(['2016-12-25'])], # changepoints
  386. [3], # n_changepoints
  387. [True, False], # yearly_seasonality
  388. [True, False], # weekly_seasonality
  389. [True, False], # daily_seasonality
  390. [None, pd.DataFrame({'ds': pd.to_datetime(['2016-12-25']), 'holiday': ['x']})], # holidays
  391. [1.1], # seasonality_prior_scale
  392. [1.1], # holidays_prior_scale
  393. [0.1], # changepoint_prior_scale
  394. [100], # mcmc_samples
  395. [0.9], # interval_width
  396. [200] # uncertainty_samples
  397. )
  398. # Values should be copied correctly
  399. for product in products:
  400. m1 = Prophet(*product)
  401. m2 = m1.copy()
  402. self.assertEqual(m1.growth, m2.growth)
  403. self.assertEqual(m1.n_changepoints, m2.n_changepoints)
  404. self.assertEqual(m1.changepoints, m2.changepoints)
  405. self.assertEqual(m1.yearly_seasonality, m2.yearly_seasonality)
  406. self.assertEqual(m1.weekly_seasonality, m2.weekly_seasonality)
  407. self.assertEqual(m1.daily_seasonality, m2.daily_seasonality)
  408. if m1.holidays is None:
  409. self.assertEqual(m1.holidays, m2.holidays)
  410. else:
  411. self.assertTrue((m1.holidays == m2.holidays).values.all())
  412. self.assertEqual(m1.seasonality_prior_scale, m2.seasonality_prior_scale)
  413. self.assertEqual(m1.changepoint_prior_scale, m2.changepoint_prior_scale)
  414. self.assertEqual(m1.holidays_prior_scale, m2.holidays_prior_scale)
  415. self.assertEqual(m1.mcmc_samples, m2.mcmc_samples)
  416. self.assertEqual(m1.interval_width, m2.interval_width)
  417. self.assertEqual(m1.uncertainty_samples, m2.uncertainty_samples)
  418. # Check for cutoff
  419. changepoints = pd.date_range('2016-12-15', '2017-01-15')
  420. cutoff = pd.Timestamp('2016-12-25')
  421. m1 = Prophet(changepoints=changepoints)
  422. m2 = m1.copy(cutoff=cutoff)
  423. changepoints = changepoints[changepoints <= cutoff]
  424. self.assertTrue((changepoints == m2.changepoints).all())