李沐55_循环神经网络RNN简洁实现——自学笔记

读取《时间机器》数据集

!pip install d2l
!pip install --upgrade d2l==0.17.5  #d2l需要更新
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)
Downloading ../data/timemachine.txt from http://d2l-data.s3-accelerate.amazonaws.com/timemachine.txt...

定义模型

构造一个具有256个隐藏单元的单隐藏层的循环神经网络层rnn_layer。

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 =

你可能感兴趣的:(rnn,深度学习,神经网络,pytorch,循环神经网络,python,李沐)