首页 > 其他分享 >《动手学深度学习 Pytorch版》 8.6 循环神经网络的简洁实现

《动手学深度学习 Pytorch版》 8.6 循环神经网络的简洁实现

时间:2023-10-12 11:03:36浏览次数:43  
标签:vocab rnn 8.6 self torch 神经网络 Pytorch num size

import torch
from torch import nn
from torch.nn import functional as F
from d2l import torch as d2l

batch_size, num_steps = 32, 35
train_iter, vocab = d2l.load_data_time_machine(batch_size, num_steps)

8.6.1 定义模型

num_hiddens = 256
rnn_layer = nn.RNN(len(vocab), num_hiddens)
state = torch.zeros((1, batch_size, num_hiddens))
state.shape  # (隐藏层数,批量大小,隐藏单元数)
torch.Size([1, 32, 256])

通过一个隐状态和一个输入可以用更新后的隐状态计算输出。

需要强调的是,rnn_layer的“输出”(Y)不涉及输出层的计算:它是指每个时间步的隐状态,这些隐状态可以用作后续输出层的输入。

X = torch.rand(size=(num_steps, batch_size, len(vocab)))
Y, state_new = rnn_layer(X, state)
Y.shape, state_new.shape
(torch.Size([35, 32, 256]), torch.Size([1, 32, 256]))
#@save
class RNNModel(nn.Module):
    """循环神经网络模型"""
    def __init__(self, rnn_layer, vocab_size, **kwargs):
        super(RNNModel, self).__init__(**kwargs)
        self.rnn = rnn_layer
        self.vocab_size = vocab_size
        self.num_hiddens = self.rnn.hidden_size
        # 如果RNN是双向的(之后将介绍),num_directions应该是2,否则应该是1
        if not self.rnn.bidirectional:
            self.num_directions = 1
            self.linear = nn.Linear(self.num_hiddens, self.vocab_size)
        else:
            self.num_directions = 2
            self.linear = nn.Linear(self.num_hiddens * 2, self.vocab_size)

    def forward(self, inputs, state):
        X = F.one_hot(inputs.T.long(), self.vocab_size)
        X = X.to(torch.float32)
        Y, state = self.rnn(X, state)
        # 全连接层首先将Y的形状改为(时间步数*批量大小,隐藏单元数)
        # 它的输出形状是(时间步数*批量大小,词表大小)。
        output = self.linear(Y.reshape((-1, Y.shape[-1])))
        return output, state

    def begin_state(self, device, batch_size=1):
        if not isinstance(self.rnn, nn.LSTM):
            # nn.GRU以张量作为隐状态
            return  torch.zeros((self.num_directions * self.rnn.num_layers,
                                 batch_size, self.num_hiddens),
                                device=device)
        else:
            # nn.LSTM以元组作为隐状态
            return (torch.zeros((
                self.num_directions * self.rnn.num_layers,
                batch_size, self.num_hiddens), device=device),
                    torch.zeros((
                        self.num_directions * self.rnn.num_layers,
                        batch_size, self.num_hiddens), device=device))

8.6.2 训练与预测

device = d2l.try_gpu()
net = RNNModel(rnn_layer, vocab_size=len(vocab))
net = net.to(device)
d2l.predict_ch8('time traveller', 10, net, vocab, device)
'time travellerffffffffff'
num_epochs, lr = 500, 1
d2l.train_ch8(net, train_iter, vocab, lr, num_epochs, device)  # 比自己写的跑得快
perplexity 1.3, 213489.4 tokens/sec on cuda:0
time traveller held in his han so withtre scon the thin one mige
travellericho for the prof read haly and hes it nople hat d

image

练习

(1)尝试使用高级API,能使循环神经网络模型过拟合吗?

略。


(2)如果在循环神经网络模型中增加隐藏层的数量会发生什么?能使模型正常工作吗?

num_hiddens1 = 1024
rnn_layer1 = nn.RNN(len(vocab), num_hiddens1)

net1 = RNNModel(rnn_layer1, vocab_size=len(vocab))
net1 = net1.to(device)

num_epochs, lr = 500, 1
d2l.train_ch8(net1, train_iter, vocab, lr, num_epochs, device)  # 效果更好了,但是曲线没那么平滑了
perplexity 1.0, 97329.8 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

image


(3)尝试使用循环神经网络实现 8.1 节的自回归模型。

