PyTorch LSTM / GRU
核对 LSTM 三门与 GRU 两门结构及精确 75% 参数比、batch_first 张量形状、双向拼接、pack/pad 变长处理,并完成文本分类与正弦时序预测实测。
学完这一章,你能够
- 核对 LSTM 三门与 GRU 两门结构及精确 75% 参数比、batch_first 张量形状、双向拼接、pack/pad 变长处理,并完成文本分类与正弦时序预测实测。
RNN 局限与 LSTM/GRU 门控机制
标准 RNN 逐时间步递推隐状态,在长序列反向传播中连乘权重矩阵极易引发梯度消失(早期步几乎无法更新)或梯度爆炸(需配合梯度裁剪)。门控循环架构通过引入可学习的 Sigmoid 阀门控制信息的遗忘、写入与输出:LSTM 使用三门加独立细胞状态,GRU 精简为两门且参数更少。
LSTM 沿时间步维护长期细胞状态 c_t 与短期隐藏状态 h_t,三个 Sigmoid 门取值在 (0, 1):遗忘门 f_t 经 f_t ⊙ c_{t-1} 决定保留多少历史记忆;输入门 i_t 与候选内容 g_t 经 i_t ⊙ g_t 写入新信息更新 c_t;输出门 o_t 经 o_t ⊙ tanh(c_t) 产生当前隐状态 h_t。细胞状态的加性更新通路显著缓解了长程梯度衰减。
GRU 取消独立的细胞状态,将遗忘与输入逻辑合并为更新门 z_t 并配合重置门 r_t:当 r_t 接近 0 时候选状态 h̃_t 几乎忽略历史;z_t 接近 1 时更多采纳新候选、接近 0 时更多延续历史。同等输入与隐藏维度下,GRU 参数量精确为 LSTM 的 75%(本站对 input=32, hidden=64 实测 LSTM 为 25,088 参数,GRU 为 18,816 参数)。
nn.LSTM 与 nn.GRU 参数、形状与状态初始化
使用 nn.LSTM 与 nn.GRU 最易出错的是维度约定:batch_first=False(默认)要求输入与 output 为 [seq_len, N, H*D],batch_first=True 则为 [N, seq_len, H*D],但无论 batch_first 取值如何,末步隐藏状态 h_n 与细胞状态 c_n 的形状始终为 [L*D, N, H](L 为层数,D 为 1 或 2)。单层单向 LSTM 参数量公式为 4*(H*(I+H)+2H)(含两套偏置),GRU 对应为 3*(H*(I+H)+2H)。不传入初始状态时 PyTorch 默认全零初始化;若跨批次保留有状态隐变量,每次反向传播后必须调用 h.detach()(及 c.detach())切断旧计算图,本站实测 detach 后连续两步反传正常无报错。
双向、多层堆叠与变长序列打包
双向循环网络(bidirectional=True)同时从正向和反向扫描序列,每步 output 最后一维为 2*H;多层堆叠时 h_n 按层与方向交错排布,取最后一层双向汇总应拼接 h_n[-2](顶层正向)与 h_n[-1](顶层反向),本站实测 2 层双向 H=64 输出 [8, 10, 128]、h_n 为 [4, 8, 64]、拼接结果 [8, 128]。注意内置 dropout 参数仅作用于层与层之间,num_layers=1 时不生效,末层输出外需手动加 nn.Dropout。
处理同批不等长序列的标准流水线是:pad_sequence 补齐并记录真实长度 → pack_padded_sequence(..., enforce_sorted=False) 压缩跳过填充步 → 送入 LSTM/GRU → 按需用 pad_packed_sequence 解包。本站对未排序长度 [3, 5, 2] 实测:解包还原精确长度 [3, 5, 2]、填充尾位输出恒为 0.0,且打包返回的 h_n 与每个样本真实末时间步输出最大误差为 0.0。
文本分类、多步时序预测实测与选型速查
本站在 CPU 完成了两项端到端实战:(1)变长 BiLSTM 文本分类(Embedding + pack_padded_sequence + clip_grad_norm_(1.0))训练 12 轮,损失由 0.69931 降至 0.05623,留出验证准确率 100%;(2)滑动窗口正弦波多步预测(输入 24 步预测未来 6 步)训练 18 轮,验证 MSE 由 0.11596 降至 0.00326,且基于首步输出做 10 步递归外推数值全部有限稳定(前三步 [-0.132, -0.03, 0.07])。下图展示本次实测 MSE 收敛曲线与留出 6 步预测对比。
选型与排障建议:算力紧张、短中序列或追求更快迭代时优先试 GRU;极长依赖或需要精细记忆门控时选 LSTM;全程统一 batch_first=True 并配合梯度裁剪可规避绝大多数形状与梯度故障,详见下方三张速查表。
LSTM/GRU 输出与隐状态张量形状对比
| 变量 | batch_first=False | batch_first=True |
| output | (seq_len, N, H * D) | (N, seq_len, H * D) |
| h_n | (L * D, N, H) | (L * D, N, H) |
| c_n | (L * D, N, H)(仅 LSTM) | (L * D, N, H)(仅 LSTM) |
LSTM 与 GRU 结构及工程特性对比
| 对比项 | LSTM | GRU |
| 门的数量 | 3(遗忘、输入、输出) | 2(重置、更新) |
| 状态向量 | 细胞状态 c + 隐藏状态 h | 仅隐藏状态 h |
| 参数量(相同 hidden_size) | 基准(实测 25,088) | 精确 75%(实测 18,816) |
| 训练速度 | 较慢 | 较快 |
| 长序列表现 | 通常更稳 | 接近 |
| 短序列表现 | 相近 | 相近 |
| 实现复杂度 | 较高 | 较低 |
LSTM/GRU 常见故障速查
| 问题 | 原因 | 解决方法 |
| 训练 Loss 不下降 | 学习率过大或梯度爆炸 | 降学习率并加 clip_grad_norm_ |
| 验证集 Loss 远高于训练集 | 过拟合 | 加 Dropout 或减 hidden_size/层数 |
| 序列尾部预测差 | 长程梯度衰减 | 使用双向结构或引入注意力机制 |
| 显存占用过大 | 序列过长或 batch 过大 | 缩短截断长度、减 batch 或开梯度检查点 |
| 有状态训练中 Loss 异常 | 跨批隐状态未截断历史计算图 | 每批传递前调用 h.detach()/c.detach() |
| 双向 LSTM 拼接维度错误 | 误取 h_n[0]/h_n[1] 忽略多层排布 | 取顶层正向 h_n[-2] 与反向 h_n[-1] 拼接 |
| PackedSequence 报错 | 默认 enforce_sorted=True 但未降序 | 显式传入 enforce_sorted=False |
| batch_first 混淆 | 模型与输入维度约定不一致 | 全链路统一 batch_first=True |
运行 LSTM/GRU 参数比、变长打包、双向文本分类与正弦时序预测实验
展开查看收起
"""Independent PyTorch 2.10 CPU LSTM & GRU shapes, packing, text classification & sine forecasting lab."""
import argparse
import hashlib
import json
import math
import platform
from pathlib import Path
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence, pad_sequence
from torch.utils.data import DataLoader, Dataset
class BiLSTMClassifier(nn.Module):
def __init__(self, vocab_size: int, embed_dim: int, hidden_size: int, num_layers: int, num_classes: int, dropout: float = 0.2):
super().__init__()
self.embedding = nn.Embedding(vocab_size, embed_dim, padding_idx=0)
self.lstm = nn.LSTM(
embed_dim, hidden_size, num_layers=num_layers, batch_first=True,
dropout=dropout if num_layers > 1 else 0.0, bidirectional=True,
)
self.dropout = nn.Dropout(dropout)
self.fc = nn.Linear(hidden_size * 2, num_classes)
def forward(self, x: torch.Tensor, lengths: torch.Tensor) -> torch.Tensor:
emb = self.dropout(self.embedding(x))
packed = pack_padded_sequence(emb, lengths.to("cpu"), batch_first=True, enforce_sorted=False)
_, (h_n, _) = self.lstm(packed)
merged = torch.cat([h_n[-2], h_n[-1]], dim=-1)
return self.fc(self.dropout(merged))
class TimeSeriesDataset(Dataset):
def __init__(self, series: np.ndarray, input_len: int, output_len: int):
self.data = torch.tensor(series, dtype=torch.float32)
self.input_len = input_len
self.output_len = output_len
def __len__(self) -> int:
return len(self.data) - self.input_len - self.output_len + 1
def __getitem__(self, idx: int):
x = self.data[idx : idx + self.input_len].unsqueeze(-1)
y = self.data[idx + self.input_len : idx + self.input_len + self.output_len]
return x, y
class LSTMForecaster(nn.Module):
def __init__(self, input_size: int, hidden_size: int, num_layers: int, output_len: int, dropout: float = 0.1):
super().__init__()
self.lstm = nn.LSTM(
input_size, hidden_size, num_layers=num_layers, batch_first=True,
dropout=dropout if num_layers > 1 else 0.0,
)
self.fc = nn.Linear(hidden_size, output_len)
def forward(self, x: torch.Tensor) -> torch.Tensor:
out, _ = self.lstm(x)
return self.fc(out[:, -1, :])
def recursive_forecast(model: nn.Module, init_seq: list[float], steps: int) -> list[float]:
model.eval()
buf = list(init_seq)
win = len(init_seq)
preds = []
with torch.inference_mode():
for _ in range(steps):
x = torch.tensor(buf[-win:], dtype=torch.float32).unsqueeze(0).unsqueeze(-1)
nxt = float(model(x)[0, 0].item())
preds.append(nxt)
buf.append(nxt)
return preds
def sha(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
def run_cases(fig_dir: Path | None):
torch.manual_seed(2026)
np.random.seed(2026)
cases = []
figures = {}
# 1. LSTM vs GRU output shapes (batch_first False/True) & exact 75% parameter ratio
lstm_bf0 = nn.LSTM(input_size=32, hidden_size=64, batch_first=False)
lstm_bf1 = nn.LSTM(input_size=32, hidden_size=64, batch_first=True)
gru_bf1 = nn.GRU(input_size=32, hidden_size=64, batch_first=True)
o0, (h0, c0) = lstm_bf0(torch.randn(10, 8, 32))
o1, (h1, c1) = lstm_bf1(torch.randn(8, 10, 32))
og, hg = gru_bf1(torch.randn(8, 10, 32))
lstm_params = sum(p.numel() for p in lstm_bf1.parameters())
gru_params = sum(p.numel() for p in gru_bf1.parameters())
ratio = round(gru_params / lstm_params, 4)
c1_ok = (
list(o0.shape) == [10, 8, 64]
and list(h0.shape) == [1, 8, 64]
and list(o1.shape) == [8, 10, 64]
and list(h1.shape) == [1, 8, 64]
and list(c1.shape) == [1, 8, 64]
and list(og.shape) == [8, 10, 64]
and list(hg.shape) == [1, 8, 64]
and ratio == 0.75
)
cases.append(dict(
name="lstm_gru_shapes_and_param_ratio",
inputs=dict(input_size=32, hidden_size=64, batch=8, seq_len=10),
prerequisites="同规模单层单向 LSTM 与 GRU 形状和参数量对比",
action="验证 batch_first=False/True 仅交换 output 前两维而 h_n/c_n 恒为 [L*D, N, H],且 GRU 参数量精确为 LSTM 的 75%。",
expected=dict(shapes_exact=True, gru_to_lstm_ratio=0.75),
actual=dict(shapes_exact=c1_ok, gru_to_lstm_ratio=ratio),
measurements=dict(lstm_params=lstm_params, gru_params=gru_params),
passed=c1_ok,
))
# 2. Bidirectional, stacked layers & stateful hidden detach()
bilstm = nn.LSTM(32, 64, num_layers=2, batch_first=True, bidirectional=True, dropout=0.2)
bo, (bh, bc) = bilstm(torch.randn(8, 10, 32))
combined = torch.cat([bh[-2], bh[-1]], dim=-1)
# Stateful step with detach() allows independent second backward
s_lstm = nn.LSTM(16, 24, batch_first=True)
y_a, (ha, ca) = s_lstm(torch.randn(4, 5, 16))
y_a.sum().backward()
y_b, _ = s_lstm(torch.randn(4, 5, 16), (ha.detach(), ca.detach()))
y_b.sum().backward()
c2_ok = list(bo.shape) == [8, 10, 128] and list(bh.shape) == [4, 8, 64] and list(combined.shape) == [8, 128]
cases.append(dict(
name="bidirectional_stacked_and_state_detach",
inputs=dict(num_layers=2, bidirectional=True, hidden_size=64),
prerequisites="双层双向 LSTM h_n 排列 [L0_fwd, L0_bwd, L1_fwd, L1_bwd] 及有状态 detach()",
action="验证双向输出 128 维、h_n[-2] 与 h_n[-1] 拼接及跨批 detach() 安全反向传播。",
expected=dict(output_shape=[8, 10, 128], hn_shape=[4, 8, 64], combined_shape=[8, 128]),
actual=dict(output_shape=list(bo.shape), hn_shape=list(bh.shape), combined_shape=list(combined.shape)),
passed=c2_ok,
))
# 3. Variable-length pack_padded_sequence & pad_packed_sequence equivalence
seqs = [torch.randn(3, 16), torch.randn(5, 16), torch.randn(2, 16)]
padded = pad_sequence(seqs, batch_first=True, padding_value=0.0)
lens = torch.tensor([3, 5, 2])
uni_lstm = nn.LSTM(16, 24, batch_first=True)
packed = pack_padded_sequence(padded, lens, batch_first=True, enforce_sorted=False)
p_out, (p_hn, _) = uni_lstm(packed)
unpacked, out_lens = pad_packed_sequence(p_out, batch_first=True)
gathered_last = unpacked[torch.arange(3), lens - 1, :]
last_diff = float((p_hn.squeeze(0) - gathered_last).abs().max().item())
pad_tail_zero = float(unpacked[2, 2:, :].abs().max().item()) == 0.0
c3_ok = out_lens.tolist() == [3, 5, 2] and last_diff < 1e-6 and pad_tail_zero
cases.append(dict(
name="variable_length_pack_and_pad",
inputs=dict(lengths=[3, 5, 2], enforce_sorted=False),
prerequisites="变长序列 pad_sequence -> pack_padded_sequence -> pad_packed_sequence",
action="验证未排序变长输入解包后还原长度 [3, 5, 2]、填充位输出恒 0,且 h_n 与真实末步输出误差 <1e-6。",
expected=dict(restored_lengths=[3, 5, 2], pad_positions_zero=True, hn_matches_last_step=True),
actual=dict(restored_lengths=out_lens.tolist(), pad_positions_zero=pad_tail_zero, hn_matches_last_step=last_diff < 1e-6),
measurements=dict(max_last_step_diff=round(last_diff, 8)),
passed=c3_ok,
))
# 4. BiLSTM variable-length sequence classification
# Positive sequences contain tokens from 2..15, negative from 16..29
clf_seqs, clf_lens, clf_lbls = [], [], []
for i in range(120):
lbl = i % 2
L = int(torch.randint(4, 12, (1,)).item())
lo, hi = (2, 16) if lbl == 1 else (16, 30)
clf_seqs.append(torch.randint(lo, hi, (L,)))
clf_lens.append(L)
clf_lbls.append(lbl)
X_pad = pad_sequence(clf_seqs, batch_first=True, padding_value=0)
L_all = torch.tensor(clf_lens, dtype=torch.long)
Y_all = torch.tensor(clf_lbls, dtype=torch.long)
clf = BiLSTMClassifier(vocab_size=32, embed_dim=16, hidden_size=24, num_layers=1, num_classes=2, dropout=0.1)
opt_c = optim.Adam(clf.parameters(), lr=8e-3)
crit_c = nn.CrossEntropyLoss()
c_losses = []
for _ in range(12):
clf.train()
opt_c.zero_grad(set_to_none=True)
loss = crit_c(clf(X_pad[:96], L_all[:96]), Y_all[:96])
loss.backward()
nn.utils.clip_grad_norm_(clf.parameters(), max_norm=1.0)
opt_c.step()
c_losses.append(round(float(loss.item()), 5))
clf.eval()
with torch.inference_mode():
clf_acc = round(float((clf(X_pad[96:], L_all[96:]).argmax(dim=1) == Y_all[96:]).float().mean().item()), 4)
c4_ok = c_losses[-1] < c_losses[0] * 0.2 and clf_acc >= 0.90
cases.append(dict(
name="bilstm_text_classifier_training",
inputs=dict(train=96, val=24, epochs=12, clip_norm=1.0),
prerequisites="Embedding + pack_padded_sequence + BiLSTM + clip_grad_norm_",
action="训练变长双向 LSTM 分类器 12 轮,验证损失大幅下降且留出验证准确率 >=90%。",
expected=dict(loss_dropped=True, val_acc_ge_90=True),
actual=dict(loss_dropped=c_losses[-1] < c_losses[0] * 0.2, val_acc_ge_90=clf_acc >= 0.90),
measurements=dict(ep1_loss=c_losses[0], ep12_loss=c_losses[-1], val_acc=clf_acc),
passed=c4_ok,
))
# 5. Multi-step & recursive sine-wave time-series forecasting
t = np.linspace(0, 60, 720)
series = np.sin(t) + 0.05 * np.random.randn(len(t))
in_len, out_len = 24, 6
split = int(len(series) * 0.8)
tr_ts = TimeSeriesDataset(series[:split], in_len, out_len)
va_ts = TimeSeriesDataset(series[split:], in_len, out_len)
tr_loader = DataLoader(tr_ts, batch_size=32, shuffle=True, generator=torch.Generator().manual_seed(7))
va_loader = DataLoader(va_ts, batch_size=64, shuffle=False)
forecaster = LSTMForecaster(input_size=1, hidden_size=32, num_layers=1, output_len=out_len)
opt_f = optim.Adam(forecaster.parameters(), lr=8e-3)
mse = nn.MSELoss()
tr_mses, va_mses = [], []
for _ in range(18):
forecaster.train()
tl = 0.0
for bx, by in tr_loader:
opt_f.zero_grad(set_to_none=True)
loss = mse(forecaster(bx), by)
loss.backward()
nn.utils.clip_grad_norm_(forecaster.parameters(), 1.0)
opt_f.step()
tl += float(loss.item()) * bx.size(0)
tr_mses.append(round(tl / len(tr_ts), 5))
forecaster.eval()
vl = 0.0
with torch.inference_mode():
for bx, by in va_loader:
vl += float(mse(forecaster(bx), by).item()) * bx.size(0)
va_mses.append(round(vl / len(va_ts), 5))
# Recursive rollout check using first predicted step
init_window = series[split : split + in_len].tolist()
rec_preds = recursive_forecast(forecaster, init_window, steps=10)
c5_ok = va_mses[-1] < va_mses[0] * 0.25 and va_mses[-1] < 0.03 and len(rec_preds) == 10 and all(math.isfinite(v) for v in rec_preds)
cases.append(dict(
name="lstm_sine_wave_forecasting",
inputs=dict(input_len=in_len, output_len=out_len, epochs=18),
prerequisites="滑动窗口 TimeSeriesDataset + LSTMForecaster 多步与递归预测",
action="验证验证集 MSE 降至 <0.03,且递归预测 10 步数值有限稳定。",
expected=dict(val_mse_lt_003=True, recursive_10_finite=True),
actual=dict(val_mse_lt_003=va_mses[-1] < 0.03, recursive_10_finite=(len(rec_preds) == 10 and all(math.isfinite(v) for v in rec_preds))),
measurements=dict(ep1_val_mse=va_mses[0], ep18_val_mse=va_mses[-1], first_3_rec=[round(v, 3) for v in rec_preds[:3]]),
passed=c5_ok,
))
# 6. Plot MSE convergence & multi-step forecast overlay
if fig_dir is not None:
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
fig_dir.mkdir(parents=True, exist_ok=True)
forecaster.eval()
with torch.inference_mode():
sample_x, sample_y = va_ts[10]
pred_y = forecaster(sample_x.unsqueeze(0))[0].numpy()
fig, axes = plt.subplots(1, 2, figsize=(9.4, 3.6), dpi=140)
ep = list(range(1, len(va_mses) + 1))
axes[0].plot(ep, tr_mses, label=f"Train MSE ({tr_mses[-1]:.4f})", color="#174d79")
axes[0].plot(ep, va_mses, label=f"Val MSE ({va_mses[-1]:.4f})", color="#ae511d", linestyle="--")
axes[0].set_title("LSTM Forecaster MSE Convergence", fontsize=10)
axes[0].set_xlabel("Epoch")
axes[0].set_ylabel("MSE")
axes[0].grid(True, alpha=0.3)
axes[0].legend(fontsize=8)
hist_x = list(range(in_len))
fut_x = list(range(in_len, in_len + out_len))
axes[1].plot(hist_x, sample_x.squeeze(-1).numpy(), label="Input Window (24 steps)", color="#555555")
axes[1].plot(fut_x, sample_y.numpy(), marker="o", label="Ground Truth (6 steps)", color="#174d79")
axes[1].plot(fut_x, pred_y, marker="x", linestyle="--", label="LSTM Forecast", color="#ae511d")
axes[1].set_title("Held-Out Multi-Step Sine Forecast", fontsize=10)
axes[1].set_xlabel("Time Step")
axes[1].set_ylabel("Value")
axes[1].grid(True, alpha=0.3)
axes[1].legend(fontsize=8)
fig.tight_layout()
out_png = fig_dir / "lstm-sine-forecast.png"
fig.savefig(out_png)
plt.close(fig)
figures["lstm-sine-forecast.png"] = sha(out_png)
mpl_ver = matplotlib.__version__
else:
mpl_ver = None
cases.append(dict(
name="observed_forecast_plot",
inputs=dict(epochs=18, forecast_horizon=out_len),
prerequisites="LSTM 时序预测训练/验证 MSE 与留出多步预测序列",
action="输出 MSE 收敛曲线与留出 6 步预测对比图。",
expected=dict(epochs_plotted=18),
actual=dict(epochs_plotted=len(va_mses)),
measurements=dict(figure_generated="lstm-sine-forecast.png" in figures),
passed=len(va_mses) == 18,
))
payload = dict(version=platform.python_version(), torch=torch.__version__, system=platform.system(), cases=cases)
if mpl_ver:
payload["matplotlib"] = mpl_ver
payload["figures"] = figures
print(json.dumps(payload, ensure_ascii=False))
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--figures", type=Path, default=None)
args = parser.parse_args()
run_cases(args.figures)
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 选择对应构建并运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
h_n 第 0 维按层号升序、每层内先正向后反向排列([L0_fwd, L0_bwd, L1_fwd, L1_bwd, ...]),因此 h_n[-2] 与 h_n[-1] 才是最后一层前向与后向的最终隐状态。