时间序列预测:解决预测结果日期索引错误问题
时间序列预测:解决预测结果日期索引错误问题
在使用 Statsmodels 进行时间序列预测时,你可能会遇到预测结果的日期索引显示为 '1970-01-01' 的问题。这通常是由于数据的时间戳格式或索引设置不正确导致的。
本文将提供一个解决方案,帮助你设置正确的日期索引,并展示如何将修改后的预测结果输出到终端。
问题描述
当你运行时间序列预测代码时,你可能会在输出中看到类似以下内容的警告信息:
D:\Python\Python311\Lib\site-packages\statsmodels\tsa\base\tsa_model.py:473: ValueWarning: An unsupported index was provided and will be ignored when e.g. forecasting. self._init_dates(dates, freq)D:\Python\Python311\Lib\site-packages\statsmodels\tsa\base\tsa_model.py:836: ValueWarning: No supported index is available. Prediction results will be given with an integer index beginning at start. return get_prediction_index(D:\Python\Python311\Lib\site-packages\statsmodels\tsa\base\tsa_model.py:836: FutureWarning: No supported index is available. In the next version, calling this method in a model without a supported index will result in an exception. return get_prediction_index(
这些警告信息表明 Statsmodels 无法识别你数据中的时间索引。因此,预测结果的日期索引会默认为 '1970-01-01' 开始。
解决方案
要解决这个问题,你需要在预测结果生成之前,使用 pandas 库中的 date_range 函数设置正确的日期索引。
以下是代码示例:pythonimport pandas as pd
...你的时间序列预测代码...
假设你已经获得了预测结果 forecast_mean 和 forecast_conf_int
设置预测结果的日期索引forecast_dates = pd.date_range(start=data.index[-1], periods=len(forecast_mean))forecast_mean.index = forecast_datesforecast_conf_int.index = forecast_dates
输出修改后的预测结果print(forecast_mean)print(forecast_conf_int)
在这段代码中:
data是你的原始时间序列数据。*forecast_mean是你的预测结果均值。*forecast_conf_int是你的预测结果置信区间。
我们使用 pd.date_range 函数创建了一个从原始数据最后一个日期开始的日期范围,并将其分配给 forecast_dates。然后,我们将 forecast_mean 和 forecast_conf_int 的索引设置为 forecast_dates,从而确保预测结果具有正确的日期索引。
总结
通过使用 pandas 库中的 date_range 函数,你可以轻松解决时间序列预测中出现的预测结果日期索引错误问题。请记住在生成预测结果之前设置正确的日期索引,以确保你的分析结果准确可靠。
原文地址: https://www.cveoy.top/t/topic/b7Xd 著作权归作者所有。请勿转载和采集!