Python实现DeepAR单变量多步预测以及误差分析和可视化代码
时间: 2024-02-18 13:00:05 浏览: 133
以下是Python实现DeepAR单变量多步预测的代码,包括误差分析和可视化:
```
# 导入必要的包
import numpy as np
import pandas as pd
import mxnet as mx
from mxnet import gluon, autograd, init
from mxnet.gluon import nn, rnn
from gluonts.dataset.common import ListDataset
from gluonts.model.deepar import DeepAREstimator
from gluonts.trainer import Trainer
from gluonts.evaluation.backtest import make_evaluation_predictions
from gluonts.evaluation import Evaluator
# 加载数据
df = pd.read_csv('data.csv')
df['Date'] = pd.to_datetime(df['Date'])
df = df.set_index('Date')
df = df.resample('D').sum()
train_data = ListDataset([{
'target': df.iloc[:'2020-12-31', 0].values.tolist()
}], freq='D')
test_data = ListDataset([{
'target': df.iloc['2021-01-01':, 0].values.tolist()
}], freq='D')
# 定义模型
estimator = DeepAREstimator(
freq="D",
prediction_length=7,
trainer=Trainer(
ctx="cpu",
epochs=10,
learning_rate=1e-3,
batch_size=32
)
)
# 训练模型
predictor = estimator.train(train_data=train_data)
# 预测结果
forecast_it, ts_it = make_evaluation_predictions(
dataset=test_data,
predictor=predictor,
num_samples=100
)
forecasts = list(forecast_it)
tss = list(ts_it)
# 误差分析
evaluator = Evaluator()
agg_metrics, item_metrics = evaluator(iter(tss), iter(forecasts), num_series=len(df.columns))
print(agg_metrics)
# 结果可视化
from gluonts.dataset.util import to_pandas
import matplotlib.pyplot as plt
ts_entry = next(iter(tss))
test_entry = next(iter(test_data))
forecast_entry = next(iter(forecasts))
plt.plot(to_pandas(ts_entry)[-30:], label='historical truth')
plt.plot(to_pandas(test_entry['target'])[:7], label='forecast target')
plt.plot(to_pandas(forecast_entry.mean)[-7:], label='forecast')
plt.fill_between(
forecast_entry.index[-7:],
forecast_entry.quantile(0.1)[-7:],
forecast_entry.quantile(0.9)[-7:],
alpha=0.2,
label='90% confidence interval'
)
plt.legend()
plt.show()
```
上述代码中,我们首先加载数据,然后定义了一个DeepAR模型,使用训练集训练模型,使用测试集进行预测,并进行误差分析和可视化。在可视化部分,我们将历史真实值、预测目标和预测结果绘制在同一张图上,并加入了90%置信区间。
阅读全文