test_prophet.py 20 KB

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