基于self-attention的GRU预测模型

基于self-attention的GRU预测模型

 

特色:1、单变量,多变量输入,自由切换

          2、单步预测,多步预测,自动切换

          3、基于Pytorch架构

          4、多个评估指标(MAE,MSE,R2,MAPE等)

           5、数据从excel文件中读取,更换简单

          6、标准框架,数据分为训练集、验证集,测试集

 

全部完整的代码,保证可以运行的代码看这里。

http://t.csdnimg.cn/El450

 

  !!!如果第一个链接打不开,请点击个人首页,查看我的个人介绍。

(搜索到的产品后,点头像,就能看到全部代码)

黑科技小土豆的博客_CSDN博客-深度学习,32单片机领域博主

81f754be553447359b8409784e21b159.png

e391c22284a64e18b0ed2e4edc68f2bd.png

 

1、GRU-selfAttention模型背景简介

GRU全名Gated Recurrent Units,是一种递归神经网络的变种。它改变了LSTM中的记忆单元和门的结构,只使用了两个门(重置门和更新门)并且直接传递当前状态到输出。

self-attention机制同样适用于GRU网络,可以根据输入序列自适应地计算各个时间步的权重。

因此,GRU-selfAttention模型采用GRU网络结合self-attention机制,来更好地解决序列数据中存在的长期依赖关系和局部依赖之间的复杂关系。

2、GRU-selfAttention模型优点总结

本模型的优点有:

  • GRU结构相对LSTM更加轻量级,计算速度更快,可以更快地进行训练和预测;
  • self-attention机制能够更好地处理序列数据之间的关系,为GRU网络提供各个时间步不同的辅助信息,帮助提高预测准确率。

 

train_ratio = 0.7  # 训练集比例
val_ratio = 0.15  # 验证集比例
test_ratio = 0.15  # 测试集比例
input_length = 48  # 输入数据长度,多步预测建议长,单步预测建议短
output_length = 1  # 输出数据长度,1为单步预测,1以上为多步预测 请注意,随着输出长度的增长,模型训练时间呈指数级增长
learning_rate = 0.1  # 学习率
estimators = 100  # 迭代次数
max_depth = 5  # 树模型的最大深度
interval_length = 2000  # 预测数据长度,最长不可以超过总数据条数
scalar = True  # 是否使用归一化
scalar_contain_labels = True  # 归一化过程是否包含目标值的历史数据
target_value = 'load'  # 需要预测的列名,可以在excel中查看

3b6eadb0210c4946bfd54e910aa2fa84.png

 

 

 

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,我们需要准备数据集。假设我们要预测房价,我们可以使用UCI Machine Learning Repository中的波士顿房价数据集。 接下来,我们可以定义我们的模型。CNN-GRU-Attention模型主要由三部分组成:卷积神经网络层(CNN)、门控循环单元层(GRU)和注意力机制层(Attention)。代码如下: ```python import torch.nn as nn class CNN_GRU_Attention(nn.Module): def __init__(self, input_dim, hidden_dim, output_dim): super(CNN_GRU_Attention, self).__init__() # 定义卷积神经网络层 self.conv_layer = nn.Sequential( nn.Conv1d(in_channels=input_dim, out_channels=32, kernel_size=3), nn.ReLU(), nn.Conv1d(in_channels=32, out_channels=64, kernel_size=3), nn.ReLU(), nn.Conv1d(in_channels=64, out_channels=128, kernel_size=3), nn.ReLU() ) # 定义门控循环单元层 self.gru_layer = nn.GRU(input_size=128, hidden_size=hidden_dim, num_layers=1, batch_first=True) # 定义注意力机制层 self.attention_layer = nn.Sequential( nn.Linear(hidden_dim, 64), nn.Tanh(), nn.Linear(64, 1) ) # 定义输出层 self.output_layer = nn.Linear(hidden_dim, output_dim) def forward(self, x): # 卷积神经网络层 x = self.conv_layer(x) # 将输出转换为GRU的输入格式 x = x.permute(0, 2, 1) # GRU层 output, hidden = self.gru_layer(x) # 注意力机制层 attention_weights = nn.functional.softmax(self.attention_layer(output), dim=1) attention_output = (output * attention_weights).sum(dim=1) # 输出层 output = self.output_layer(attention_output) return output ``` 接下来,我们可以定义损失函数和优化器,并开始训练我们的模型。这里我们使用均方误差(Mean Squared Error)作为损失函数,Adam优化器进行优化。代码如下: ```python import torch.optim as optim # 定义损失函数和优化器 criterion = nn.MSELoss() optimizer = optim.Adam(model.parameters(), lr=0.001) # 开始训练 num_epochs = 100 for epoch in range(num_epochs): # 训练模式 model.train() # 循环批次 for batch_idx, (data, target) in enumerate(train_loader): # 清空梯度 optimizer.zero_grad() # 前向传播 output = model(data) # 计算损失 loss = criterion(output, target) # 反向传播 loss.backward() # 更新参数 optimizer.step() # 测试模式 model.eval() # 计算测试集上的损失 test_loss = 0.0 with torch.no_grad(): for data, target in test_loader: output = model(data) test_loss += criterion(output, target).item() * data.size(0) test_loss /= len(test_loader.dataset) # 打印损失 print('Epoch: {}, Training Loss: {:.6f}, Testing Loss: {:.6f}'.format(epoch+1, loss.item(), test_loss)) ``` 最后,我们可以使用训练好的模型进行预测。代码如下: ```python # 使用模型进行预测 model.eval() with torch.no_grad(): output = model(test_data) # 打印预测结果 print('Prediction:', output.item()) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值