使用python GluonTS库做概率预测

167 篇文章 5 订阅
28 篇文章 2 订阅
本文介绍了如何利用GluonTS工具包进行时间序列预测。通过核心代码展示了一个简单的全连接网络模型(SimpleFeedForwardEstimator)的训练过程,以及如何将训练结果用于测试数据并进行预测。最后,提供了绘制预测结果的函数,以图形方式展示预测的中位数及置信区间。尽管由于随机性预测效果可能不佳,但该文详细阐述了GluonTS的使用流程。
摘要由CSDN通过智能技术生成

文章目录

工具包

使用GluonTS工具包,主页:https://ts.gluon.ai/
github页面:https://github.com/awslabs/gluon-ts/

使用代码

非官方代码,是我学习时测试的代码,并且尽可能标注了注释:

核心代码:

import pandas as pd
import matplotlib.pyplot as plt
from gluonts.dataset.common import ListDataset
from gluonts.mx.trainer import Trainer
from gluonts.model.simple_feedforward import SimpleFeedForwardEstimator
from gluonts.evaluation.backtest import make_evaluation_predictions

def probabilistic_predict(train_se: pd.Series, test_se: pd.Series, freq):
    training_data = ListDataset(  # 使用这个工具包需要把数据格式转换为这种类型
        [
            {
                "start": train_se.index[0],  # 训练集的起始日期
                "target": train_se,
            }
        ],
        freq=freq,
    )
    test_data = ListDataset(
        [
            {
                "start": train_se.index[0],  # 测试集的起始日期
                "target": pd.concat([train_se, test_se]),  # 注意这里是训练集+测试集
            }
        ],
        freq=freq,
    )
    prediction_length = len(test_se)
    estimator = SimpleFeedForwardEstimator(  # 构造训练器
        num_hidden_dimensions=[100],
        prediction_length=prediction_length,
        context_length=100,
        freq=freq,
        trainer=Trainer(epochs=10,
                        learning_rate=1e-3,
                        num_batches_per_epoch=100)
    )
    predictor = estimator.train(training_data)  # 开始训练
    forecast_it, ts_it = make_evaluation_predictions(  # 用测试集测试训练的效果
        dataset=test_data,  # test dataset
        predictor=predictor,  # predictor
        num_samples=100,  # number of sample paths we want for evaluation
    )
    tss = list(ts_it)
    ts_entry = tss[0]
    forecasts = list(forecast_it)
    forecast_entry = forecasts[0]
    return ts_entry, forecast_entry

绘图函数:

def plot_prob_forecasts(ts_entry, forecast_entry):  # 绘图
    plot_length = 100  # 绘制多少个点
    prediction_intervals = (50.0, 90.0)
    legend = ["observations", "median prediction"] + [f"{k}% prediction interval" for k in prediction_intervals][::-1]

    fig, ax = plt.subplots(1, 1, figsize=(20, 10))
    ts_entry[-plot_length:].plot(ax=ax)  # plot the time series
    forecast_entry.plot(prediction_intervals=prediction_intervals, color='g')
    plt.grid(which="both")
    plt.legend(legend, loc="upper left")
    plt.savefig('save_fig.png')
    plt.show()

使用:

if __name__ == '__main__':
    import numpy as np

	# 生成从2021.01.01至2021.12.30共365天的数据,模拟时间序列
    time_df = pd.DataFrame(np.random.randint(0, 10, size=(365, 1)), columns=['data'],
                           index=pd.date_range('2021-01-01', periods=365, freq='D'))
	# 把1.1至10.31当做训练集,11.1至12.30当做测试集
    train = time_df.truncate(after='2021-10-31').iloc[:, 0]
    test = time_df.truncate(before='2021-11-01').iloc[:, 0]
    ts_entry, forecast_entry = probabilistic_predict(train, test, freq='D') # 预测
    plot_prob_forecasts(ts_entry, forecast_entry) # 绘图

绘制出的效果图如下:
在这里插入图片描述
由于是随机数,因此可预测性并不高,效果自然不会太好。

  • 4
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

呆萌的代Ma

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值