循环神经网络的从零开始实现

:label:sec_rnn_scratch

在本节中,我们将根据 :numref:sec_rnn中的描述, 从头开始基于循环神经网络实现字符级语言模型。 这样的模型将在H.G.Wells的时光机器数据集上训练。 和前面 :numref:sec_language_model中介绍过的一样, 我们先读取数据集。

```{.python .input} %matplotlib inline from d2l import mxnet as d2l import math from mxnet import autograd, gluon, np, npx npx.set_np()

  1. ```{.python .input}
  2. #@tab pytorch
  3. %matplotlib inline
  4. from d2l import torch as d2l
  5. import math
  6. import torch
  7. from torch import nn
  8. from torch.nn import functional as F

```{.python .input}

@tab tensorflow

%matplotlib inline from d2l import tensorflow as d2l import math import tensorflow as tf

  1. ```{.python .input}
  2. #@tab all
  3. batch_size, num_steps = 32, 35
  4. train_iter, vocab = d2l.load_data_time_machine(batch_size, num_steps)

```{.python .input}

@tab tensorflow

train_random_iter, vocab_random_iter = d2l.load_data_time_machine( batch_size, num_steps, use_random_iter=True)

  1. ## [**独热编码**]
  2. 回想一下,在`train_iter`中,每个词元都表示为一个数字索引,
  3. 将这些索引直接输入神经网络可能会使学习变得困难。
  4. 我们通常将每个词元表示为更具表现力的特征向量。
  5. 最简单的表示称为*独热编码*(one-hot encoding),
  6. 它在 :numref:`subsec_classification-problem`中介绍过。
  7. 简言之,将每个索引映射为相互不同的单位向量:
  8. 假设词表中不同词元的数目为$N$(即`len(vocab)`),
  9. 词元索引的范围为$0$$N-1$
  10. 如果词元的索引是整数$i$
  11. 那么我们将创建一个长度为$N$的全$0$向量,
  12. 并将第$i$处的元素设置为$1$
  13. 此向量是原始词元的一个独热向量。
  14. 索引为$0$$2$的独热向量如下所示:
  15. ```{.python .input}
  16. npx.one_hot(np.array([0, 2]), len(vocab))

```{.python .input}

@tab pytorch

F.one_hot(torch.tensor([0, 2]), len(vocab))

  1. ```{.python .input}
  2. #@tab tensorflow
  3. tf.one_hot(tf.constant([0, 2]), len(vocab))

我们每次采样的(小批量数据形状是二维张量: (批量大小,时间步数)。) one_hot函数将这样一个小批量数据转换成三维张量, 张量的最后一个维度等于词表大小(len(vocab))。 我们经常转换输入的维度,以便获得形状为 (时间步数,批量大小,词表大小)的输出。 这将使我们能够更方便地通过最外层的维度, 一步一步地更新小批量数据的隐状态。

```{.python .input} X = d2l.reshape(d2l.arange(10), (2, 5)) npx.one_hot(X.T, 28).shape

  1. ```{.python .input}
  2. #@tab pytorch
  3. X = d2l.reshape(d2l.arange(10), (2, 5))
  4. F.one_hot(X.T, 28).shape

```{.python .input}

@tab tensorflow

X = d2l.reshape(d2l.arange(10), (2, 5)) tf.one_hot(tf.transpose(X), 28).shape

  1. ## 初始化模型参数
  2. 接下来,我们[**初始化循环神经网络模型的模型参数**]。
  3. 隐藏单元数`num_hiddens`是一个可调的超参数。
  4. 当训练语言模型时,输入和输出来自相同的词表。
  5. 因此,它们具有相同的维度,即词表的大小。
  6. ```{.python .input}
  7. def get_params(vocab_size, num_hiddens, device):
  8. num_inputs = num_outputs = vocab_size
  9. def normal(shape):
  10. return np.random.normal(scale=0.01, size=shape, ctx=device)
  11. # 隐藏层参数
  12. W_xh = normal((num_inputs, num_hiddens))
  13. W_hh = normal((num_hiddens, num_hiddens))
  14. b_h = d2l.zeros(num_hiddens, ctx=device)
  15. # 输出层参数
  16. W_hq = normal((num_hiddens, num_outputs))
  17. b_q = d2l.zeros(num_outputs, ctx=device)
  18. # 附加梯度
  19. params = [W_xh, W_hh, b_h, W_hq, b_q]
  20. for param in params:
  21. param.attach_grad()
  22. return params

