GluonTS 快速预测时间序列

目录

头文件

1、定义数据集

2、构建简单前馈网络(MLP)进行预测

3、训练完成之后对测试数据预测进行评估

4、对结果进行画图展示

5、训练代码


 

头文件

import mxnet as mx
from mxnet import gluon
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import json
from gluonts.dataset.common import ListDataset

1、定义数据集

定义一个样本数量为10,每个样本有100个时间序列的数据集,数据集预测的长度是后24个数值

N = 10  # number of time series
T = 100  # number of timesteps
prediction_length = 24
freq = "1H"
custom_dataset = np.random.normal(size=(N, T))
start = pd.Timestamp("01-01-2019", freq=freq)  # can be different for each time series

注释:start表示这个时间序列开始的时间,freq表示时间按照这个时间长度进行不断累加(相当于等差数列)

2、构建简单前馈网络(MLP)进行预测

这里构建输入为(100-24),两层隐藏层(40, 40),输出层为24

def creat_SFFEstimator():
    from gluonts.model.simple_feedforward import SimpleFeedForwardEstimator
    from gluonts.trainer import Trainer

    estimator = SimpleFeedForwardEstimator(
        num_hidden_dimensions=[40, 40],
        prediction_length=prediction_length,
        context_length=100,
        freq=freq,
        trainer=Trainer(ctx="cpu",
                        epochs=5,
                        learning_rate=1e-3,
                        num_batches_per_epoch=1
                        ),
    )
    # 使用构建的Estimator(可自定义),在训练集上训练
    predictor = estimator.train(train_ds)
    return predictor

3、训练完成之后对测试数据预测进行评估

def evaluation(predictor):
    from gluonts.evaluation.backtest import make_evaluation_predictions
    from gluonts.evaluation import Evaluator

    forecast_it, ts_it = make_evaluation_predictions(
        dataset=test_ds,  # test dataset
        predictor=predictor,  # predictor
        num_samples=10,  # number of sample paths we want for evaluation
    )
    forecasts = list(forecast_it)
    tss = list(ts_it)

    ts_entry = tss[0]
    forecast_entry = forecasts[0]

    evaluator = Evaluator(quantiles=[0.1, 0.5, 0.9])
    agg_metrics, item_metrics = evaluator(iter(tss), iter(forecasts), num_series=len(test_ds))
    print (agg_metrics)

    return forecast_entry, ts_entry

4、对结果进行画图展示

def plot_prob_forecasts(forecast_entry, ts_entry):
    plot_length = 48
    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=(10, 7))
    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.show()

5、训练代码

def unconstom_train():
    # 创建
    predictor = creat_SFFEstimator()
    # 评估、预测
    forecast_entry, ts_entry = evaluation(predictor)
    # 展示
    plot_prob_forecasts(forecast_entry, ts_entry)

unconstom_train()

实验结果

GluonTS 快速预测时间序列_第1张图片

你可能感兴趣的:(Time,Series,Prediction,时间序列预测)