标签:vocab,rnn,8.6,self,torch,神经网络,Pytorch,num,size
From: https://www.cnblogs.com/AncilunKiang/p/17758981.html

相关文章

  • pytorch(8-6) 循环神经网络的简洁实现
     https://zh.d2l.ai/chapter_recurrent-neural-networks/rnn-concise.html# 86循环神经网络的简洁.pyimporttorchfromtorchimportnnfromtorch.nnimportfunctionalasFfromd2limporttorchasd2lfromAPI_86import*batch_size,num_steps=32,35tra......
  • pytorch(8-6) 循环神经网络的简洁实现
    https://zh.d2l.ai/chapter_recurrent-neural-networks/rnn-concise.html API_85.pyimportcollectionsimportrefromd2limporttorchasd2limportrandomimportmathimporttorchimportrandomdraw_pic=0#@saved2l.DATA_HUB['time_machine']=......
  • 《动手学深度学习 Pytorch版》 8.5 循环神经网络的从零开始实现
    %matplotlibinlineimportmathimporttorchfromtorchimportnnfromtorch.nnimportfunctionalasFfromd2limporttorchasd2lbatch_size,num_steps=32,35train_iter,vocab=d2l.load_data_time_machine(batch_size,num_steps)#仍然使用时间机器数据集......
  • pytorch nn.KLDivLoss()损失计算
    参考:https://blog.csdn.net/L888666Q/article/details/126346022?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_baidulandingword~default-1-126346022-blog-128974654.235^v38^pc_relevant_default_base&spm=1001.2101.3001.4242.2&utm_relev......
  • 《动手学深度学习 Pytorch版》 8.4 循环神经网络
    8.4.1无隐状态的神经网络对于无隐藏装态的神经网络来说,给定一个小批量样本\(\boldsymbol{X}\in\mathbb{R}^{n\timesd}\),则隐藏层的输出\(\boldsymbol{H}\in\mathbb{R}^{n\timesh}\)通过下式计算:\[\boldsymbol{H}=\phi(\boldsymbol{XW}_{xh}+\boldsymbol{b}_h)\]\(\phi\)......
  • BP神经网络
    一、感知器(机)上图的圆圈就代表一个感知器。它接受多个输入(x1,x2,x3…),产生一个输出(output),好比神经末梢感受各种外部环境的变化,最后产生电信号。为了简化模型,我们约定每种输入只有两种可能:1或0。如果所有输入都是1,表示各种条件都成立,输出就是1;如果所有输入都是0,表示条件都不成立,输出......
  • 搭建Pytorch2.1+CUDA12.1+Anaconda+Pycharm深度学习环境
    环境:  Win1122H2需要的安装包:Anaconda3-2021.05-Windows-x86_64.exe  Python3.11.(pytorch2.0目前推荐的Python版本为3.8-3.11)pycharm-professional-2021.2.1.exeCUDA12.1与CUDNNV8.9.5pytorch2.1选择性安装OpenCV库一、安装CUDA12.1与C......
  • 《动手学深度学习 Pytorch版》 8.3 语言模型和数据集
    8.3.1学习语言模型依靠在8.1节中对序列模型的分析,可以在单词级别对文本数据进行词元化。基本概率规则如下:\[P(x_1,x_2,\dots,x_T)=\prod^T_{t=1}P(x_t|x_1,\dots,x_{t-1})\]例如,包含了四个单词的一个文本序列的概率是:\[P(deep,learning,is,fun)=P(deep)P(learning|deep)P(i......
  • pytorch(8-2) 文本语言处理 拆分成字符统计词频并从高到底分配ID
    https://zh.d2l.ai/chapter_recurrent-neural-networks/language-models-and-dataset.html  importcollectionsimportrefromd2limporttorchasd2l#@saved2l.DATA_HUB['time_machine']=(d2l.DATA_URL+'timemachine.txt',......
  • 安装pytorch报错,没解决
    environmentvariables:CIO_TEST=CLASS_PATH=.:/exe/jdk/jdk1.8.0_341/lib/dt.jar:/exe/jdk/jdk1.8.0_341/lib/tools.jar:/exe/jdk/jdk1.8.0_341/jre/libCONDA_DEFAULT_ENV=test1CONDA_EXE=/exe/conda/yes/bin/condaCONDA_PREFIX=/exe/conda/yes/envs/test1CONDA_PROMP......