```{.python .input}

@tab pytorch

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

  1. def normal(shape):
  2. return torch.randn(size=shape, device=device) * 0.01
  3. # 隐藏层参数
  4. W_xh = normal((num_inputs, num_hiddens))
  5. W_hh = normal((num_hiddens, num_hiddens))
  6. b_h = d2l.zeros(num_hiddens, device=device)
  7. # 输出层参数
  8. W_hq = normal((num_hiddens, num_outputs))
  9. b_q = d2l.zeros(num_outputs, device=device)
  10. # 附加梯度
  11. params = [W_xh, W_hh, b_h, W_hq, b_q]
  12. for param in params:
  13. param.requires_grad_(True)
  14. return params
  1. ```{.python .input}
  2. #@tab tensorflow
  3. def get_params(vocab_size, num_hiddens):
  4. num_inputs = num_outputs = vocab_size
  5. def normal(shape):
  6. return d2l.normal(shape=shape,stddev=0.01,mean=0,dtype=tf.float32)
  7. # 隐藏层参数
  8. W_xh = tf.Variable(normal((num_inputs, num_hiddens)), dtype=tf.float32)
  9. W_hh = tf.Variable(normal((num_hiddens, num_hiddens)), dtype=tf.float32)
  10. b_h = tf.Variable(d2l.zeros(num_hiddens), dtype=tf.float32)
  11. # 输出层参数
  12. W_hq = tf.Variable(normal((num_hiddens, num_outputs)), dtype=tf.float32)
  13. b_q = tf.Variable(d2l.zeros(num_outputs), dtype=tf.float32)
  14. params = [W_xh, W_hh, b_h, W_hq, b_q]
  15. return params

循环神经网络模型

为了定义循环神经网络模型, 我们首先需要[一个init_rnn_state函数在初始化时返回隐状态]。 这个函数的返回是一个张量,张量全用0填充, 形状为(批量大小,隐藏单元数)。 在后面的章节中我们将会遇到隐状态包含多个变量的情况, 而使用元组可以更容易地处理些。

```{.python .input} def init_rnn_state(batch_size, num_hiddens, device): return (d2l.zeros((batch_size, num_hiddens), ctx=device), )

  1. ```{.python .input}
  2. #@tab pytorch
  3. def init_rnn_state(batch_size, num_hiddens, device):
  4. return (d2l.zeros((batch_size, num_hiddens), device=device), )

```{.python .input}

@tab tensorflow

def init_rnn_state(batch_size, num_hiddens): return (d2l.zeros((batch_size, num_hiddens)), )

  1. [**下面的`rnn`函数定义了如何在一个时间步内计算隐状态和输出。**]
  2. 循环神经网络模型通过`inputs`最外层的维度实现循环,
  3. 以便逐时间步更新小批量数据的隐状态`H`
  4. 此外,这里使用$\tanh$函数作为激活函数。
  5. :numref:`sec_mlp`所述,
  6. 当元素在实数上满足均匀分布时,$\tanh$函数的平均值为0
  7. ```{.python .input}
  8. def rnn(inputs, state, params):
  9. # inputs的形状:(时间步数量,批量大小,词表大小)
  10. W_xh, W_hh, b_h, W_hq, b_q = params
  11. H, = state
  12. outputs = []
  13. # X的形状:(批量大小,词表大小)
  14. for X in inputs:
  15. H = np.tanh(np.dot(X, W_xh) + np.dot(H, W_hh) + b_h)
  16. Y = np.dot(H, W_hq) + b_q
  17. outputs.append(Y)
  18. return np.concatenate(outputs, axis=0), (H,)

