欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

简单却好用:使用Keras 2实现基于LSTM的多维时间序列预测

程序员文章站 2023-04-03 07:54:14
朋友们好,时隔很久我又开始写时间序列相关的博客啦。本次博客的主题是:提供一种适用于初中级学者的时间序列预测模型并且十分的有效好用数据介绍该数据集是一个污染数据集,我们需要用该多维时间序列去预测pollution这个维度,采用80%作为训练集,20%作为测试集。模型实现模型使用双层LSTM加一个全连接层实现预测具体结构如下def trainModel(trainX,trainY,config): ''' trainX,trainY: 训练LSTM模型所需要的数据 p...

朋友们好,时隔很久我又开始写时间序列相关的博客啦。

新年新气象,过去的时间序列预测博客采用版本为Keras 2.2 tensorflow-gpu 1.13.1版本实现。

本次博客的主题是:
提供一种适用于新手LSTM时间序列预测模型
十分的有效好用
同时采用Keras 2 + TensorFlow 2 实现,提供预测和验证全流程。

版本:
cuda 10.1
cudnn 8.0.5
keras 2.4.3
tensorflow-gpu 2.3.0

Keras 2.4版本仅支持TensorFlow 作为后端,参见 Keras 2.4发布,真正成为TensorFlow的Keras ,import 相比之前版本也有一些改动。

数据介绍

该数据集是一个污染数据集,我们需要用该多维时间序列去预测pollution这个维度,采用80%作为训练集,20%作为测试集。
简单却好用:使用Keras 2实现基于LSTM的多维时间序列预测

开始

深度学习的第一步

import tensorflow as tf

相对于旧版本keras 这里有一些改动

from  tensorflow.keras import Sequential
from  tensorflow.keras.layers import LSTM,Dense,Activation,Dropout
from  tensorflow.keras.callbacks import History,Callback,EarlyStopping
import  numpy as np

模型实现

模型使用最简单的序贯模型,
使用双层LSTM加一个全连接层实现预测
具体结构如下

然后还添加了一个early stopping 机制


def lstm_model(train_x,train_y,config):

    model = Sequential()
    model.add(LSTM(config.lstm_layers[0],input_shape=(train_x.shape[1],train_x.shape[2]),
                   return_sequences=True))
    model.add(Dropout(config.dropout))

    model.add(LSTM(
        config.lstm_layers[1],
        return_sequences=False))
    model.add(Dropout(config.dropout))

    model.add(Dense(
        train_y.shape[1]))
    model.add(Activation("relu"))

    model.summary()

    cbs = [History(), EarlyStopping(monitor='val_loss',
                                    patience=config.patience,
                                    min_delta=config.min_delta,
                                    verbose=0)]
    model.compile(loss=config.loss_metric,optimizer=config.optimizer)
    model.fit(train_x,
                   train_y,
                   batch_size=config.lstm_batch_size,
                   epochs=config.epochs,
                   validation_split=config.validation_split,
                   callbacks=cbs,
                   verbose=True)
    return model

同时具体模型的输入输出是根据train_x和 train_y的shape来设置的。所以这是一个自适应的模型 。
只要确保train_x的维度为3,train_y的维度为2,就能流畅运行。

具体参数

#使用类实现一个配置文件
class Config:
    def __init__(self):
        self.path = './Model/'
        self.dimname = 'pollution'

        #使用前n_predictions 步去预测下一步
        self.n_predictions = 30

        #指定EarlyStopping  如果训练时单次val_loss值不能至少减少min_delta时,最多允许再训练patience次
        #能够容忍多少个epoch内都没有improvement
        self.patience = 10
        self.min_delta = 0.00001

        #指定LSTM两层的神经元个数
        self.lstm_layers = [80,80]
        self.dropout = 0.2

        self.lstm_batch_size = 64
        self.optimizer = 'adam'
        self.loss_metric = 'mse'
        self.validation_split = 0.2
        self.verbose = 1
        self.epochs = 200

    ## 是一个数组 如[64,64]
    def change_lstm_layers(self,layers):
        self.lstm_layers = layers

模型结构如图
简单却好用:使用Keras 2实现基于LSTM的多维时间序列预测
由于采用了Early Stopping机制 训练28次就结束了
Epoch 28/200
438/438 [==============================] - 10s 23ms/step - loss: 8.4697e-04 - val_loss: 4.9450e-04

结果

让我们来看看结果吧
RMSE为 24.096020043963737
MAE为 13.384563587562422
MAPE为 25.183164455025054
简单却好用:使用Keras 2实现基于LSTM的多维时间序列预测

简单却好用:使用Keras 2实现基于LSTM的多维时间序列预测

可以看到我们这个方法虽然简单,但是预测效果是很好的~

本代码已经上传到了我的github

同时还附录了本教程的旧版本(梯度搜索部分可能有点小bug 如果使用需要仔细校对一下)

如果本文点赞过1000或者github 本项目 star 过100
我就开源 登堂入室LSTM:使用LSTM进行简单的时间序列异常检测
的新版本 更优实现。

参考

tensorflow2_tutorials_chinese

Anomaly Detection in Time Series Data Using LSTMs and Automatic Thresholding

本文地址:https://blog.csdn.net/qq_35649669/article/details/112169863