人工智能(Pytorch)搭建模型3-GRU网络的构建,构造数据实现训练过程与评估

大家好,我是微学AI,今天给大家介绍一下人工智能(Pytorch)搭建模型3-GRU网络的构建,构造数据实现训练过程与评估,让大家了解整个训练的过程。

一、GRU模型

GRU(Gated Recurrent Unit,门控循环单元)是一种循环神经网络(RNN)的变体,用于处理序列数据。对于每个时刻,GRU模型都根据当前输入和之前的状态来推断出新状态,从而输出预测结果。与传统的RNN模型不同,在GRU模型中添加了两个门控机制,即「重置门」和「更新门」,来控制模型在推断时候保留多少历史信息。

76803872a3ec48a7bc86dfea0ef1f1c7.png

举个例子:假设任务是让模型学习一段句子并预测它的下一个单词是什么。在传统的RNN模型中,模型在处理较长的序列时会出现梯度消失/爆炸的问题。而在GRU模型中,我们引入了两个门控机制。第一个是重置门,负责让模型忘记历史状态中的某些信息,以便有更好的记忆和推断。第二个是更新门,它决定了这时刻的门口该有多大程度打开,来控制历史信息的保留。因此,GRU模型不仅能够自动地提取各种长期依赖性,而且计算复杂度较低、训练效果也比传统的RNN模型更好。

二、GRU计算过程

在GRU的简化形式中,一个输入的序列被送入GRU网络,每一个时刻是一个单独的向量或一个含多个元素的序列。每一个时刻网络会读入一个输入向量,计算出当前的隐含状态,并把这个状态传递到下一个时刻。每一个时刻的计算包括三个部分࿱

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
使用 Keras-GPU 搭建 CNN-GRU-Attention 模型: 首先导入必要的库: ``` import numpy as np import pandas as pd import keras.backend as K from keras.models import Model from keras.layers import Input, Dense, Embedding, Conv1D, MaxPooling1D, GRU, Bidirectional, TimeDistributed, Flatten, Dropout, Lambda ``` 接着加载数据: ``` # 加载数据 data = pd.read_csv('data.csv') # 分割特征和标签 X = data.iloc[:, :-1].values y = data.iloc[:, -1].values # 将标签转换为one-hot编码 y = pd.get_dummies(y).values ``` 构建模型: ``` def cnn_gru_att(): input_layer = Input(shape=(X.shape[1],)) # embedding层 emb = Embedding(input_dim=VOCAB_SIZE, output_dim=EMB_SIZE)(input_layer) # CNN层 conv1 = Conv1D(filters=64, kernel_size=3, activation='relu', padding='same')(emb) pool1 = MaxPooling1D(pool_size=2)(conv1) conv2 = Conv1D(filters=128, kernel_size=3, activation='relu', padding='same')(pool1) pool2 = MaxPooling1D(pool_size=2)(conv2) conv3 = Conv1D(filters=256, kernel_size=3, activation='relu', padding='same')(pool2) pool3 = MaxPooling1D(pool_size=2)(conv3) # GRUgru = Bidirectional(GRU(units=128, return_sequences=True))(pool3) # Attention层 attention = TimeDistributed(Dense(1, activation='tanh'))(gru) attention = Flatten()(attention) attention = Lambda(lambda x: K.softmax(x))(attention) attention = RepeatVector(256)(attention) attention = Permute([2, 1])(attention) # 加权求和 sent_representation = Multiply()([gru, attention]) sent_representation = Lambda(lambda xin: K.sum(xin, axis=-2), output_shape=(256,))(sent_representation) # 全连接层 fc1 = Dense(units=256, activation='relu')(sent_representation) fc2 = Dense(units=128, activation='relu')(fc1) output_layer = Dense(units=NUM_CLASSES, activation='softmax')(fc2) model = Model(inputs=input_layer, outputs=output_layer) return model ``` 使用 PyTorch 搭建 CNN-GRU-Attention 模型: 首先导入必要的库: ``` import torch import torch.nn as nn import torch.nn.functional as F ``` 接着定义模型: ``` class CNN_GRU_ATT(nn.Module): def __init__(self, vocab_size, emb_size, num_filters, kernel_sizes, hidden_size, num_classes, dropout_rate): super(CNN_GRU_ATT, self).__init__() # embedding层 self.embedding = nn.Embedding(vocab_size, emb_size) # CNN层 self.convs = nn.ModuleList([nn.Conv1d(in_channels=emb_size, out_channels=num_filters, kernel_size=ks) for ks in kernel_sizes]) # GRU层 self.gru = nn.GRU(input_size=num_filters*len(kernel_sizes), hidden_size=hidden_size, bidirectional=True, batch_first=True) # Attention层 self.attention_layer = nn.Linear(hidden_size*2, 1) # 全连接层 self.fc1 = nn.Linear(hidden_size*2, hidden_size) self.fc2 = nn.Linear(hidden_size, num_classes) # Dropout层 self.dropout = nn.Dropout(dropout_rate) def forward(self, x): # embedding层 embedded = self.embedding(x) # CNN层 conv_outputs = [] for conv in self.convs: conv_output = F.relu(conv(embedded.transpose(1, 2))) pooled_output = F.max_pool1d(conv_output, conv_output.size(2)).squeeze(2) conv_outputs.append(pooled_output) cnn_output = torch.cat(conv_outputs, dim=1) # GRUgru_output, _ = self.gru(cnn_output.unsqueeze(0)) gru_output = gru_output.squeeze(0) # Attention层 attention_weights = F.softmax(self.attention_layer(gru_output), dim=0) attention_output = (gru_output * attention_weights).sum(dim=0) # 全连接层 fc1_output = self.dropout(F.relu(self.fc1(attention_output))) fc2_output = self.fc2(fc1_output) return fc2_output ``` 以上是使用 Keras-GPU 和 PyTorch 搭建 CNN-GRU-Attention 模型的示例代码,需要根据具体的任务修改模型参数和数据处理方式。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

微学AI

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

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

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

打赏作者

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

抵扣说明:

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

余额充值