```{.python .input}

@tab pytorch

def rnn(inputs, state, params):

  1. # inputs的形状:(时间步数量,批量大小,词表大小)
  2. W_xh, W_hh, b_h, W_hq, b_q = params
  3. H, = state
  4. outputs = []
  5. # X的形状:(批量大小,词表大小)
  6. for X in inputs:
  7. H = torch.tanh(torch.mm(X, W_xh) + torch.mm(H, W_hh) + b_h)
  8. Y = torch.mm(H, W_hq) + b_q
  9. outputs.append(Y)
  10. return torch.cat(outputs, dim=0), (H,)
  1. ```{.python .input}
  2. #@tab tensorflow
  3. def rnn(inputs, state, params):
  4. # inputs的形状:(时间步数量,批量大小,词表大小)
  5. W_xh, W_hh, b_h, W_hq, b_q = params
  6. H, = state
  7. outputs = []
  8. # X的形状:(批量大小,词表大小)
  9. for X in inputs:
  10. X = tf.reshape(X,[-1,W_xh.shape[0]])
  11. H = tf.tanh(tf.matmul(X, W_xh) + tf.matmul(H, W_hh) + b_h)
  12. Y = tf.matmul(H, W_hq) + b_q
  13. outputs.append(Y)
  14. return d2l.concat(outputs, axis=0), (H,)

定义了所有需要的函数之后,接下来我们[创建一个类来包装这些函数], 并存储从零开始实现的循环神经网络模型的参数。

```{.python .input} class RNNModelScratch: #@save “””从零开始实现的循环神经网络模型””” def init(self, vocab_size, num_hiddens, device, get_params, init_state, forward_fn): self.vocab_size, self.num_hiddens = vocab_size, num_hiddens self.params = get_params(vocab_size, num_hiddens, device) self.init_state, self.forward_fn = init_state, forward_fn

  1. def __call__(self, X, state):
  2. X = npx.one_hot(X.T, self.vocab_size)
  3. return self.forward_fn(X, state, self.params)
  4. def begin_state(self, batch_size, ctx):
  5. return self.init_state(batch_size, self.num_hiddens, ctx)
  1. ```{.python .input}
  2. #@tab pytorch
  3. class RNNModelScratch: #@save
  4. """从零开始实现的循环神经网络模型"""
  5. def __init__(self, vocab_size, num_hiddens, device,
  6. get_params, init_state, forward_fn):
  7. self.vocab_size, self.num_hiddens = vocab_size, num_hiddens
  8. self.params = get_params(vocab_size, num_hiddens, device)
  9. self.init_state, self.forward_fn = init_state, forward_fn
  10. def __call__(self, X, state):
  11. X = F.one_hot(X.T, self.vocab_size).type(torch.float32)
  12. return self.forward_fn(X, state, self.params)
  13. def begin_state(self, batch_size, device):
  14. return self.init_state(batch_size, self.num_hiddens, device)

```{.python .input}

@tab tensorflow

class RNNModelScratch: #@save “””从零开始实现的循环神经网络模型””” def init(self, vocab_size, num_hiddens, init_state, forward_fn, get_params): self.vocab_size, self.num_hiddens = vocab_size, num_hiddens self.init_state, self.forward_fn = init_state, forward_fn self.trainable_variables = get_params(vocab_size, num_hiddens)

  1. def __call__(self, X, state):
  2. X = tf.one_hot(tf.transpose(X), self.vocab_size)
  3. X = tf.cast(X, tf.float32)
  4. return self.forward_fn(X, state, self.trainable_variables)
  5. def begin_state(self, batch_size, *args, **kwargs):
  6. return self.init_state(batch_size, self.num_hiddens)
  1. 让我们[**检查输出是否具有正确的形状**]。
  2. 例如,隐状态的维数是否保持不变。
  3. ```{.python .input}
  4. #@tab mxnet
  5. num_hiddens = 512
  6. net = RNNModelScratch(len(vocab), num_hiddens, d2l.try_gpu(), get_params,
  7. init_rnn_state, rnn)
  8. state = net.begin_state(X.shape[0], d2l.try_gpu())
  9. Y, new_state = net(X.as_in_context(d2l.try_gpu()), state)
  10. Y.shape, len(new_state), new_state[0].shape

```{.python .input}

@tab pytorch

num_hiddens = 512 net = RNNModelScratch(len(vocab), num_hiddens, d2l.try_gpu(), get_params, init_rnn_state, rnn) state = net.begin_state(X.shape[0], d2l.try_gpu()) Y, new_state = net(X.to(d2l.try_gpu()), state) Y.shape, len(new_state), new_state[0].shape

  1. ```{.python .input}
  2. #@tab tensorflow
  3. # 定义tensorflow训练策略
  4. device_name = d2l.try_gpu()._device_name
  5. strategy = tf.distribute.OneDeviceStrategy(device_name)
  6. num_hiddens = 512
  7. with strategy.scope():
  8. net = RNNModelScratch(len(vocab), num_hiddens, init_rnn_state, rnn,
  9. get_params)
  10. state = net.begin_state(X.shape[0])
  11. Y, new_state = net(X, state)
  12. Y.shape, len(new_state), new_state[0].shape

