循环神经网络(RNN)
系统核对标准 RNN 循环机制与梯度消失/爆炸、LSTM 三门一单元、GRU 双门结构、GRU vs LSTM 对比及双向 RNN;修复来源 GRUCell 缺失右括号 SyntaxError 与未定义 sigmoid,并以纯 NumPy 完成完整 BPTT 梯度校验及 5 项序列实测。
学完这一章,你能够
- 系统核对标准 RNN 循环机制与梯度消失/爆炸、LSTM 三门一单元、GRU 双门结构、GRU vs LSTM 对比及双向 RNN;修复来源 GRUCell 缺失右括号 SyntaxError 与未定义 sigmoid,并以纯 NumPy 完成完整 BPTT 梯度校验及 5 项序列实测。
RNN 核心思想、工作机制与纯 NumPy BPTT 实测
循环神经网络(Recurrent Neural Network,RNN)专为文本、语音与时间序列等变长序列设计。与各样本独立前向计算的传统前馈网络不同,RNN 借助循环连接把上一时间步的隐藏状态 h_{t-1} 传入当前步,使当前输出同时依赖当前输入与全部历史上下文(恰如阅读“他打开了__”时依据前文预测“门”或“书”)。
在每个时间步 t,标准 RNN 接收输入 x_t 与历史状态 h_{t-1},按 h_t = f(W_hh·h_{t-1} + W_xh·x_t + b) 更新隐状态并由 y_t = g(W_hy·h_t + c) 输出(f、g 常取 tanh 与 softmax)。其优点是支持变长序列、跨时间步共享权重且理论上可编码任意历史,缺点是串行依赖难以时间并行,以及深层时间展开后极易出现梯度消失或爆炸。本站以纯 NumPy 实现了含完整时间反向传播(BPTT)的字符级 SimpleRNN 语言模型(覆盖练习 1):解析 BPTT 梯度与中心差分数值梯度相对误差仅 2.56e-09,在 7 字符序列 “hello_nlp_” 上经 180 轮训练,交叉熵损失由 1.9925 降至 0.0251、下一字符预测准确率达 1.0;同时在 20 步雅可比连乘实验中测得谱半径 0.5 时梯度衰减至 3.42e-07(消失)、谱半径 1.6 时膨胀至 4330.0(爆炸)。
长短期记忆网络(LSTM)结构与长距离梯度通路
长短期记忆网络(LSTM)在隐状态 h_t 之外增设独立记忆单元 c_t,并通过遗忘门 f_t、输入门 i_t 与输出门 o_t 三个 Sigmoid 门控精确调控信息流(各组件职责见下表):c_t = f_t ⊙ c_{t-1} + i_t ⊙ c̃_t,h_t = o_t ⊙ tanh(c_t)。由于记忆单元按加性通道跨步传递,当遗忘门接近 1 时梯度 ∂c_T/∂c_0 ≈ ∏ f_t 避免连乘收缩(本站实测 20 步 f_t=0.95 梯度通路范数保持 0.3585,远优于标准 RNN 的 3.42e-07),从而通过选择性记忆、直通梯度与信息保护显著缓解长期依赖衰减。
门控循环单元(GRU)、源码语法修复与 LSTM 对比
门控循环单元(GRU)省去独立细胞状态 c_t,将门控精简为更新门 z_t 与重置门 r_t(组件及与 LSTM 对比见下两表):h̃_t = tanh(W_c·[r_t ⊙ h_{t-1}, x_t] + b_c),h_t = (1 - z_t) ⊙ h_{t-1} + z_t ⊙ h̃_t。代码勘误:来源 GRUCell 与 LSTMCell 均直接调用未定义的 sigmoid(...),且来源 GRUCell 计算 h_candidate 时末尾缺少一个闭合右括号 ) 导致真实 SyntaxError。本站补全数值稳定 sigmoid 并修复括号后,在 D=8, H=16 下实测 LSTM 共 1600 参数、GRU 共 1200 参数(精确缩减 25.0%),且极限门控测试(遗忘门置 1/0 与更新门置 0)记忆保持和清零误差均 <= 1.65e-09。
双向 RNN 架构验证、模型对比实验与进阶方向
双向 RNN(Bi-RNN,实践常以 LSTM 或 GRU 为基础单元)并行运行按时间正序与逆序扫描的两个独立循环层,将各时刻双向隐状态拼接或求和输出,同时融合过去与未来语境,广泛应用于词性标注、命名实体识别、语音识别、蛋白质结构预测和离线时间序列分析。本站用纯 NumPy 构建前向+反向双向 LSTM(序列长 6、D=4、H=8),验证拼接形状 (6, 16) 与求和形状 (6, 8),且仅扰动序列末步 x_5 时,首步 t=0 的前向状态差为 0.0(对未来完全盲区)而反向与双向状态产生 0.022011 的可观测响应。
针对文末四项实践练习,练习 1 纯 NumPy 字符级 RNN+BPTT 已完整跑通,练习 4 同维(D=4, H=8)对比实测参数量严格递增 RNN 104 < GRU 312 < LSTM 416,且 15 步零输入初始信号留存率标准 RNN 跌至 0.00317、而门控 GRU 与 LSTM 均保持 0.4825;练习 2(Keras LSTM 电影评论情感分析)与练习 3(双向 GRU 实体识别)涉及 TensorFlow/Keras 框架与外部数据集,记录为后续深度框架环境待办。深入学习 RNN 后,建议继续沿着梯度流分析、注意力增强 RNN、Transformer 替代架构以及机器翻译/语音合成实践进阶。
LSTM 核心门控与记忆单元组件
| 组件 | 功能 |
| 输入门 | 经 Sigmoid 输出 (0,1) 权重,控制当前候选记忆流入细胞状态的比例 |
| 遗忘门 | 决定上一时刻细胞状态 c_{t-1} 中保留或丢弃的历史信息比例 |
| 输出门 | 控制当前细胞状态经 tanh 激活后暴露给隐状态 h_t 的信息量 |
| 记忆单元 | 以加性通路 c_t = f_t*c_{t-1} + i_t*c̃_t 保存长期状态并稳定梯度传播 |
GRU 核心门控组件
| 组件 | 功能 |
| 更新门 | 决定保留旧隐状态 h_{t-1} 与接纳候选新状态 h̃_t 的线性插值权重 z_t |
| 重置门 | 控制计算候选状态时对上一时刻隐状态 h_{t-1} 的截断与组合程度 |
| 候选激活 | 基于重置门调制后的历史状态与当前输入经 tanh 计算的候选隐状态 |
GRU 与 LSTM 关键特性对比
| 特性 | GRU | LSTM |
| 参数数量 | 较少(3*H*(D+H+1),实测 D=8,H=16 为 1200 参,少 25%) | 较多(4*H*(D+H+1),实测 D=8,H=16 为 1600 参) |
| 训练速度 | 矩阵乘法少一组门控,单步计算与迭代通常更快 | 多一组门控及细胞状态更新,计算开销相对较高 |
| 记忆单元 | 无独立细胞状态,仅维护单一隐状态 h_t | 有独立细胞状态 c_t 与隐状态 h_t 分离存储 |
| 门控数量 | 2 个(更新门、重置门) | 3 个(遗忘门、输入门、输出门) |
| 性能 | 参数紧凑,中小数据集上不易过拟合、表现常具优势 | 表达容量更大,在大规模复杂长序列任务中可能更具潜力 |
运行纯 NumPy SimpleRNN BPTT 梯度检验、梯度消失/爆炸对比、LSTM/GRU 门控与参数量及双向 LSTM 实验
展开查看收起
"""Independent offline NLP lab for Ch 11 (RNN): pure-NumPy Vanilla RNN BPTT, vanishing/exploding vs LSTM gradient highway, LSTM/GRU cells & params, Bi-RNN."""
import json
import platform
import numpy as np
def sigmoid(x: np.ndarray) -> np.ndarray:
x_clip = np.clip(x, -50.0, 50.0)
return 1.0 / (1.0 + np.exp(-x_clip))
def softmax(logits: np.ndarray) -> np.ndarray:
shifted = logits - np.max(logits, axis=0, keepdims=True)
exps = np.exp(shifted)
return exps / np.sum(exps, axis=0, keepdims=True)
class SimpleRNNCell:
def __init__(self, input_size: int, hidden_size: int, seed: int = 42):
rng = np.random.default_rng(seed)
self.wx = rng.normal(0.0, 0.25, size=(hidden_size, input_size))
self.wh = rng.normal(0.0, 0.25, size=(hidden_size, hidden_size))
self.b = np.zeros((hidden_size, 1))
def forward(self, x: np.ndarray, h_prev: np.ndarray) -> np.ndarray:
return np.tanh(self.wx @ x + self.wh @ h_prev + self.b)
class LSTMCell:
def __init__(self, input_size: int, hidden_size: int, seed: int = 42):
rng = np.random.default_rng(seed)
self.h = hidden_size
self.w = rng.normal(0.0, 0.2, size=(4 * hidden_size, input_size + hidden_size))
self.b = np.zeros((4 * hidden_size, 1))
def param_count(self) -> int:
return int(self.w.size + self.b.size)
def forward(self, x: np.ndarray, h_prev: np.ndarray, c_prev: np.ndarray):
combined = np.vstack((h_prev, x))
gates = self.w @ combined + self.b
h = self.h
f_gate = sigmoid(gates[:h])
i_gate = sigmoid(gates[h:2 * h])
o_gate = sigmoid(gates[2 * h:3 * h])
c_cand = np.tanh(gates[3 * h:])
c_next = f_gate * c_prev + i_gate * c_cand
h_next = o_gate * np.tanh(c_next)
return h_next, c_next, (f_gate, i_gate, o_gate, c_cand)
class GRUCell:
def __init__(self, input_size: int, hidden_size: int, seed: int = 42):
rng = np.random.default_rng(seed)
self.h = hidden_size
self.w = rng.normal(0.0, 0.2, size=(3 * hidden_size, input_size + hidden_size))
self.b = np.zeros((3 * hidden_size, 1))
def param_count(self) -> int:
return int(self.w.size + self.b.size)
def forward(self, x: np.ndarray, h_prev: np.ndarray):
combined = np.vstack((h_prev, x))
gates = self.w[:2 * self.h] @ combined + self.b[:2 * self.h]
z = sigmoid(gates[:self.h])
r = sigmoid(gates[self.h:2 * self.h])
# Fixes missing closing parenthesis syntax bug in source CODE 2
h_cand = np.tanh(self.w[2 * self.h:] @ np.vstack((r * h_prev, x)) + self.b[2 * self.h:])
h_next = (1.0 - z) * h_prev + z * h_cand
return h_next, (z, r, h_cand)
def run_cases():
cases = []
# 1. Pure-NumPy Vanilla RNN with exact BPTT gradient check & char-level sequence learning (CODE 0 + Exercise 1)
seq_text = "hello_nlp_"
chars = sorted(set(seq_text))
c2i = {ch: i for i, ch in enumerate(chars)}
v_size = len(chars)
h_size = 12
xs_idx = [c2i[ch] for ch in seq_text[:-1]]
ys_idx = [c2i[ch] for ch in seq_text[1:]]
rng = np.random.default_rng(42)
wx = rng.normal(0.0, 0.25, size=(h_size, v_size))
wh = rng.normal(0.0, 0.25, size=(h_size, h_size))
wy = rng.normal(0.0, 0.25, size=(v_size, h_size))
bh = np.zeros((h_size, 1))
by = np.zeros((v_size, 1))
def loss_and_grads(wx_, wh_, wy_, bh_, by_):
hs = {-1: np.zeros((h_size, 1))}
ps = {}
loss = 0.0
for t, (xi, yi) in enumerate(zip(xs_idx, ys_idx)):
x_oh = np.zeros((v_size, 1))
x_oh[xi, 0] = 1.0
hs[t] = np.tanh(wx_ @ x_oh + wh_ @ hs[t - 1] + bh_)
ps[t] = softmax(wy_ @ hs[t] + by_)
loss -= float(np.log(max(float(ps[t][yi, 0]), 1e-12)))
dwx = np.zeros_like(wx_)
dwh = np.zeros_like(wh_)
dwy = np.zeros_like(wy_)
dbh = np.zeros_like(bh_)
dby = np.zeros_like(by_)
dh_next = np.zeros((h_size, 1))
for t in reversed(range(len(xs_idx))):
dy = ps[t].copy()
dy[ys_idx[t], 0] -= 1.0
dwy += dy @ hs[t].T
dby += dy
dh = wy_.T @ dy + dh_next
dtanh = (1.0 - hs[t] ** 2) * dh
dbh += dtanh
x_oh = np.zeros((v_size, 1))
x_oh[xs_idx[t], 0] = 1.0
dwx += dtanh @ x_oh.T
dwh += dtanh @ hs[t - 1].T
dh_next = wh_.T @ dtanh
return loss / len(xs_idx), (dwx / len(xs_idx), dwh / len(xs_idx), dwy / len(xs_idx), dbh / len(xs_idx), dby / len(xs_idx)), ps
loss_init, grads_init, _ = loss_and_grads(wx, wh, wy, bh, by)
# Finite-difference check on wh[0, 1]
eps = 1e-6
wh_plus = wh.copy()
wh_plus[0, 1] += eps
wh_minus = wh.copy()
wh_minus[0, 1] -= eps
l_plus, _, _ = loss_and_grads(wx, wh_plus, wy, bh, by)
l_minus, _, _ = loss_and_grads(wx, wh_minus, wy, bh, by)
num_grad = (l_plus - l_minus) / (2 * eps)
ana_grad = float(grads_init[1][0, 1])
grad_rel_err = abs(num_grad - ana_grad) / max(abs(num_grad) + abs(ana_grad), 1e-12)
lr = 0.25
for _ in range(180):
_, (dwx, dwh, dwy, dbh, dby), _ = loss_and_grads(wx, wh, wy, bh, by)
for g in (dwx, dwh, dwy, dbh, dby):
np.clip(g, -5.0, 5.0, out=g)
wx -= lr * dwx
wh -= lr * dwh
wy -= lr * dwy
bh -= lr * dbh
by -= lr * dby
loss_final, _, ps_final = loss_and_grads(wx, wh, wy, bh, by)
preds = [int(np.argmax(ps_final[t])) for t in range(len(ys_idx))]
acc = sum(1 for p, y in zip(preds, ys_idx) if p == y) / len(ys_idx)
c1_ok = grad_rel_err < 1e-6 and loss_final < 0.08 and acc == 1.0
cases.append(dict(
name="vanilla_rnn_bptt_char_lm",
inputs=dict(sequence=seq_text, vocab_size=v_size, hidden_size=h_size, epochs=180),
prerequisites="纯 NumPy 实现 SimpleRNN 前向传播与完整时间反向传播(BPTT)训练字符级语言模型。",
action="验证解析 BPTT 梯度与中心差分数值梯度相对误差 <1e-6,并在 180 轮训练后检查交叉熵收敛与下一字符预测准确率。",
expected=dict(bptt_grad_check_passed=True, loss_below_008=True, next_char_acc_1=True),
actual=dict(
bptt_grad_check_passed=(grad_rel_err < 1e-6),
loss_below_008=(loss_final < 0.08),
next_char_acc_1=(acc == 1.0),
),
measurements=dict(
bptt_grad_rel_err=float(f"{grad_rel_err:.2e}"),
loss_init=round(loss_init, 4),
loss_final=round(loss_final, 4),
next_char_acc=round(acc, 4),
),
passed=c1_ok,
))
# 2. Vanishing vs Exploding gradients in Vanilla RNN vs LSTM cell-state highway across T=20 steps
steps = 20
# Orthogonal matrix scaled by spectral radius rho
q_mat, _ = np.linalg.qr(np.random.default_rng(1).normal(size=(8, 8)))
wh_vanish = 0.5 * q_mat
wh_explode = 1.6 * q_mat
# Linearized Jacobian product ||prod(diag(1-h^2) Wh)|| with small pre-activations (sech^2 ~ 0.95)
sech2 = 0.95
jac_vanish = np.eye(8)
jac_explode = np.eye(8)
for _ in range(steps):
jac_vanish = (sech2 * wh_vanish) @ jac_vanish
jac_explode = (sech2 * wh_explode) @ jac_explode
norm_vanish = float(np.linalg.norm(jac_vanish, ord=2))
norm_explode = float(np.linalg.norm(jac_explode, ord=2))
# LSTM cell-state highway: dc_T / dc_0 = prod_{t=1}^T f_t with f_t = 0.95
lstm_highway_norm = float(0.95 ** steps)
c2_ok = norm_vanish < 1e-5 and norm_explode > 1000.0 and 0.30 < lstm_highway_norm < 0.40
cases.append(dict(
name="rnn_vanishing_exploding_gradients",
inputs=dict(sequence_steps=steps, rho_vanish=0.5, rho_explode=1.6, lstm_forget_gate=0.95),
prerequisites="在 20 个时间步上沿隐状态雅可比连乘测量谱半径 0.5(梯度消失)、1.6(梯度爆炸)与 LSTM 记忆单元直通路径。",
action="对比三者的 20 步梯度传递范数,验证遗忘门接近 1 时记忆单元可稳定保留长距离梯度。",
expected=dict(vanishing_lt_1e5=True, exploding_gt_1000=True, lstm_highway_stable=True),
actual=dict(
vanishing_lt_1e5=(norm_vanish < 1e-5),
exploding_gt_1000=(norm_explode > 1000.0),
lstm_highway_stable=(0.30 < lstm_highway_norm < 0.40),
),
measurements=dict(
rnn_vanish_grad_norm=float(f"{norm_vanish:.2e}"),
rnn_explode_grad_norm=float(f"{norm_explode:.2e}"),
lstm_cell_highway_norm=round(lstm_highway_norm, 4),
),
passed=c2_ok,
))
# 3. LSTMCell & corrected GRUCell parameter counts (4 vs 3 blocks) & selective-memory gate checks (CODE 1 & CODE 2)
d_in, d_h = 8, 16
lstm = LSTMCell(d_in, d_h, seed=42)
gru = GRUCell(d_in, d_h, seed=42)
exp_lstm_params = 4 * d_h * (d_in + d_h + 1) # 1600
exp_gru_params = 3 * d_h * (d_in + d_h + 1) # 1200
x0 = np.ones((d_in, 1)) * 0.5
h0 = np.ones((d_h, 1)) * 0.25
c0 = np.ones((d_h, 1)) * 0.8
h_l, c_l, (fg, ig, og, _) = lstm.forward(x0, h0, c0)
h_g, (zg, rg, _) = gru.forward(x0, h0)
gates_in_01 = all(
float(g.min()) > 0.0 and float(g.max()) < 1.0 for g in (fg, ig, og, zg, rg)
)
# Selective memory extreme test: LSTM with f_bias=+20, i_bias=-20 preserves c0 exactly; f_bias=-20, i_bias=-20 erases c0
lstm_keep = LSTMCell(d_in, d_h, seed=42)
lstm_keep.w[:] = 0.0
lstm_keep.b[:d_h] = 20.0
lstm_keep.b[d_h:2 * d_h] = -20.0
_, c_kept, _ = lstm_keep.forward(x0, h0, c0)
keep_err = float(np.max(np.abs(c_kept - c0)))
lstm_forget = LSTMCell(d_in, d_h, seed=42)
lstm_forget.w[:] = 0.0
lstm_forget.b[:d_h] = -20.0
lstm_forget.b[d_h:2 * d_h] = -20.0
_, c_erased, _ = lstm_forget.forward(x0, h0, c0)
erase_err = float(np.max(np.abs(c_erased)))
# GRU update gate z->0 preserves h0 exactly
gru_keep = GRUCell(d_in, d_h, seed=42)
gru_keep.w[:] = 0.0
gru_keep.b[:d_h] = -20.0
h_g_kept, _ = gru_keep.forward(x0, h0)
gru_keep_err = float(np.max(np.abs(h_g_kept - h0)))
c3_ok = (
lstm.param_count() == exp_lstm_params
and gru.param_count() == exp_gru_params
and gates_in_01
and keep_err < 1e-6
and erase_err < 1e-6
and gru_keep_err < 1e-6
)
cases.append(dict(
name="lstm_and_gru_cell_param_counts",
inputs=dict(input_size=d_in, hidden_size=d_h),
prerequisites="实现纯 NumPy LSTMCell 与修复括号语法缺失及补全 sigmoid 后的 GRUCell。",
action="验证 LSTM 1600 参 vs GRU 1200 参(精确减少 25%)、门控值域 (0,1) 与遗忘/保留极限门控行为。",
expected=dict(lstm_1600_gru_1200=True, gates_bounded_01=True, selective_memory_exact=True),
actual=dict(
lstm_1600_gru_1200=(lstm.param_count() == 1600 and gru.param_count() == 1200),
gates_bounded_01=gates_in_01,
selective_memory_exact=(keep_err < 1e-6 and erase_err < 1e-6 and gru_keep_err < 1e-6),
),
measurements=dict(
lstm_params=lstm.param_count(),
gru_params=gru.param_count(),
gru_param_reduction_pct=round((1.0 - gru.param_count() / lstm.param_count()) * 100.0, 2),
lstm_keep_err=float(f"{keep_err:.2e}"),
lstm_erase_err=float(f"{erase_err:.2e}"),
gru_keep_err=float(f"{gru_keep_err:.2e}"),
),
passed=c3_ok,
))
# 4. Bidirectional LSTM/GRU: proving future token perturbation affects t=0 ONLY in bidirectional/backward pass (CODE 3)
seq_len = 6
d_bi_in, d_bi_h = 4, 8
rng_bi = np.random.default_rng(99)
xs_a = [rng_bi.normal(0.0, 1.0, size=(d_bi_in, 1)) for _ in range(seq_len)]
xs_b = [x.copy() for x in xs_a]
xs_b[-1] = xs_b[-1] + 5.0 # Perturb ONLY the last time step t=5
fwd_cell = LSTMCell(d_bi_in, d_bi_h, seed=10)
bwd_cell = LSTMCell(d_bi_in, d_bi_h, seed=20)
def run_bilstm(xs):
hf, cf = np.zeros((d_bi_h, 1)), np.zeros((d_bi_h, 1))
fwd_outs = []
for x in xs:
hf, cf, _ = fwd_cell.forward(x, hf, cf)
fwd_outs.append(hf)
hb, cb = np.zeros((d_bi_h, 1)), np.zeros((d_bi_h, 1))
bwd_outs = [None] * len(xs)
for t in reversed(range(len(xs))):
hb, cb, _ = bwd_cell.forward(xs[t], hb, cb)
bwd_outs[t] = hb
concat_outs = np.stack([np.vstack((f, b)).ravel() for f, b in zip(fwd_outs, bwd_outs)], axis=0)
sum_outs = np.stack([(f + b).ravel() for f, b in zip(fwd_outs, bwd_outs)], axis=0)
return fwd_outs, bwd_outs, concat_outs, sum_outs
fwd_a, bwd_a, cat_a, sum_a = run_bilstm(xs_a)
fwd_b, bwd_b, cat_b, sum_b = run_bilstm(xs_b)
fwd_t0_diff = float(np.max(np.abs(fwd_a[0] - fwd_b[0])))
bwd_t0_diff = float(np.max(np.abs(bwd_a[0] - bwd_b[0])))
cat_t0_diff = float(np.max(np.abs(cat_a[0] - cat_b[0])))
c4_ok = (
cat_a.shape == (seq_len, 2 * d_bi_h)
and sum_a.shape == (seq_len, d_bi_h)
and fwd_t0_diff == 0.0
and bwd_t0_diff > 1e-4
and cat_t0_diff > 1e-4
)
cases.append(dict(
name="bidirectional_rnn_lstm_gru",
inputs=dict(seq_len=seq_len, input_size=d_bi_in, hidden_size=d_bi_h),
prerequisites="用纯 NumPy 构建前向+反向双独立 LSTM 层,输出拼接 (T, 2H) 与求和 (T, H) 表示。",
action="仅扰动序列末步 x_5,验证 t=0 处前向状态零变化而反向与双向拼接状态均感知未来上下文变化。",
expected=dict(concat_shape_6_16=True, sum_shape_6_8=True, fwd_blind_to_future=True, bwd_captures_future=True),
actual=dict(
concat_shape_6_16=(cat_a.shape == (seq_len, 2 * d_bi_h)),
sum_shape_6_8=(sum_a.shape == (seq_len, d_bi_h)),
fwd_blind_to_future=(fwd_t0_diff == 0.0),
bwd_captures_future=(bwd_t0_diff > 1e-4 and cat_t0_diff > 1e-4),
),
measurements=dict(
concat_shape=list(cat_a.shape),
sum_shape=list(sum_a.shape),
fwd_t0_diff=fwd_t0_diff,
bwd_t0_diff=round(bwd_t0_diff, 6),
),
passed=c4_ok,
))
# 5. Exercise 4: Vanilla RNN vs GRU vs LSTM parameter count & long-horizon cue retention comparison
d_c, h_c = 4, 8
rnn_c = SimpleRNNCell(d_c, h_c, seed=7)
rnn_params = int(rnn_c.wx.size + rnn_c.wh.size + rnn_c.b.size)
gru_c = GRUCell(d_c, h_c, seed=7)
lstm_c = LSTMCell(d_c, h_c, seed=7)
# Compare 15-step cue retention: set recurrent weight spectral norm 0.7 for vanilla RNN vs gate-preserved LSTM/GRU
steps_cmp = 15
q_c, _ = np.linalg.qr(np.random.default_rng(7).normal(size=(h_c, h_c)))
rnn_c.wh = 0.7 * q_c
h_r = np.ones((h_c, 1))
zero_x = np.zeros((d_c, 1))
for _ in range(steps_cmp):
h_r = rnn_c.forward(zero_x, h_r)
rnn_retained = float(np.linalg.norm(h_r) / np.linalg.norm(np.ones((h_c, 1))))
# LSTM with high forget gate bias (b_f=3.0, zero input) & GRU with low update gate bias (b_z=-3.0)
lstm_ret = LSTMCell(d_c, h_c, seed=7)
lstm_ret.w[:] = 0.0
lstm_ret.b[:h_c] = 3.0
lstm_ret.b[h_c:2 * h_c] = -6.0
h_l2, c_l2 = np.zeros((h_c, 1)), np.ones((h_c, 1))
for _ in range(steps_cmp):
h_l2, c_l2, _ = lstm_ret.forward(zero_x, h_l2, c_l2)
lstm_retained = float(np.linalg.norm(c_l2) / np.linalg.norm(np.ones((h_c, 1))))
gru_ret = GRUCell(d_c, h_c, seed=7)
gru_ret.w[:] = 0.0
gru_ret.b[:h_c] = -3.0
h_g2 = np.ones((h_c, 1))
for _ in range(steps_cmp):
h_g2, _ = gru_ret.forward(zero_x, h_g2)
gru_retained = float(np.linalg.norm(h_g2) / np.linalg.norm(np.ones((h_c, 1))))
c5_ok = (
rnn_params < gru_c.param_count() < lstm_c.param_count()
and rnn_retained < 0.01
and lstm_retained > 0.45
and gru_retained > 0.45
)
cases.append(dict(
name="rnn_lstm_gru_sequence_benchmark",
inputs=dict(input_size=d_c, hidden_size=h_c, retention_steps=steps_cmp),
prerequisites="在同等 (D=4, H=8) 维度下对比 Vanilla RNN、GRU 与 LSTM 的参数量与 15 步零输入初始信号留存率。",
action="核对参数量严格满足 RNN < GRU < LSTM,且门控结构(LSTM/GRU)15 步后信号留存远高于标准 RNN。",
expected=dict(param_order_rnn_lt_gru_lt_lstm=True, gated_retention_beats_vanilla=True),
actual=dict(
param_order_rnn_lt_gru_lt_lstm=(rnn_params < gru_c.param_count() < lstm_c.param_count()),
gated_retention_beats_vanilla=(rnn_retained < 0.01 and lstm_retained > 0.45 and gru_retained > 0.45),
),
measurements=dict(
rnn_params=rnn_params,
gru_params=gru_c.param_count(),
lstm_params=lstm_c.param_count(),
rnn_15step_retention=round(rnn_retained, 5),
gru_15step_retention=round(gru_retained, 4),
lstm_15step_retention=round(lstm_retained, 4),
),
passed=c5_ok,
))
print(json.dumps(dict(version=platform.python_version(), system=platform.system(), cases=cases), ensure_ascii=False))
if __name__ == "__main__":
run_cases()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
LSTM 拼接 [h_{t-1}, x_t] 后需要计算遗忘门、输入门、输出门和候选记忆共 4 组线性变换,总参数 4*H*(D+H+1);GRU 仅计算更新门、重置门和候选状态共 3 组线性变换,总参数 3*H*(D+H+1),两者比值恒为 3/4,故精确减少 25%。