test_diagnostics.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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. from fbprophet import diagnostics
  19. DATA_all = pd.read_csv(
  20. os.path.join(os.path.dirname(__file__), 'data.csv'), parse_dates=['ds']
  21. )
  22. DATA = DATA_all.head(100)
  23. # fb-block 1 end
  24. # fb-block 2
  25. class TestDiagnostics(TestCase):
  26. def __init__(self, *args, **kwargs):
  27. super(TestDiagnostics, self).__init__(*args, **kwargs)
  28. # Use first 100 record in data.csv
  29. self.__df = DATA
  30. def test_simulated_historical_forecasts(self):
  31. m = Prophet()
  32. m.fit(self.__df)
  33. k = 2
  34. for p in [1, 10]:
  35. for h in [1, 3]:
  36. period = '{} days'.format(p)
  37. horizon = '{} days'.format(h)
  38. df_shf = diagnostics.simulated_historical_forecasts(
  39. m, horizon=horizon, k=k, period=period)
  40. # All cutoff dates should be less than ds dates
  41. self.assertTrue((df_shf['cutoff'] < df_shf['ds']).all())
  42. # The unique size of output cutoff should be equal to 'k'
  43. self.assertEqual(len(np.unique(df_shf['cutoff'])), k)
  44. self.assertEqual(
  45. max(df_shf['ds'] - df_shf['cutoff']),
  46. pd.Timedelta(horizon),
  47. )
  48. dc = df_shf['cutoff'].diff()
  49. dc = dc[dc > pd.Timedelta(0)].min()
  50. self.assertTrue(dc >= pd.Timedelta(period))
  51. # Each y in df_shf and self.__df with same ds should be equal
  52. df_merged = pd.merge(df_shf, self.__df, 'left', on='ds')
  53. self.assertAlmostEqual(
  54. np.sum((df_merged['y_x'] - df_merged['y_y']) ** 2), 0.0)
  55. def test_simulated_historical_forecasts_logistic(self):
  56. m = Prophet(growth='logistic')
  57. df = self.__df.copy()
  58. df['cap'] = 40
  59. m.fit(df)
  60. df_shf = diagnostics.simulated_historical_forecasts(
  61. m, horizon='3 days', k=2, period='3 days')
  62. # All cutoff dates should be less than ds dates
  63. self.assertTrue((df_shf['cutoff'] < df_shf['ds']).all())
  64. # The unique size of output cutoff should be equal to 'k'
  65. self.assertEqual(len(np.unique(df_shf['cutoff'])), 2)
  66. # Each y in df_shf and self.__df with same ds should be equal
  67. df_merged = pd.merge(df_shf, df, 'left', on='ds')
  68. self.assertAlmostEqual(
  69. np.sum((df_merged['y_x'] - df_merged['y_y']) ** 2), 0.0)
  70. def test_simulated_historical_forecasts_extra_regressors(self):
  71. m = Prophet()
  72. m.add_seasonality(name='monthly', period=30.5, fourier_order=5)
  73. m.add_regressor('extra')
  74. df = self.__df.copy()
  75. df['cap'] = 40
  76. df['extra'] = range(df.shape[0])
  77. m.fit(df)
  78. df_shf = diagnostics.simulated_historical_forecasts(
  79. m, horizon='3 days', k=2, period='3 days')
  80. # All cutoff dates should be less than ds dates
  81. self.assertTrue((df_shf['cutoff'] < df_shf['ds']).all())
  82. # The unique size of output cutoff should be equal to 'k'
  83. self.assertEqual(len(np.unique(df_shf['cutoff'])), 2)
  84. # Each y in df_shf and self.__df with same ds should be equal
  85. df_merged = pd.merge(df_shf, df, 'left', on='ds')
  86. self.assertAlmostEqual(
  87. np.sum((df_merged['y_x'] - df_merged['y_y']) ** 2), 0.0)
  88. def test_simulated_historical_forecasts_default_value_check(self):
  89. m = Prophet()
  90. m.fit(self.__df)
  91. # Default value of period should be equal to 0.5 * horizon
  92. df_shf1 = diagnostics.simulated_historical_forecasts(
  93. m, horizon='10 days', k=1)
  94. df_shf2 = diagnostics.simulated_historical_forecasts(
  95. m, horizon='10 days', k=1, period='5 days')
  96. self.assertAlmostEqual(
  97. ((df_shf1['y'] - df_shf2['y']) ** 2).sum(), 0.0)
  98. self.assertAlmostEqual(
  99. ((df_shf1['yhat'] - df_shf2['yhat']) ** 2).sum(), 0.0)
  100. def test_cross_validation(self):
  101. m = Prophet()
  102. m.fit(self.__df)
  103. # Calculate the number of cutoff points(k)
  104. horizon = pd.Timedelta('4 days')
  105. period = pd.Timedelta('10 days')
  106. k = 5
  107. df_cv = diagnostics.cross_validation(
  108. m, horizon='4 days', period='10 days', initial='90 days')
  109. # The unique size of output cutoff should be equal to 'k'
  110. self.assertEqual(len(np.unique(df_cv['cutoff'])), k)
  111. self.assertEqual(max(df_cv['ds'] - df_cv['cutoff']), horizon)
  112. dc = df_cv['cutoff'].diff()
  113. dc = dc[dc > pd.Timedelta(0)].min()
  114. self.assertTrue(dc >= period)
  115. def test_cross_validation_default_value_check(self):
  116. m = Prophet()
  117. m.fit(self.__df)
  118. # Default value of initial should be equal to 3 * horizon
  119. df_cv1 = diagnostics.cross_validation(
  120. m, horizon='32 days', period='10 days')
  121. df_cv2 = diagnostics.cross_validation(
  122. m, horizon='32 days', period='10 days', initial='96 days')
  123. self.assertAlmostEqual(
  124. ((df_cv1['y'] - df_cv2['y']) ** 2).sum(), 0.0)
  125. self.assertAlmostEqual(
  126. ((df_cv1['yhat'] - df_cv2['yhat']) ** 2).sum(), 0.0)
  127. def test_performance_metrics(self):
  128. m = Prophet()
  129. m.fit(self.__df)
  130. df_cv = diagnostics.cross_validation(
  131. m, horizon='4 days', period='10 days', initial='90 days')
  132. # Aggregation level none
  133. df_none = diagnostics.performance_metrics(df_cv, rolling_window=0)
  134. self.assertEqual(
  135. set(df_none.columns),
  136. {'horizon', 'coverage', 'mae', 'mape', 'mse', 'rmse'},
  137. )
  138. self.assertEqual(df_none.shape[0], 14)
  139. # Aggregation level 0.2
  140. df_horizon = diagnostics.performance_metrics(df_cv, rolling_window=0.2)
  141. self.assertEqual(len(df_horizon['horizon'].unique()), 4)
  142. self.assertEqual(df_horizon.shape[0], 13)
  143. # Aggregation level all
  144. df_all = diagnostics.performance_metrics(df_cv, rolling_window=1)
  145. self.assertEqual(df_all.shape[0], 1)
  146. for metric in ['mse', 'mape', 'mae', 'coverage']:
  147. self.assertEqual(df_all[metric].values[0], df_none[metric].mean())
  148. # Custom list of metrics
  149. df_horizon = diagnostics.performance_metrics(
  150. df_cv, metrics=['coverage', 'mse'],
  151. )
  152. self.assertEqual(
  153. set(df_horizon.columns),
  154. {'coverage', 'mse', 'horizon'},
  155. )
  156. def test_copy(self):
  157. df = DATA_all.copy()
  158. df['cap'] = 200.
  159. df['binary_feature'] = [0] * 255 + [1] * 255
  160. # These values are created except for its default values
  161. holiday = pd.DataFrame(
  162. {'ds': pd.to_datetime(['2016-12-25']), 'holiday': ['x']})
  163. products = itertools.product(
  164. ['linear', 'logistic'], # growth
  165. [None, pd.to_datetime(['2016-12-25'])], # changepoints
  166. [3], # n_changepoints
  167. [0.9], # changepoint_range
  168. [True, False], # yearly_seasonality
  169. [True, False], # weekly_seasonality
  170. [True, False], # daily_seasonality
  171. [None, holiday], # holidays
  172. ['additive', 'multiplicative'], # seasonality_mode
  173. [1.1], # seasonality_prior_scale
  174. [1.1], # holidays_prior_scale
  175. [0.1], # changepoint_prior_scale
  176. [100], # mcmc_samples
  177. [0.9], # interval_width
  178. [200] # uncertainty_samples
  179. )
  180. # Values should be copied correctly
  181. for product in products:
  182. m1 = Prophet(*product)
  183. m1.history = m1.setup_dataframe(
  184. df.copy(), initialize_scales=True)
  185. m1.set_auto_seasonalities()
  186. m2 = diagnostics.prophet_copy(m1)
  187. self.assertEqual(m1.growth, m2.growth)
  188. self.assertEqual(m1.n_changepoints, m2.n_changepoints)
  189. self.assertEqual(m1.changepoint_range, m2.changepoint_range)
  190. self.assertEqual(m1.changepoints, m2.changepoints)
  191. self.assertEqual(False, m2.yearly_seasonality)
  192. self.assertEqual(False, m2.weekly_seasonality)
  193. self.assertEqual(False, m2.daily_seasonality)
  194. self.assertEqual(
  195. m1.yearly_seasonality, 'yearly' in m2.seasonalities)
  196. self.assertEqual(
  197. m1.weekly_seasonality, 'weekly' in m2.seasonalities)
  198. self.assertEqual(
  199. m1.daily_seasonality, 'daily' in m2.seasonalities)
  200. if m1.holidays is None:
  201. self.assertEqual(m1.holidays, m2.holidays)
  202. else:
  203. self.assertTrue((m1.holidays == m2.holidays).values.all())
  204. self.assertEqual(m1.seasonality_mode, m2.seasonality_mode)
  205. self.assertEqual(m1.seasonality_prior_scale, m2.seasonality_prior_scale)
  206. self.assertEqual(m1.changepoint_prior_scale, m2.changepoint_prior_scale)
  207. self.assertEqual(m1.holidays_prior_scale, m2.holidays_prior_scale)
  208. self.assertEqual(m1.mcmc_samples, m2.mcmc_samples)
  209. self.assertEqual(m1.interval_width, m2.interval_width)
  210. self.assertEqual(m1.uncertainty_samples, m2.uncertainty_samples)
  211. # Check for cutoff and custom seasonality and extra regressors
  212. changepoints = pd.date_range('2012-06-15', '2012-09-15')
  213. cutoff = pd.Timestamp('2012-07-25')
  214. m1 = Prophet(changepoints=changepoints)
  215. m1.add_seasonality('custom', 10, 5)
  216. m1.add_regressor('binary_feature')
  217. m1.fit(df)
  218. m2 = diagnostics.prophet_copy(m1, cutoff=cutoff)
  219. changepoints = changepoints[changepoints <= cutoff]
  220. self.assertTrue((changepoints == m2.changepoints).all())
  221. self.assertTrue('custom' in m2.seasonalities)
  222. self.assertTrue('binary_feature' in m2.extra_regressors)