《动手学深度学习 Pytorch版》 9.3 深度循环神经网络

将多层循环神经网络堆叠在一起,通过对几个简单层的组合,产生一个灵活的机制。其中的数据可能与不同层的堆叠有关。

9.3.1 函数依赖关系

将深度架构中的函数依赖关系形式化,第 l l l 个隐藏层的隐状态表达式为:

H t ( l ) = ϕ l ( H t ( l − 1 ) W x h ( l ) + H t − 1 ( l ) W h h ( l ) + b h ( l ) ) \boldsymbol{H}^{(l)}t=\phi_l(\boldsymbol{H}^{(l-1)}t\boldsymbol{W}^{(l)}{xh}+\boldsymbol{H}^{(l)}{t-1}\boldsymbol{W}^{(l)}_{hh}+\boldsymbol{b}^{(l)}_h) Ht(l)=ϕl(Ht(l−1)Wxh(l)+Ht−1(l)Whh(l)+bh(l))

参数字典:

  • ϕ l \phi_l ϕl 表示第 l l l 个隐藏层的激活函数

  • X t ∈ R n × d \boldsymbol{X}_t\in\R^{n\times d} Xt∈Rn×d 表示小批量输入

    • n n n 表示样本个数

    • d d d 表示输入个数

  • H t ( l ) ∈ R n × h \boldsymbol{H}^{(l)}_{t}\in\R^{n\times h} Ht(l)∈Rn×h 表示 l t h l^{th} lth 隐藏层 ( l = 1 , ... , L ) (l=1,\dots,L) (l=1,...,L) 的隐状态

    • h h h 表示隐藏单元个数

    • 设置 H t ( 0 ) = X t \boldsymbol{H}^{(0)}{t}=\boldsymbol{X}{t} Ht(0)=Xt

  • O t ∈ R n × q \boldsymbol{O}_{t}\in\R^{n\times q} Ot∈Rn×q 表示输出层变量

    • q q q 表示输出数
  • W x h ( l ) , W h h ( l ) ∈ R h × h \boldsymbol{W}^{(l)}{xh},\boldsymbol{W}^{(l)}{hh}\in\R^{h\times h} Wxh(l),Whh(l)∈Rh×h 表示第 l l l 个隐藏层的权重参数

  • b h ( l ) ∈ R 1 × h \boldsymbol{b}^{(l)}_h\in\R^{1\times h} bh(l)∈R1×h 表示第 l l l 个隐藏层的偏重参数

最后,输出层的计算仅基于第 l l l 个隐藏层最终的隐状态:

O t = H t L W h q + b q \boldsymbol{O}_t=\boldsymbol{H}^{L}t\boldsymbol{W}{hq}+\boldsymbol{b}_q Ot=HtLWhq+bq

其中 W h q ∈ R h × q \boldsymbol{W}_{hq}\in\R^{h\times q} Whq∈Rh×q 和 b q ∈ R 1 × q \boldsymbol{b}_q\in\R^{1\times q} bq∈R1×q 表示输出层的模型参数

9.3.2 简洁实现

手撸多层循环神经网络有点过于麻烦了,在此仅简单实现。

python 复制代码
import torch
from torch import nn
from d2l import torch as d2l
python 复制代码
batch_size, num_steps = 32, 35
train_iter, vocab = d2l.load_data_time_machine(batch_size, num_steps)
python 复制代码
vocab_size, num_hiddens, num_layers = len(vocab), 256, 2  # 用 num_layers 来设定隐藏层数
num_inputs = vocab_size
device = d2l.try_gpu()
lstm_layer = nn.LSTM(num_inputs, num_hiddens, num_layers)
model = d2l.RNNModel(lstm_layer, len(vocab))
model = model.to(device)

9.3.3 训练与预测

python 复制代码
num_epochs, lr = 500, 2
d2l.train_ch8(model, train_iter, vocab, lr*1.0, num_epochs, device)  # 多了一层后训练速度大幅下降
perplexity 1.0, 116173.5 tokens/sec on cuda:0
time travelleryou can show black is white by argument said filby
travelleryou can show black is white by argument said filby

练习

(1)基于我们在 8.5 节中讨论的单层实现,尝试从零开始实现两层循环神经网络。

python 复制代码
batch_size, num_steps = 32, 35
train_iter, vocab = d2l.load_data_time_machine(batch_size, num_steps)

def get_params_bilayer(vocab_size, num_hiddens, device):
    num_inputs = num_outputs = vocab_size

    def normal(shape):
        return torch.randn(size=shape, device=device) * 0.01

    # 隐藏层1参数
    W_xh1 = normal((num_inputs, num_hiddens))
    W_hh1 = normal((num_hiddens, num_hiddens))
    b_h1 = torch.zeros(num_hiddens, device=device)
    # 新增隐藏层2参数
    W_hh2 = normal((num_hiddens, num_hiddens))
    b_h2 = torch.zeros(num_hiddens, device=device)
    # 输出层参数
    W_hq = normal((num_hiddens, num_outputs))
    b_q = torch.zeros(num_outputs, device=device)
    # 附加梯度
    params = [W_xh1, W_hh1, b_h1, W_hh2, b_h2, W_hq, b_q]
    for param in params:
        param.requires_grad_(True)
    return params

