test_prophet.py 22 KB

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