test_prophet.py 23 KB

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