def init_rnn_state_bilayer(batch_size, num_hiddens, device):
    return (torch.zeros((batch_size, num_hiddens), device=device),
            torch.zeros((batch_size, num_hiddens), device=device))  # 新增第二个隐状态初始化张量

def rnn_bilayer(inputs, state, params):  # inputs的形状:(时间步数量,批量大小,词表大小)
    W_xh1, W_hh1, b_h1, W_hh2, b_h2, W_hq, b_q = params  # 新增第二层参数
    H1, H2 = state
    outputs = []
    for X in inputs:  # X的形状:(批量大小,词表大小) 前面转置是为了这里遍历
        H1 = torch.tanh(torch.mm(X, W_xh1) + torch.mm(H1, W_hh1) + b_h1)  # 计算隐状态1
        H2 = torch.tanh(torch.mm(H1, W_hh2) + b_h2)  # 计算隐状态2
        Y = torch.mm(H2, W_hq) + b_q  # 计算输出
        outputs.append(Y)
    return torch.cat(outputs, dim=0), (H1, H2)  # 沿时间步拼接

num_hiddens = 512
net_rnn_bilayer = d2l.RNNModelScratch(len(vocab), num_hiddens, d2l.try_gpu(), get_params_bilayer,
                      init_rnn_state_bilayer, rnn_bilayer)
num_epochs, lr = 500, 1
d2l.train_ch8(net_rnn_bilayer, train_iter, vocab, lr, num_epochs, d2l.try_gpu())
perplexity 1.0, 63514.3 tokens/sec on cuda:0
time travelleryou can show black is white by argument said filby
travelleryou can show black is white by argument said filby

(2)在本节训练模型中,比较使用门控循环单元替换长短期记忆网络后模型的精确度和训练速度。

python 复制代码
vocab_size, num_hiddens, num_layers = len(vocab), 256, 2  # 用 num_layers 来设定隐藏层数
num_inputs = vocab_size
device = d2l.try_gpu()
# lstm_layer = nn.LSTM(num_inputs, num_hiddens, num_layers)
# model = d2l.RNNModel(lstm_layer, len(vocab))
gru_layer = nn.GRU(num_inputs, num_hiddens)
model_gru = d2l.RNNModel(gru_layer, len(vocab))
model_gru = model_gru.to(device)

num_epochs, lr = 500, 2
d2l.train_ch8(model_gru, train_iter, vocab, lr*1.0, num_epochs, device)  # 换 gru 后更快了
perplexity 1.0, 230590.6 tokens/sec on cuda:0
time traveller for so it will be convenient to speak of himwas e
travelleryou can show black is white by argument said filby

(3)如果增加训练数据,能够将困惑度降到多低?

已经是 1 了,没得降了。


(4)在为文本建模时,是否可以将不同作者的源数据合并?有何优劣呢?

不同作者的数据源之间可能没有什么关系,拼在一起可能效果反而下降。

相关推荐
9命怪猫6 分钟前
DeepSeek底层揭秘——微调
人工智能·深度学习·神经网络·ai·大模型
Jackilina_Stone1 小时前
【论文阅读笔记】浅谈深度学习中的知识蒸馏 | 关系知识蒸馏 | CVPR 2019 | RKD
论文阅读·深度学习·蒸馏·rkd
倒霉蛋小马3 小时前
【YOLOv8】损失函数
深度学习·yolo·机器学习
Fansv5873 小时前
深度学习-2.机械学习基础
人工智能·经验分享·python·深度学习·算法·机器学习
小怪兽会微笑4 小时前
PyTorch Tensor 形状变化操作详解
人工智能·pytorch·python
IT古董5 小时前
【深度学习】计算机视觉(CV)-目标检测-DETR(DEtection TRansformer)—— 基于 Transformer 的端到端目标检测
深度学习·目标检测·计算机视觉
Jackilina_Stone5 小时前
【论文阅读笔记】知识蒸馏:一项调查 | CVPR 2021 | 近万字翻译+解释
论文阅读·人工智能·深度学习·蒸馏
咩咩大主教5 小时前
人工智能神经网络
人工智能·python·深度学习·神经网络·机器学习·bp神经网络
三年呀5 小时前
计算机视觉之图像处理-----SIFT、SURF、FAST、ORB 特征提取算法深度解析
图像处理·python·深度学习·算法·目标检测·机器学习·计算机视觉
ITPUB-微风6 小时前
58同城深度学习推理平台:基于Istio的云原生网关实践解析
深度学习·云原生·istio