我们可以看到输出形状是(时间步数$\times$批量大小,词表大小), 而隐状态形状保持不变,即(批量大小,隐藏单元数)。

预测

让我们[首先定义预测函数来生成prefix之后的新字符], 其中的prefix是一个用户提供的包含多个字符的字符串。 在循环遍历prefix中的开始字符时, 我们不断地将隐状态传递到下一个时间步,但是不生成任何输出。 这被称为预热(warm-up)期, 因为在此期间模型会自我更新(例如,更新隐状态), 但不会进行预测。 预热期结束后,隐状态的值通常比刚开始的初始值更适合预测, 从而预测字符并输出它们。

```{.python .input} def predictch8(prefix, num_preds, net, vocab, device): #@save “””在prefix后面生成新字符””” state = net.begin_state(batch_size=1, ctx=device) outputs = [vocab[prefix[0]]] get_input = lambda: d2l.reshape( d2l.tensor([outputs[-1]], ctx=device), (1, 1)) for y in prefix[1:]: # 预热期 , state = net(getinput(), state) outputs.append(vocab[y]) for in range(num_preds): # 预测num_preds步 y, state = net(get_input(), state) outputs.append(int(y.argmax(axis=1).reshape(1))) return ‘’.join([vocab.idx_to_token[i] for i in outputs])

  1. ```{.python .input}
  2. #@tab pytorch
  3. def predict_ch8(prefix, num_preds, net, vocab, device): #@save
  4. """在prefix后面生成新字符"""
  5. state = net.begin_state(batch_size=1, device=device)
  6. outputs = [vocab[prefix[0]]]
  7. get_input = lambda: d2l.reshape(d2l.tensor(
  8. [outputs[-1]], device=device), (1, 1))
  9. for y in prefix[1:]: # 预热期
  10. _, state = net(get_input(), state)
  11. outputs.append(vocab[y])
  12. for _ in range(num_preds): # 预测num_preds步
  13. y, state = net(get_input(), state)
  14. outputs.append(int(y.argmax(dim=1).reshape(1)))
  15. return ''.join([vocab.idx_to_token[i] for i in outputs])

```{.python .input}

@tab tensorflow

def predictch8(prefix, num_preds, net, vocab): #@save “””在prefix后面生成新字符””” state = net.begin_state(batch_size=1, dtype=tf.float32) outputs = [vocab[prefix[0]]] get_input = lambda: d2l.reshape(d2l.tensor([outputs[-1]]), (1, 1)).numpy() for y in prefix[1:]: # 预热期 , state = net(getinput(), state) outputs.append(vocab[y]) for in range(num_preds): # 预测num_preds步 y, state = net(get_input(), state) outputs.append(int(y.numpy().argmax(axis=1).reshape(1))) return ‘’.join([vocab.idx_to_token[i] for i in outputs])

  1. 现在我们可以测试`predict_ch8`函数。
  2. 我们将前缀指定为`time traveller `
  3. 并基于这个前缀生成10个后续字符。
  4. 鉴于我们还没有训练网络,它会生成荒谬的预测结果。
  5. ```{.python .input}
  6. #@tab mxnet,pytorch
  7. predict_ch8('time traveller ', 10, net, vocab, d2l.try_gpu())

