PyTorch 循环神经网络
按时间步核对循环递推公式、隐状态截断与梯度裁剪,并运行序列分类与字符旋转实验。
学完这一章,你能够
- 按时间步核对循环递推公式、隐状态截断与梯度裁剪,并运行序列分类与字符旋转实验。
循环结构与时间步递推
循环神经网络(RNN)用于处理文本、音频、时间序列等有序数据。与只在层间单向传递的前馈网络不同,RNN 在每个时间步维护隐状态,把前序步骤的摘要带入当前计算。
在时间步 t,循环单元接收当前输入向量 x_t 与上一时刻的隐状态 h_{t-1},更新得到新的隐状态 h_t;若任务需要逐步输出,再由 h_t 计算当前时刻输出 y_t。
基本递推可写为 h_t = f(W_hh h_{t-1} + W_xh x_t + b_h),其中 f 常取 tanh 或 ReLU;输出层为 y_t = W_hy h_t + b_y。PyTorch 的 nn.RNN 在内部保存输入偏置 bias_ih_l0 与隐态偏置 bias_hh_l0 两项,本站手算逐时间步递推与 nn.RNN 及线性头的输出在 1e-6 精度内一致。
按时间展开的真实依赖
按时间步展开可直观看到信息流:各时刻输入 x_t 经输入权重矩阵进入隐状态,隐状态经循环权重矩阵沿时间步传递,再由输出权重矩阵映射到各时刻输出 y_t;不同时间步共享同一组循环权重。
需要注意:实际实现是对同一批次内的多个样本以及单个时间步内的矩阵乘法做并行计算,而不是把相互依赖的时间步并行计算——因为 h_t 依赖 h_{t-1},时间维度本身仍按顺序递推。
PyTorch 循环模块与序列分类
PyTorch 提供三种核心循环模块:torch.nn.RNN 为基本循环层;torch.nn.LSTM 引入细胞状态 c_t 与门控机制以缓解长序列依赖问题,返回 (out, (h_n, c_n));torch.nn.GRU 简化门控结构并返回 (out, h_n)。默认输入布局为 [T, N, D],设置 batch_first=True 后改为 [N, T, D]。
序列分类通常取最后一步隐输出 out[:, -1, :] 送入 nn.Linear。本站构造 448 条长度 10、维度 5 的确定性序列并划分为 320 条训练与 128 条独立留出测试(避免用训练集充当测试集),以 SimpleRNN(5, 24, 2)、CrossEntropyLoss 和 Adam(lr=0.01) 训练 15 轮:训练损失由 0.67549 降至 0.14048,在 model.eval() 与 torch.inference_mode() 下独立测试集判对 116/128,准确率 90.62%。
字符序列预测与隐态截断
构建字符词表时应先去重:直接对 "hello" 调用 list 会保留两个 'l' 导致索引冲突与多余维度;按出现顺序去重得到 ['h', 'e', 'l', 'o'] 共 4 个唯一字符,再把输入 "hello" 编码为 [5, 4] 独热矩阵、目标 "elloh" 编码为整型类别索引,经 nn.RNN 与 nn.Linear 映射回词表 logits。
在跨批次复用隐状态(截断反向传播 TBPTT)时,调用 hidden.detach() 的真实作用是切断与上一轮计算图的引用,防止再次 backward 触发“Trying to backward through the graph a second time”错误,它本身并不替代梯度裁剪。控制大梯度爆炸应使用 torch.nn.utils.clip_grad_norm_;本站实测将范数 45.3257 裁剪至 1.0。对独立的整条短序列重复训练时,每轮将 hidden 置为 None 即可避免跨轮携带尾步状态。
本站用 CharRNN(4, 12) 与 Adam(lr=0.05) 对 "hello" → "elloh" 训练 120 轮,第 20 轮交叉熵损失为 0.00107,第 120 轮降至 0.00008,推断模式完整预测出 "elloh"。下图绘制本次 120 轮实测损失曲线。
PyTorch 三种循环模块对照
| 模块 | 返回状态 | 默认与 batch_first=True 输入形状 |
| torch.nn.RNN | (out, h_n) | 默认 [T, N, D];batch_first=True 时 [N, T, D] |
| torch.nn.LSTM | (out, (h_n, c_n)) | 额外维护细胞状态 c_n,形状与 h_n 相同 [L, N, H] |
| torch.nn.GRU | (out, h_n) | 含更新门与重置门,无独立细胞状态 |
运行循环神经网络递推、分类与字符序列实验
展开查看收起
"""Observe PyTorch RNN recurrence, LSTM/GRU variants, sequence classification and character training."""
import argparse
from hashlib import sha256
import json
from pathlib import Path
import platform
import numpy as np
from PIL import Image
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
class SimpleRNN(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super().__init__()
self.rnn = nn.RNN(input_size, hidden_size, batch_first=True)
self.fc = nn.Linear(hidden_size, output_size)
def forward(self, x):
out, _ = self.rnn(x)
return self.fc(out[:, -1, :])
class CharRNN(nn.Module):
def __init__(self, vocab_size, hidden_size):
super().__init__()
self.rnn = nn.RNN(vocab_size, hidden_size, batch_first=True)
self.fc = nn.Linear(hidden_size, vocab_size)
def forward(self, x, hidden=None):
out, hidden = self.rnn(x, hidden)
return self.fc(out), hidden
def record(cases, name, inputs, conditions, action, expected, actual, **measurements):
assert actual == expected, (name, expected, actual)
cases.append(dict(name=name, inputs=inputs, prerequisites=conditions, action=action,
expected=expected, actual=actual, passed=True, measurements=measurements))
def check_recurrence_and_variants(cases):
torch.manual_seed(7)
rnn = nn.RNN(3, 4, batch_first=True, nonlinearity="tanh")
head = nn.Linear(4, 2)
x = torch.randn(2, 3, 3)
h0 = torch.zeros(1, 2, 4)
out, hn = rnn(x, h0)
y = head(out)
# Manual step-by-step recurrence matching PyTorch's two-bias formula.
h = h0[0]
manual_steps = []
for t in range(x.size(1)):
h = torch.tanh(x[:, t, :] @ rnn.weight_ih_l0.T + rnn.bias_ih_l0
+ h @ rnn.weight_hh_l0.T + rnn.bias_hh_l0)
manual_steps.append(h)
manual_out = torch.stack(manual_steps, dim=1)
manual_y = manual_out @ head.weight.T + head.bias
relu_rnn = nn.RNN(3, 4, batch_first=True, nonlinearity="relu")
relu_out, _ = relu_rnn(x)
record(cases, "rnn_step_formula", {"batch": 2, "seq_len": 3, "input_size": 3, "hidden_size": 4},
"nn.RNN(nonlinearity='tanh' and 'relu') with zero initial hidden state",
"Compare nn.RNN and linear head against explicit step-by-step recurrence",
[True, True, True, True],
[torch.allclose(out, manual_out, atol=1e-6),
torch.allclose(hn[0], manual_out[:, -1, :], atol=1e-6),
torch.allclose(y, manual_y, atol=1e-6),
bool(torch.all(relu_out >= 0))])
seq_bf = torch.randn(4, 6, 5)
seq_sf = seq_bf.transpose(0, 1)
r_out, r_h = nn.RNN(5, 8, batch_first=True)(seq_bf)
l_out, (l_h, l_c) = nn.LSTM(5, 8, batch_first=True)(seq_bf)
g_out, g_h = nn.GRU(5, 8, batch_first=True)(seq_bf)
sf_out, sf_h = nn.RNN(5, 8, batch_first=False)(seq_sf)
record(cases, "rnn_lstm_gru_variants", {"batch_first_shape": [4, 6, 5], "seq_first_shape": [6, 4, 5]},
"Single-layer unidirectional RNN, LSTM and GRU",
"Compare output and final state shapes across batch_first=True and False",
[[4, 6, 8], [1, 4, 8], True, [1, 4, 8], [1, 4, 8], True, [1, 4, 8], True, [6, 4, 8], [1, 4, 8]],
[list(r_out.shape), list(r_h.shape), torch.allclose(r_out[:, -1, :], r_h[-1]),
list(l_h.shape), list(l_c.shape), torch.allclose(l_out[:, -1, :], l_h[-1]),
list(g_h.shape), torch.allclose(g_out[:, -1, :], g_h[-1]),
list(sf_out.shape), list(sf_h.shape)])
def check_sequence_classification(cases):
gen = torch.Generator().manual_seed(42)
x_all = torch.randn(448, 10, 5, generator=gen)
# Deterministic rule: class depends on cumulative sum across all time steps.
scores = x_all.sum(dim=(1, 2))
y_all = (scores > 0).long()
train_ds = TensorDataset(x_all[:320], y_all[:320])
test_ds = TensorDataset(x_all[320:], y_all[320:])
train_loader = DataLoader(train_ds, batch_size=32, shuffle=True, generator=torch.Generator().manual_seed(11))
test_loader = DataLoader(test_ds, batch_size=32, shuffle=False)
torch.manual_seed(42)
model = SimpleRNN(input_size=5, hidden_size=24, output_size=2)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
epoch_losses = []
for _ in range(15):
model.train()
total_loss = 0.0
for bx, by in train_loader:
optimizer.zero_grad(set_to_none=True)
loss = criterion(model(bx), by)
loss.backward()
optimizer.step()
total_loss += loss.item() * len(by)
epoch_losses.append(total_loss / len(train_ds))
model.eval()
correct = 0
with torch.inference_mode():
for bx, by in test_loader:
preds = model(bx).argmax(dim=1)
correct += int((preds == by).sum())
test_acc = correct / len(test_ds)
record(cases, "sequence_classification_split", {"train": 320, "test": 128, "seq_len": 10, "input_size": 5},
"Separate train/test splits, Adam lr=0.01, 15 epochs, eval + inference_mode",
"Train SimpleRNN on sequence polarity and measure held-out accuracy",
[15, True, True, True],
[len(epoch_losses), epoch_losses[-1] < epoch_losses[0], not model.training, test_acc >= 0.85],
first_loss=round(epoch_losses[0], 5), final_loss=round(epoch_losses[-1], 5),
test_correct=correct, test_total=len(test_ds), test_accuracy=round(test_acc, 4))
def check_detach_and_clip(cases):
torch.manual_seed(5)
model = CharRNN(4, 6)
x = torch.eye(4).unsqueeze(0)
targets = torch.tensor([1, 2, 3, 0])
criterion = nn.CrossEntropyLoss()
# Step 1: Without detach(), reusing hidden across two backward passes fails.
out1, h1 = model(x, None)
criterion(out1.view(-1, 4), targets).backward()
out2, _ = model(x, h1)
second_backward_error = ""
try:
criterion(out2.view(-1, 4), targets).backward()
except RuntimeError as err:
second_backward_error = str(err)
# Step 2: With detach(), graph history is cut and second backward succeeds.
model.zero_grad(set_to_none=True)
out1, h1 = model(x, None)
criterion(out1.view(-1, 4), targets).backward()
h1_detached = h1.detach()
model.zero_grad(set_to_none=True)
out2, _ = model(x, h1_detached)
criterion(out2.view(-1, 4), targets).backward()
detached_grad_ok = all(p.grad is not None for p in model.parameters())
# Step 3: Gradient clipping bounds large L2 gradient norm.
for p in model.parameters():
p.grad.mul_(100.0)
pre_clip = float(torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0))
post_clip = float(torch.sqrt(sum(p.grad.detach().square().sum() for p in model.parameters())))
record(cases, "hidden_detach_and_clip", {"max_norm": 1.0},
"Two sequential passes reusing hidden state, plus synthetic large gradients",
"Contrast missing detach RuntimeError, detached truncated BPTT and clip_grad_norm_",
[True, False, True, True, True],
["backward through the graph a second time" in second_backward_error,
h1_detached.requires_grad, detached_grad_ok, pre_clip > 1.0, abs(post_clip - 1.0) < 1e-5],
pre_clip_norm=round(pre_clip, 4), post_clip_norm=round(post_clip, 6))
def check_char_sequence_and_plot(cases, fig_dir):
raw_list = list("hello")
vocab = list(dict.fromkeys("hello"))
c2i = {c: i for i, c in enumerate(vocab)}
i2c = {i: c for i, c in enumerate(vocab)}
in_ids = [c2i[c] for c in "hello"]
tgt_ids = [c2i[c] for c in "elloh"]
one_hot = np.eye(len(vocab), dtype=np.float32)[in_ids]
record(cases, "vocab_dedup_onehot", {"input": "hello", "target": "elloh"},
"Deduplicated character vocabulary vs raw list('hello')",
"Verify unique vocabulary size 4, round-trip mapping and one-hot tensor shape",
[5, 4, ["h", "e", "l", "o"], [5, 4], "hello", "elloh"],
[len(raw_list), len(vocab), vocab, list(one_hot.shape),
"".join(i2c[i] for i in in_ids), "".join(i2c[i] for i in tgt_ids)])
inputs = torch.from_numpy(one_hot).unsqueeze(0)
targets = torch.tensor(tgt_ids, dtype=torch.long)
torch.manual_seed(17)
model = CharRNN(len(vocab), hidden_size=12)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.05)
losses = []
for _ in range(120):
optimizer.zero_grad(set_to_none=True)
outputs, _ = model(inputs, None)
loss = criterion(outputs.view(-1, len(vocab)), targets)
loss.backward()
optimizer.step()
losses.append(loss.item())
model.eval()
with torch.inference_mode():
logits, _ = model(inputs, None)
pred_ids = logits.argmax(dim=2).squeeze(0).tolist()
pred_str = "".join(i2c[i] for i in pred_ids)
record(cases, "hello_sequence_training", {"epochs": 120, "hidden_size": 12, "lr": 0.05},
"Reset hidden=None per independent sequence pass; Adam optimizer",
"Train character rotation hello -> elloh and inspect final loss and prediction",
[120, True, True, "elloh"],
[len(losses), losses[-1] < losses[0], losses[-1] < 0.02, pred_str],
epoch20_loss=round(losses[19], 5), final_loss=round(losses[-1], 5), predicted=pred_str)
import matplotlib
matplotlib.use("Agg")
from matplotlib import pyplot as plt
fig_dir.mkdir(parents=True, exist_ok=True)
fig, ax = plt.subplots(figsize=(7.2, 3.6), layout="constrained")
epochs = list(range(1, len(losses) + 1))
line, = ax.plot(epochs, losses, color="#174d79", linewidth=2.2, label="Training Loss (hello -> elloh)")
ax.set_title("PyTorch RNN Character Sequence Training Loss", color="#173b55", fontweight="bold")
ax.set_xlabel("Epoch")
ax.set_ylabel("Cross-Entropy Loss")
ax.grid(True, linestyle="--", alpha=0.45)
ax.legend()
out_png = fig_dir / "rnn-char-loss.png"
fig.savefig(out_png, dpi=125, facecolor="#f7fafb")
plt.close(fig)
with Image.open(out_png) as png:
assert png.format == "PNG"
width, height = png.size
plotted_y = line.get_ydata().tolist()
record(cases, "observed_rnn_loss_plot", {"points": len(losses)},
"Matplotlib Agg backend from real 120-epoch RNN loss history",
"Check plotted loss array matches recorded training history and PNG size",
[True, 900, 450],
[np.allclose(plotted_y, losses), width, height])
return matplotlib.__version__, {out_png.name: sha256(out_png.read_bytes()).hexdigest()}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--figures", type=Path, default=Path("charts"))
args = parser.parse_args()
torch.set_num_threads(1)
cases = []
check_recurrence_and_variants(cases)
check_sequence_classification(cases)
check_detach_and_clip(cases)
mpl_ver, figs = check_char_sequence_and_plot(cases, args.figures)
print(json.dumps(dict(
version=platform.python_version(), system=platform.system(), torch=torch.__version__,
numpy=np.__version__, matplotlib=mpl_ver, cases=cases, figures=figs,
), allow_nan=False))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 选择对应构建并运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
detach() 切断前一轮计算图历史,避免第二次 backward 重复遍历已释放图;梯度裁剪 clip_grad_norm_ 则用于在反向传播后限制梯度范数上限。