test_prophet.py 22 KB

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