```{.python .input}

@tab tensorflow

predict_ch8(‘time traveller ‘, 10, net, vocab)

  1. ## [**梯度裁剪**]
  2. 对于长度为$T$的序列,我们在迭代中计算这$T$个时间步上的梯度,
  3. 将会在反向传播过程中产生长度为$\mathcal{O}(T)$的矩阵乘法链。
  4. :numref:`sec_numerical_stability`所述,
  5. $T$较大时,它可能导致数值不稳定,
  6. 例如可能导致梯度爆炸或梯度消失。
  7. 因此,循环神经网络模型往往需要额外的方式来支持稳定训练。
  8. 一般来说,当解决优化问题时,我们对模型参数采用更新步骤。
  9. 假定在向量形式的$\mathbf{x}$中,
  10. 或者在小批量数据的负梯度$\mathbf{g}$方向上。
  11. 例如,使用$\eta > 0$作为学习率时,在一次迭代中,
  12. 我们将$\mathbf{x}$更新为$\mathbf{x} - \eta \mathbf{g}$
  13. 如果我们进一步假设目标函数$f$表现良好,
  14. 即函数$f$在常数$L$下是*利普希茨连续的*(Lipschitz continuous)。
  15. 也就是说,对于任意$\mathbf{x}$$\mathbf{y}$我们有:
  16. $$|f(\mathbf{x}) - f(\mathbf{y})| \leq L \|\mathbf{x} - \mathbf{y}\|.$$
  17. 在这种情况下,我们可以安全地假设:
  18. 如果我们通过$\eta \mathbf{g}$更新参数向量,则
  19. $$|f(\mathbf{x}) - f(\mathbf{x} - \eta\mathbf{g})| \leq L \eta\|\mathbf{g}\|,$$
  20. 这意味着我们不会观察到超过$L \eta \|\mathbf{g}\|$的变化。
  21. 这既是坏事也是好事。
  22. 坏的方面,它限制了取得进展的速度;
  23. 好的方面,它限制了事情变糟的程度,尤其当我们朝着错误的方向前进时。
  24. 有时梯度可能很大,从而优化算法可能无法收敛。
  25. 我们可以通过降低$\eta$的学习率来解决这个问题。
  26. 但是如果我们很少得到大的梯度呢?
  27. 在这种情况下,这种做法似乎毫无道理。
  28. 一个流行的替代方案是通过将梯度$\mathbf{g}$投影回给定半径
  29. (例如$\theta$)的球来裁剪梯度$\mathbf{g}$
  30. 如下式:
  31. (**$$\mathbf{g} \leftarrow \min\left(1, \frac{\theta}{\|\mathbf{g}\|}\right) \mathbf{g}.$$**)
  32. 通过这样做,我们知道梯度范数永远不会超过$\theta$
  33. 并且更新后的梯度完全与$\mathbf{g}$的原始方向对齐。
  34. 它还有一个值得拥有的副作用,
  35. 即限制任何给定的小批量数据(以及其中任何给定的样本)对参数向量的影响,
  36. 这赋予了模型一定程度的稳定性。
  37. 梯度裁剪提供了一个快速修复梯度爆炸的方法,
  38. 虽然它并不能完全解决问题,但它是众多有效的技术之一。
  39. 下面我们定义一个函数来裁剪模型的梯度,
  40. 模型是从零开始实现的模型或由高级API构建的模型。
  41. 我们在此计算了所有模型参数的梯度的范数。
  42. ```{.python .input}
  43. def grad_clipping(net, theta): #@save
  44. """裁剪梯度"""
  45. if isinstance(net, gluon.Block):
  46. params = [p.data() for p in net.collect_params().values()]
  47. else:
  48. params = net.params
  49. norm = math.sqrt(sum((p.grad ** 2).sum() for p in params))
  50. if norm > theta:
  51. for param in params:
  52. param.grad[:] *= theta / norm

```{.python .input}

@tab pytorch

def grad_clipping(net, theta): #@save “””裁剪梯度””” if isinstance(net, nn.Module): params = [p for p in net.parameters() if p.requires_grad] else: params = net.params norm = torch.sqrt(sum(torch.sum((p.grad * 2)) for p in params)) if norm > theta: for param in params: param.grad[:] = theta / norm

  1. ```{.python .input}
  2. #@tab tensorflow
  3. def grad_clipping(grads, theta): #@save
  4. """裁剪梯度"""
  5. theta = tf.constant(theta, dtype=tf.float32)
  6. new_grad = []
  7. for grad in grads:
  8. if isinstance(grad, tf.IndexedSlices):
  9. new_grad.append(tf.convert_to_tensor(grad))
  10. else:
  11. new_grad.append(grad)
  12. norm = tf.math.sqrt(sum((tf.reduce_sum(grad ** 2)).numpy()
  13. for grad in new_grad))
  14. norm = tf.cast(norm, tf.float32)
  15. if tf.greater(norm, theta):
  16. for i, grad in enumerate(new_grad):
  17. new_grad[i] = grad * theta / norm
  18. else:
  19. new_grad = new_grad
  20. return new_grad

