一        tensorflow 框架

input 格式 (batch, seq_len, input_size) 

默认输出为输出层的最后一个

方法1        先设置RNN单元,再设置网络

1 单向循环神经网络

定义
import tensorflow as tf

# units指的是隐藏层的维数
units = 128

# 单向的RNN, GRU, LSTM用下面的
# tf.keras.layers.RNN(" 单元名称 例如:tf.keras.layers.LSTMCell")

# 单向的RNN
RNN_Cell = tf.keras.layers.SimpleRNNCell(units=units)
RNN = tf.keras.layers.RNN(RNN_Cell)

# 单向的GRU
GRU_Cell = tf.keras.layers.GRUCell(units=units)
GRU = tf.keras.layers.RNN(GRU_Cell)

# 单向的LSTM
LSTM_Cell = tf.keras.layers.LSTMCell(units=units)
LSTM = tf.keras.layers.RNN(LSTM_Cell)
使用 
batch_size = 32     # 批次大小
time_steps = 12     # 时间步长, 或者序列长度, 即len_sequence
input_dims = 128    # 输入向量维度
units = 128         # units是隐藏层的维数
# 初始化输入向量
inputs = tf.random.normal((batch_size, time_steps, input_dims))

# 初始化隐藏层, 也可以不初始化, 因为会自动初始化
initial_hidden_state = tf.zeros((batch_size, units))

outputs = GRU(inputs, initial_state=initial_hidden_state)

2 双向循环神经网络

定义
import tensorflow as tf

# units指的是隐藏层的维数
units = 128

# 双向的RNN, GRU, LSTM用下面的
# tf.keras.layers.RNN(" 单元名称 例如:tf.keras.layers.LSTMCell")

# 双向的RNN
RNN_Cell = tf.keras.layers.SimpleRNNCell(units=units)
RNN = tf.keras.layers.RNN(RNN_Cell)
Bidirectional_RNN = tf.keras.layers.Bidirectional(RNN)

# 双向的GRU
GRU_Cell = tf.keras.layers.GRUCell(units=units)
GRU = tf.keras.layers.RNN(GRU_Cell)
Bidirectional_GRU = tf.keras.layers.Bidirectional(GRU)

# 双向的LSTM
LSTM_Cell = tf.keras.layers.LSTMCell(units=units)
LSTM = tf.keras.layers.RNN(LSTM_Cell)
Bidirectional_LSTM = tf.keras.layers.Bidirectional(LSTM)
使用 
batch_size = 32     # 批次大小
time_steps = 12     # 时间步长, 或者序列长度, 即len_sequence
input_dims = 128    # 输入向量维度
units = 128         # units是隐藏层的维数
# 初始化输入向量
inputs = tf.random.normal((batch_size, time_steps, input_dims))

# 初始化隐藏层, 也可以不初始化, 因为会自动初始化
initial_forward_state = tf.zeros((batch_size, units))
initial_backward_state = tf.zeros((batch_size, units))
initial_state = [initial_forward_state, initial_backward_state]

outputs = Bidirectional_GRU(inputs, initial_state=initial_state)

3 输出特性

默认输出为输出层的最后一个,若想改为整个输出层,设置return_sequences=True

RNN = tf.keras.layers.RNN(RNN_Cell, return_sequences=True)

若想输出隐藏层状态,设置return_state=True

# return_state=True 返回隐藏状态 (h) 和 细胞状态 (c)
bidirectional_lstm = tf.keras.layers.Bidirectional(
    tf.keras.layers.LSTM(units, return_sequences=True, return_state=True)
)

# 获取输出和隐藏状态
outputs, forward_h, forward_c, backward_h, backward_c = bidirectional_lstm(inputs)

print("Output shape:", outputs.shape)  # (32, 10, 256)
print("Forward hidden state shape:", forward_h.shape)  # (32, 128)
print("Backward hidden state shape:", backward_h.shape)  # (32, 128)
print("Forward cell state shape:", forward_c.shape)  # (32, 128)
print("Backward cell state shape:", backward_c.shape)  # (32, 128)

方法2        直接调用接口

