蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行循环神经网络递推、分类与字符序列实验

PYTHONWindows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。train-rnn-sequence.py
train-rnn-sequence.py259 行
"""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()
本例需在 Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。

入口文件:projects/pytorch-recurrent-neural-network-lab/train-rnn-sequence.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 train-rnn-sequence.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:PyTorch

课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a409.zip

下载课程关联工程包:PyTorch

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a433.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习