训练

在训练模型之前,让我们[定义一个函数在一个迭代周期内训练模型]。 它与我们训练 :numref:sec_softmax_scratch模型的方式有三个不同之处:

  1. 序列数据的不同采样方法(随机采样和顺序分区)将导致隐状态初始化的差异。
  2. 我们在更新模型参数之前裁剪梯度。 这样的操作的目的是:即使训练过程中某个点上发生了梯度爆炸,也能保证模型不会发散。
  3. 我们用困惑度来评价模型。如 :numref:subsec_perplexity所述, 这样的度量确保了不同长度的序列具有可比性。

具体来说,当使用顺序分区时, 我们只在每个迭代周期的开始位置初始化隐状态。 由于下一个小批量数据中的第$i$个子序列样本 与当前第$i$个子序列样本相邻, 因此当前小批量数据最后一个样本的隐状态, 将用于初始化下一个小批量数据第一个样本的隐状态。 这样,存储在隐状态中的序列的历史信息 可以在一个迭代周期内流经相邻的子序列。 然而,在任何一点隐状态的计算, 都依赖于同一迭代周期中前面所有的小批量数据, 这使得梯度计算变得复杂。 为了降低计算量,在处理任何一个小批量数据之前, 我们先分离梯度,使得隐状态的梯度计算总是限制在一个小批量数据的时间步内。

当使用随机抽样时,因为每个样本都是在一个随机位置抽样的, 因此需要为每个迭代周期重新初始化隐状态。 与 :numref:sec_softmax_scratch中的 train_epoch_ch3函数相同, updater是更新模型参数的常用函数。 它既可以是从头开始实现的d2l.sgd函数, 也可以是深度学习框架中内置的优化函数。

```{.python .input}

@save

def train_epoch_ch8(net, train_iter, loss, updater, device, use_random_iter): “””训练模型一个迭代周期(定义见第8章)””” state, timer = None, d2l.Timer() metric = d2l.Accumulator(2) # 训练损失之和,词元数量 for X, Y in train_iter: if state is None or use_random_iter:

  1. # 在第一次迭代或使用随机抽样时初始化state
  2. state = net.begin_state(batch_size=X.shape[0], ctx=device)
  3. else:
  4. for s in state:
  5. s.detach()
  6. y = Y.T.reshape(-1)
  7. X, y = X.as_in_ctx(device), y.as_in_ctx(device)
  8. with autograd.record():
  9. y_hat, state = net(X, state)
  10. l = loss(y_hat, y).mean()
  11. l.backward()
  12. grad_clipping(net, 1)
  13. updater(batch_size=1) # 因为已经调用了mean函数
  14. metric.add(l * d2l.size(y), d2l.size(y))
  15. return math.exp(metric[0] / metric[1]), metric[1] / timer.stop()
  1. ```{.python .input}
  2. #@tab pytorch
  3. #@save
  4. def train_epoch_ch8(net, train_iter, loss, updater, device, use_random_iter):
  5. """训练网络一个迭代周期(定义见第8章)"""
  6. state, timer = None, d2l.Timer()
  7. metric = d2l.Accumulator(2) # 训练损失之和,词元数量
  8. for X, Y in train_iter:
  9. if state is None or use_random_iter:
  10. # 在第一次迭代或使用随机抽样时初始化state
  11. state = net.begin_state(batch_size=X.shape[0], device=device)
  12. else:
  13. if isinstance(net, nn.Module) and not isinstance(state, tuple):
  14. # state对于nn.GRU是个张量
  15. state.detach_()
  16. else:
  17. # state对于nn.LSTM或对于我们从零开始实现的模型是个张量
  18. for s in state:
  19. s.detach_()
  20. y = Y.T.reshape(-1)
  21. X, y = X.to(device), y.to(device)
  22. y_hat, state = net(X, state)
  23. l = loss(y_hat, y.long()).mean()
  24. if isinstance(updater, torch.optim.Optimizer):
  25. updater.zero_grad()
  26. l.backward()
  27. grad_clipping(net, 1)
  28. updater.step()
  29. else:
  30. l.backward()
  31. grad_clipping(net, 1)
  32. # 因为已经调用了mean函数
  33. updater(batch_size=1)
  34. metric.add(l * d2l.size(y), d2l.size(y))
  35. return math.exp(metric[0] / metric[1]), metric[1] / timer.stop()

