Skip to content

RNN 与 LSTM

RNN 处理序列数据,核心是隐状态在时间步之间传递

flowchart LR
A[x] --> B[h] --> C[x] --> D[h] --> E[x] --> F[h]
B --> B
D --> D
ht=tanh(Whht1+Wxxt+b)h_t = \tanh(W_h h_{t-1} + W_x x_t + b)
import torch
import torch.nn as nn
rnn = nn.RNN(input_size=128, hidden_size=256, batch_first=True)
x = torch.randn(2, 10, 128) # (batch=2, seq_len=10, features=128)
output, hidden = rnn(x)
print(f"输出: {output.shape}, 隐状态: {hidden.shape}")

LSTM 通过三个门控制信息流动:

flowchart LR
A[遗忘门] --> D[细胞状态]
B[输入门] --> D
C[输出门] --> E[隐状态]
D --> E
作用
遗忘门决定丢弃哪些旧信息
输入门决定存储哪些新信息
输出门决定输出什么
lstm = nn.LSTM(input_size=128, hidden_size=256, batch_first=True)
output, (hidden, cell) = lstm(x)
print(f"输出: {output.shape}, 隐状态: {hidden.shape}, 细胞状态: {cell.shape}")

RNN 的局限是串行计算。Transformer 用 Self-Attention 替代循环,实现并行计算。