时间序列预测 | Python实现GRU时间序列数据预测

41 篇文章 229 订阅 ¥29.90 ¥99.00
25 篇文章 226 订阅 ¥29.90 ¥99.00

GRU门控循环单元

GRU(Gate Recurrent Unit)是循环神经网络(Recurrent Neural Network, RNN)的一种。和LSTM(Long-Short Term Memory)一样,也是为了解决长期记忆和反向传播中的梯度等问题而提出来的。
相比LSTM,使用GRU能够达到相当的效果,并且相比之下更容易进行训练,能够很大程度上提高训练效率,因此很多时候会更倾向于使用GRU。

1

GRU原理

  • 首先,我们先通过上一个传输下来的状态和当前节点的输入来获取两个门控状态。如下图所示。
    1
  • 与LSTM分明的层次结构不同,得到门控信号之后,首先使用重置门控来得到“重置”之后的数据,再通过一个tanh激活函数来将数据放缩到-1~1的范围内。
  • 1
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
GRU-Attention是一种用于时间序列预测深度学习模型。下面我来简单介绍一下GRU-Attention的实现过程。 首先,我们需要导入必要的库: ```python import numpy as np import pandas as pd import matplotlib.pyplot as plt from keras.models import Sequential, Model from keras.layers import Dense, GRU, Input, RepeatVector, TimeDistributed, Lambda, Activation, Dot, Concatenate from keras.optimizers import Adam from keras.callbacks import EarlyStopping ``` 接着,我们需要准备数据集。这里以一个简单的sin函数为例: ```python x = np.arange(0, 100, 0.1) y = np.sin(x) ``` 由于GRU-Attention是一种序列模型,我们需要将数据集转化为时间序列数据。这里我们取时间窗口为10,即每个时间点预测后面10个时间点的数值: ```python window_size = 10 X = [] Y = [] for i in range(len(y) - window_size): X.append(y[i:i+window_size]) Y.append(y[i+window_size:i+window_size+1]) X = np.array(X) Y = np.array(Y) ``` 接着,我们需要定义GRU-Attention模型。这里我们使用两层GRU和一个Attention层: ```python def attention(inputs): # inputs.shape = (batch_size, time_steps, input_dim) input_dim = int(inputs.shape[2]) a = Permute((2, 1))(inputs) a = Dense(time_steps, activation='softmax')(a) a = Lambda(lambda x: K.mean(x, axis=1), name='dim_reduction')(a) a = RepeatVector(input_dim)(a) a_probs = Permute((2, 1), name='attention_vec')(a) output_attention_mul = Multiply(name='attention_mul')([inputs, a_probs]) return output_attention_mul model = Sequential() model.add(GRU(64, input_shape=(window_size, 1), return_sequences=True)) model.add(GRU(32, return_sequences=True)) model.add(Attention()) model.add(TimeDistributed(Dense(1))) model.add(Activation('linear')) model.compile(loss='mean_squared_error', optimizer=Adam(lr=0.001)) ``` 接着,我们可以开始训练模型: ```python early_stopping = EarlyStopping(monitor='val_loss', patience=10) history = model.fit(X_train, Y_train, validation_split=0.2, epochs=100, batch_size=64, callbacks=[early_stopping]) ``` 最后,我们可以用模型进行预测: ```python y_pred = model.predict(X) plt.plot(y, label='true') plt.plot(y_pred[:, -1, 0], label='predicted') plt.legend() plt.show() ``` 以上就是GRU-Attention时间序列预测实现过程。当然,具体的模型参数和数据集处理方式需要根据实际情况进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

前程算法屋

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

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

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

打赏作者

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

抵扣说明:

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

余额充值