```{.python .input}

@tab tensorflow

@save

def train_epoch_ch8(net, train_iter, loss, updater, use_random_iter): “””训练模型一个迭代周期(定义见第8章)””” state, timer = None, d2l.Timer() metric = d2l.Accumulator(2) # 训练损失之和,词元数量 for X, Y in train_iter: if state is None or use_random_iter:

  1. # 在第一次迭代或使用随机抽样时初始化state
  2. state = net.begin_state(batch_size=X.shape[0], dtype=tf.float32)
  3. with tf.GradientTape(persistent=True) as g:
  4. y_hat, state = net(X, state)
  5. y = d2l.reshape(tf.transpose(Y), (-1))
  6. l = loss(y, y_hat)
  7. params = net.trainable_variables
  8. grads = g.gradient(l, params)
  9. grads = grad_clipping(grads, 1)
  10. updater.apply_gradients(zip(grads, params))
  11. # Keras默认返回一个批量中的平均损失
  12. metric.add(l * d2l.size(y), d2l.size(y))
  13. return math.exp(metric[0] / metric[1]), metric[1] / timer.stop()
  1. [**循环神经网络模型的训练函数既支持从零开始实现,
  2. 也可以使用高级API来实现。**]
  3. ```{.python .input}
  4. def train_ch8(net, train_iter, vocab, lr, num_epochs, device, #@save
  5. use_random_iter=False):
  6. """训练模型(定义见第8章)"""
  7. loss = gluon.loss.SoftmaxCrossEntropyLoss()
  8. animator = d2l.Animator(xlabel='epoch', ylabel='perplexity',
  9. legend=['train'], xlim=[10, num_epochs])
  10. # 初始化
  11. if isinstance(net, gluon.Block):
  12. net.initialize(ctx=device, force_reinit=True,
  13. init=init.Normal(0.01))
  14. trainer = gluon.Trainer(net.collect_params(),
  15. 'sgd', {'learning_rate': lr})
  16. updater = lambda batch_size: trainer.step(batch_size)
  17. else:
  18. updater = lambda batch_size: d2l.sgd(net.params, lr, batch_size)
  19. predict = lambda prefix: predict_ch8(prefix, 50, net, vocab, device)
  20. # 训练和预测
  21. for epoch in range(num_epochs):
  22. ppl, speed = train_epoch_ch8(
  23. net, train_iter, loss, updater, device, use_random_iter)
  24. if (epoch + 1) % 10 == 0:
  25. animator.add(epoch + 1, [ppl])
  26. print(f'困惑度 {ppl:.1f}, {speed:.1f} 词元/秒 {str(device)}')
  27. print(predict('time traveller'))
  28. print(predict('traveller'))

```{.python .input}

@tab pytorch

@save

def train_ch8(net, train_iter, vocab, lr, num_epochs, device, use_random_iter=False): “””训练模型(定义见第8章)””” loss = nn.CrossEntropyLoss() animator = d2l.Animator(xlabel=’epoch’, ylabel=’perplexity’, legend=[‘train’], xlim=[10, num_epochs])

  1. # 初始化
  2. if isinstance(net, nn.Module):
  3. updater = torch.optim.SGD(net.parameters(), lr)
  4. else:
  5. updater = lambda batch_size: d2l.sgd(net.params, lr, batch_size)
  6. predict = lambda prefix: predict_ch8(prefix, 50, net, vocab, device)
  7. # 训练和预测
  8. for epoch in range(num_epochs):
  9. ppl, speed = train_epoch_ch8(
  10. net, train_iter, loss, updater, device, use_random_iter)
  11. if (epoch + 1) % 10 == 0:
  12. print(predict('time traveller'))
  13. animator.add(epoch + 1, [ppl])
  14. print(f'困惑度 {ppl:.1f}, {speed:.1f} 词元/秒 {str(device)}')
  15. print(predict('time traveller'))
  16. print(predict('traveller'))
  1. ```{.python .input}
  2. #@tab tensorflow
  3. #@save
  4. def train_ch8(net, train_iter, vocab, lr, num_epochs, strategy,
  5. use_random_iter=False):
  6. """训练模型(定义见第8章)"""
  7. with strategy.scope():
  8. loss = tf.keras.losses.SparseCategoricalCrossentropy(
  9. from_logits=True)
  10. updater = tf.keras.optimizers.SGD(lr)
  11. animator = d2l.Animator(xlabel='epoch', ylabel='perplexity',
  12. legend=['train'], xlim=[10, num_epochs])
  13. predict = lambda prefix: predict_ch8(prefix, 50, net, vocab)
  14. # 训练和预测
  15. for epoch in range(num_epochs):
  16. ppl, speed = train_epoch_ch8(net, train_iter, loss, updater,
  17. use_random_iter)
  18. if (epoch + 1) % 10 == 0:
  19. print(predict('time traveller'))
  20. animator.add(epoch + 1, [ppl])
  21. device = d2l.try_gpu()._device_name
  22. print(f'困惑度 {ppl:.1f}, {speed:.1f} 词元/秒 {str(device)}')
  23. print(predict('time traveller'))
  24. print(predict('traveller'))

