diagnostics.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  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 logging
  12. logger = logging.getLogger(__name__)
  13. import numpy as np
  14. import pandas as pd
  15. from functools import reduce
  16. def _cutoffs(df, horizon, k, period):
  17. """Generate cutoff dates
  18. Parameters
  19. ----------
  20. df: pd.DataFrame with historical data
  21. horizon: pd.Timedelta.
  22. Forecast horizon
  23. k: Int number.
  24. The number of forecasts point.
  25. period: pd.Timedelta.
  26. Simulated Forecast will be done at every this period.
  27. Returns
  28. -------
  29. list of pd.Timestamp
  30. """
  31. # Last cutoff is 'latest date in data - horizon' date
  32. cutoff = df['ds'].max() - horizon
  33. if cutoff < df['ds'].min():
  34. raise ValueError('Less data than horizon.')
  35. result = [cutoff]
  36. for i in range(1, k):
  37. cutoff -= period
  38. # If data does not exist in data range (cutoff, cutoff + horizon]
  39. if not (((df['ds'] > cutoff) & (df['ds'] <= cutoff + horizon)).any()):
  40. # Next cutoff point is 'closest date before cutoff in data - horizon'
  41. closest_date = df[df['ds'] <= cutoff].max()['ds']
  42. cutoff = closest_date - horizon
  43. if cutoff < df['ds'].min():
  44. logger.warning('Not enough data for requested number of cutoffs! Using {}.'.format(i))
  45. break
  46. result.append(cutoff)
  47. # Sort lines in ascending order
  48. return reversed(result)
  49. def simulated_historical_forecasts(model, horizon, k, period=None):
  50. """Simulated Historical Forecasts.
  51. If you would like to know it in detail, read the original paper
  52. https://facebookincubator.github.io/prophet/static/prophet_paper_20170113.pdf
  53. Parameters
  54. ----------
  55. model: Prophet class object.
  56. Fitted Prophet model
  57. horizon: string which has pd.Timedelta compatible style.
  58. Forecast horizon ('5 days', '3 hours', '10 seconds' etc)
  59. k: Int number.
  60. The number of forecasts point.
  61. period: string which has pd.Timedelta compatible style or None, default None.
  62. Simulated Forecast will be done at every this period.
  63. 0.5 * horizon is used when it is None.
  64. Returns
  65. -------
  66. A pd.DataFrame with the forecast, actual value and cutoff.
  67. """
  68. df = model.history.copy().reset_index(drop=True)
  69. horizon = pd.Timedelta(horizon)
  70. period = 0.5 * horizon if period is None else pd.Timedelta(period)
  71. cutoffs = _cutoffs(df, horizon, k, period)
  72. predicts = []
  73. for cutoff in cutoffs:
  74. # Generate new object with copying fitting options
  75. m = model.copy(cutoff)
  76. # Train model
  77. m.fit(df[df['ds'] <= cutoff])
  78. # Calculate yhat
  79. index_predicted = (df['ds'] > cutoff) & (df['ds'] <= cutoff + horizon)
  80. columns = ['ds'] + (['cap'] if m.growth == 'logistic' else [])
  81. yhat = m.predict(df[index_predicted][columns])
  82. # Merge yhat(predicts), y(df, original data) and cutoff
  83. predicts.append(pd.concat([
  84. yhat[['ds', 'yhat', 'yhat_lower', 'yhat_upper']],
  85. df[index_predicted][['y']].reset_index(drop=True),
  86. pd.DataFrame({'cutoff': [cutoff] * len(yhat)})
  87. ], axis=1))
  88. # Combine all predicted pd.DataFrame into one pd.DataFrame
  89. return reduce(lambda x, y: x.append(y), predicts).reset_index(drop=True)
  90. def cross_validation(model, horizon, period, initial=None):
  91. """Cross-Validation for time-series.
  92. This function is the same with Time series cross-validation described in https://robjhyndman.com/hyndsight/tscv/
  93. when the value of period is equal to the time interval of data.
  94. Parameters
  95. ----------
  96. model: Prophet class object. Fitted Prophet model
  97. horizon: string which has pd.Timedelta compatible style.
  98. Forecast horizon ('5 days', '3 hours', '10 seconds' etc)
  99. period: string which has pd.Timedelta compatible style.
  100. Simulated Forecast will be done at every this period.
  101. initial: string which has pd.Timedelta compatible style or None, default None.
  102. First training period.
  103. 3 * horizon is used when it is None.
  104. Returns
  105. -------
  106. A pd.DataFrame with the forecast, actual value and cutoff.
  107. """
  108. te = model.history['ds'].max()
  109. ts = model.history['ds'].min()
  110. horizon = pd.Timedelta(horizon)
  111. period = pd.Timedelta(period)
  112. initial = 3 * horizon if initial is None else pd.Timedelta(initial)
  113. k = int(np.ceil(((te - horizon) - (ts + initial)) / period))
  114. if k < 1:
  115. raise ValueError('Not enough data for specified horizon and initial.')
  116. return simulated_historical_forecasts(model, horizon, k, period)