import tensorflow as tf

# units指的是隐藏层的维数
units = 128

# 单向的RNN
RNN = tf.keras.layers.SimpleRNN(units)

# 双向的GRU
GRU = tf.keras.layers.GRU(units)
Bidirectional_GRU = tf.keras.layers.Bidirectional(GRU)

二        pytorch 框架

默认input 格式 (seq_len, batch, input_size) 

设置batch_first=True可以使输入输出使用(batch, seq, feature)格式

默认输出为整个输出层,以及隐藏层(对RNN, GRU来说,对LSTM还有cell_state)

方法1        底层单元(适合自定义RNN网络)

PyTorch还提供了更底层的RNN单元实现:

  1. torch.nn.RNNCell - 单个RNN单元

  2. torch.nn.LSTMCell - 单个LSTM单元

  3. torch.nn.GRUCell - 单个GRU单元

这些单元一次只处理一个时间步,适合自定义RNN结构:

rnn_cell = nn.RNNCell(input_size=10, hidden_size=20)
input = torch.randn(3, 10)  # (batch, input_size)
hx = torch.randn(3, 20)     # (batch, hidden_size)
hx = rnn_cell(input, hx)

方法2        直接调用接口

RNN模型

  1. torch.nn.RNN - 基本的RNN实现

    • 输入维度: input_size

    • 隐藏层维度: hidden_size

    • 层数: num_layers

    • 非线性激活函数: tanh或ReLU

    • 支持双向: bidirectional

rnn = nn.RNN(input_size=10, hidden_size=20, num_layers=2)
input = torch.randn(5, 3, 10)  # (seq_len, batch, input_size)
h0 = torch.randn(2, 3, 20)     # (num_layers, batch, hidden_size)
output, hn = rnn(input, h0)

GRU模型 

  1. torch.nn.GRU - 门控循环单元

    • LSTM的简化版本

    • 只有重置门和更新门

    • 计算效率比LSTM高

gru = nn.GRU(input_size=10, hidden_size=20, num_layers=2)
input = torch.randn(5, 3, 10)
h0 = torch.randn(2, 3, 20)
output, hn = gru(input, h0)

LSTM模型

  1. torch.nn.LSTM - 长短期记忆网络

    • 解决了普通RNN的梯度消失问题

    • 包含输入门、遗忘门、输出门

    • 有细胞状态(cell state)和隐藏状态(hidden state)

lstm = nn.LSTM(input_size=10, hidden_size=20, num_layers=2)
input = torch.randn(5, 3, 10)
h0 = torch.randn(2, 3, 20)
c0 = torch.randn(2, 3, 20)
output, (hn, cn) = lstm(input, (h0, c0))

输出特性

参数 输入形状 (inputs) 输出形状 (outputs) 隐藏状态形状 (hidden) 说明
batch_first=True
单向RNN
(B, L, input_size) (B, L, hidden_size) (num_layers, B, hidden_size) 隐藏状态:层数 × batch × 特征
batch_first=True
双向RNN
(B, L, input_size) (B, L, hidden_size × 2) (num_layers × 2, B, hidden_size) 隐藏状态:层数×2 × batch × 特征
batch_first=False
单向RNN
(L, B, input_size) (L, B, hidden_size) (num_layers, B, hidden_size) 隐藏状态形状不受影响
batch_first=False
双向RNN
(L, B, input_size) (L, B, hidden_size × 2) (num_layers × 2, B, hidden_size) 隐藏状态形状不受影响
符号 含义 说明
B batch_size 批次大小
L seq_len 序列长度
input_size 输入特征维度 每个时间步的输入特征数
hidden_size 隐藏层特征维度 每个RNN单元的输出特征数
num_layers RNN层数 堆叠的RNN层数量
num_directions 方向数 1(单向) 或 2(双向)

变体和扩展

PyTorch还支持:

  • 双向RNN (bidirectional=True)

  • Dropout (dropout参数)

  • 多层RNN (num_layers参数)

  • PackedSequence处理变长序列

这些RNN单元可以灵活组合使用,构建各种序列模型架构。

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