diagnostics.py 4.8 KB

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