[现在,我们训练循环神经网络模型。] 因为我们在数据集中只使用了10000个词元, 所以模型需要更多的迭代周期来更好地收敛。

```{.python .input}

@tab mxnet,pytorch

num_epochs, lr = 500, 1 train_ch8(net, train_iter, vocab, lr, num_epochs, d2l.try_gpu())

  1. ```{.python .input}
  2. #@tab tensorflow
  3. num_epochs, lr = 500, 1
  4. train_ch8(net, train_iter, vocab, lr, num_epochs, strategy)

[最后,让我们检查一下使用随机抽样方法的结果。]

```{.python .input}

@tab mxnet,pytorch

net = RNNModelScratch(len(vocab), num_hiddens, d2l.try_gpu(), get_params, init_rnn_state, rnn) train_ch8(net, train_iter, vocab, lr, num_epochs, d2l.try_gpu(), use_random_iter=True)

  1. ```{.python .input}
  2. #@tab tensorflow
  3. with strategy.scope():
  4. net = RNNModelScratch(len(vocab), num_hiddens, init_rnn_state, rnn,
  5. get_params)
  6. train_ch8(net, train_iter, vocab_random_iter, lr, num_epochs, strategy,
  7. use_random_iter=True)

从零开始实现上述循环神经网络模型, 虽然有指导意义,但是并不方便。 在下一节中,我们将学习如何改进循环神经网络模型。 例如,如何使其实现地更容易,且运行速度更快。

小结

  • 我们可以训练一个基于循环神经网络的字符级语言模型,根据用户提供的文本的前缀生成后续文本。
  • 一个简单的循环神经网络语言模型包括输入编码、循环神经网络模型和输出生成。
  • 循环神经网络模型在训练以前需要初始化状态,不过随机抽样和顺序划分使用初始化方法不同。
  • 当使用顺序划分时,我们需要分离梯度以减少计算量。
  • 在进行任何预测之前,模型通过预热期进行自我更新(例如,获得比初始值更好的隐状态)。
  • 梯度裁剪可以防止梯度爆炸,但不能应对梯度消失。

练习

  1. 尝试说明独热编码等价于为每个对象选择不同的嵌入表示。
  2. 通过调整超参数(如迭代周期数、隐藏单元数、小批量数据的时间步数、学习率等)来改善困惑度。
    • 你能将困惑度降到多少?
    • 用可学习的嵌入表示替换独热编码,是否会带来更好的表现?
    • 如果用H.G.Wells的其他书作为数据集时效果如何, 例如世界大战
  3. 修改预测函数,例如使用采样,而不是选择最有可能的下一个字符。
    • 会发生什么?
    • 调整模型使之偏向更可能的输出,例如,当$\alpha > 1$,从$q(xt \mid x{t-1}, \ldots, x1) \propto P(x_t \mid x{t-1}, \ldots, x_1)^\alpha$中采样。
  4. 在不裁剪梯度的情况下运行本节中的代码会发生什么?
  5. 更改顺序划分,使其不会从计算图中分离隐状态。运行时间会有变化吗?困惑度呢?
  6. 用ReLU替换本节中使用的激活函数,并重复本节中的实验。我们还需要梯度裁剪吗?为什么?

:begin_tab:mxnet Discussions :end_tab:

:begin_tab:pytorch Discussions :end_tab:

:begin_tab:tensorflow Discussions :end_tab: