"""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()
本例需在 Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。
入口文件:projects/nlp-recurrent-neural-network-lab/explore-recurrent-neural-network.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-recurrent-neural-network.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a556.zip
课程关联工程包(登记关联21章) · 含当前章节或实例 · mbskycom202612a545.zip