下圖展現瞭如何基於循環神經網絡實現語言模型。基於當前的輸入與過去的輸入序列,預測序列的下一個字符。循環神經網絡引入一個隱藏變量\(H\),用\(H_{t}\)表示\(H\)在時間步\(t\)的值。\(H_{t}\)的計算基於\(X_{t}\)和\(H_{t-1}\),能夠認爲\(H_{t}\)記錄了到當前字符爲止的序列信息,利用\(H_{t}\)對序列的下一個字符進行預測。
html
假設\(\boldsymbol{X}_t \in \mathbb{R}^{n \times d}\)是時間步\(t\)的小批量輸入,\(\boldsymbol{H}_t \in \mathbb{R}^{n \times h}\)是該時間步的隱藏變量,則:python
\[ \boldsymbol{H}_t = \phi(\boldsymbol{X}_t \boldsymbol{W}_{xh} + \boldsymbol{H}_{t-1} \boldsymbol{W}_{hh} + \boldsymbol{b}_h). \]網絡
其中,\(\boldsymbol{W}_{xh} \in \mathbb{R}^{d \times h}\),\(\boldsymbol{W}_{hh} \in \mathbb{R}^{h \times h}\),\(\boldsymbol{b}_{h} \in \mathbb{R}^{1 \times h}\),\(\phi\)函數是非線性激活函數。因爲引入了\(\boldsymbol{H}_{t-1} \boldsymbol{W}_{hh}\),\(H_{t}\)可以捕捉截至當前時間步的序列的歷史信息,就像是神經網絡當前時間步的狀態或記憶同樣。因爲\(H_{t}\)的計算基於\(H_{t-1}\),上式的計算是循環的,使用循環計算的網絡即循環神經網絡(recurrent neural network)。app
在時間步\(t\),輸出層的輸出爲:dom
\[ \boldsymbol{O}_t = \boldsymbol{H}_t \boldsymbol{W}_{hq} + \boldsymbol{b}_q. \]ide
其中\(\boldsymbol{W}_{hq} \in \mathbb{R}^{h \times q}\),\(\boldsymbol{b}_q \in \mathbb{R}^{1 \times q}\)。函數
咱們先嚐試從零開始實現一個基於字符級循環神經網絡的語言模型,這裏咱們使用周杰倫的歌詞做爲語料,首先咱們讀入數據:測試
import torch import torch.nn as nn import time import math import sys sys.path.append("/home/kesci/input") import d2l_jay9460 as d2l (corpus_indices, char_to_idx, idx_to_char, vocab_size) = d2l.load_data_jay_lyrics() device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
咱們須要將字符表示成向量,這裏採用one-hot向量。假設詞典大小是\(N\),每次字符對應一個從\(0\)到\(N-1\)的惟一的索引,則該字符的向量是一個長度爲\(N\)的向量,若字符的索引是\(i\),則該向量的第\(i\)個位置爲\(1\),其餘位置爲\(0\)。下面分別展現了索引爲0和2的one-hot向量,向量長度等於詞典大小。spa
def one_hot(x, n_class, dtype=torch.float32): result = torch.zeros(x.shape[0], n_class, dtype=dtype, device=x.device) # shape: (n, n_class) result.scatter_(1, x.long().view(-1, 1), 1) # result[i, x[i, 0]] = 1 return result x = torch.tensor([0, 2]) x_one_hot = one_hot(x, vocab_size) print(x_one_hot) print(x_one_hot.shape) print(x_one_hot.sum(axis=1))
咱們每次採樣的小批量的形狀是(批量大小, 時間步數)。下面的函數將這樣的小批量變換成數個形狀爲(批量大小, 詞典大小)的矩陣,矩陣個數等於時間步數。也就是說,時間步\(t\)的輸入爲\(\boldsymbol{X}_t \in \mathbb{R}^{n \times d}\),其中\(n\)爲批量大小,\(d\)爲詞向量大小,即one-hot向量長度(詞典大小)。3d
def to_onehot(X, n_class): return [one_hot(X[:, i], n_class) for i in range(X.shape[1])] X = torch.arange(10).view(2, 5) inputs = to_onehot(X, vocab_size) print(len(inputs), inputs[0].shape)
num_inputs, num_hiddens, num_outputs = vocab_size, 256, vocab_size # num_inputs: d # num_hiddens: h, 隱藏單元的個數是超參數 # num_outputs: q def get_params(): def _one(shape): param = torch.zeros(shape, device=device, dtype=torch.float32) nn.init.normal_(param, 0, 0.01) return torch.nn.Parameter(param) # 隱藏層參數 W_xh = _one((num_inputs, num_hiddens)) W_hh = _one((num_hiddens, num_hiddens)) b_h = torch.nn.Parameter(torch.zeros(num_hiddens, device=device)) # 輸出層參數 W_hq = _one((num_hiddens, num_outputs)) b_q = torch.nn.Parameter(torch.zeros(num_outputs, device=device)) return (W_xh, W_hh, b_h, W_hq, b_q)
函數rnn
用循環的方式依次完成循環神經網絡每一個時間步的計算。
def rnn(inputs, state, params): # inputs和outputs皆爲num_steps個形狀爲(batch_size, vocab_size)的矩陣 W_xh, W_hh, b_h, W_hq, b_q = params H, = state outputs = [] for X in inputs: H = torch.tanh(torch.matmul(X, W_xh) + torch.matmul(H, W_hh) + b_h) Y = torch.matmul(H, W_hq) + b_q outputs.append(Y) return outputs, (H,)
函數init_rnn_state初始化隱藏變量,這裏的返回值是一個元組。
def init_rnn_state(batch_size, num_hiddens, device): return (torch.zeros((batch_size, num_hiddens), device=device), )
作個簡單的測試來觀察輸出結果的個數(時間步數),以及第一個時間步的輸出層輸出的形狀和隱藏狀態的形狀。
print(X.shape) print(num_hiddens) print(vocab_size) state = init_rnn_state(X.shape[0], num_hiddens, device) inputs = to_onehot(X.to(device), vocab_size) params = get_params() outputs, state_new = rnn(inputs, state, params) print(len(inputs), inputs[0].shape) print(len(outputs), outputs[0].shape) print(len(state), state[0].shape) print(len(state_new), state_new[0].shape)
循環神經網絡中較容易出現梯度衰減或梯度爆炸,這會致使網絡幾乎沒法訓練。裁剪梯度(clip gradient)是一種應對梯度爆炸的方法。假設咱們把全部模型參數的梯度拼接成一個向量 \(\boldsymbol{g}\),並設裁剪的閾值是\(\theta\)。裁剪後的梯度
\[ \min\left(\frac{\theta}{\|\boldsymbol{g}\|}, 1\right)\boldsymbol{g} \]
的\(L_2\)範數不超過\(\theta\)。
def grad_clipping(params, theta, device): norm = torch.tensor([0.0], device=device) for param in params: norm += (param.grad.data ** 2).sum() norm = norm.sqrt().item() if norm > theta: for param in params: param.grad.data *= (theta / norm)
如下函數基於前綴prefix
(含有數個字符的字符串)來預測接下來的num_chars
個字符。這個函數稍顯複雜,其中咱們將循環神經單元rnn
設置成了函數參數,這樣在後面小節介紹其餘循環神經網絡時能重複使用這個函數。
def predict_rnn(prefix, num_chars, rnn, params, init_rnn_state, num_hiddens, vocab_size, device, idx_to_char, char_to_idx): state = init_rnn_state(1, num_hiddens, device) output = [char_to_idx[prefix[0]]] # output記錄prefix加上預測的num_chars個字符 for t in range(num_chars + len(prefix) - 1): # 將上一時間步的輸出做爲當前時間步的輸入 X = to_onehot(torch.tensor([[output[-1]]], device=device), vocab_size) # 計算輸出和更新隱藏狀態 (Y, state) = rnn(X, state, params) # 下一個時間步的輸入是prefix裏的字符或者當前的最佳預測字符 if t < len(prefix) - 1: output.append(char_to_idx[prefix[t + 1]]) else: output.append(Y[0].argmax(dim=1).item()) return ''.join([idx_to_char[i] for i in output])`
咱們先測試一下predict_rnn
函數。咱們將根據前綴「分開」創做長度爲10個字符(不考慮前綴長度)的一段歌詞。由於模型參數爲隨機值,因此預測結果也是隨機的。
predict_rnn('分開', 10, rnn, params, init_rnn_state, num_hiddens, vocab_size, device, idx_to_char, char_to_idx)
咱們一般使用困惑度(perplexity)來評價語言模型的好壞。回憶一下「softmax迴歸」一節中交叉熵損失函數的定義。困惑度是對交叉熵損失函數作指數運算後獲得的值。特別地,
顯然,任何一個有效模型的困惑度必須小於類別個數。在本例中,困惑度必須小於詞典大小vocab_size
。
跟以前章節的模型訓練函數相比,這裏的模型訓練函數有如下幾點不一樣:
def train_and_predict_rnn(rnn, get_params, init_rnn_state, num_hiddens, vocab_size, device, corpus_indices, idx_to_char, char_to_idx, is_random_iter, num_epochs, num_steps, lr, clipping_theta, batch_size, pred_period, pred_len, prefixes): if is_random_iter: data_iter_fn = d2l.data_iter_random else: data_iter_fn = d2l.data_iter_consecutive params = get_params() loss = nn.CrossEntropyLoss() for epoch in range(num_epochs): if not is_random_iter: # 如使用相鄰採樣,在epoch開始時初始化隱藏狀態 state = init_rnn_state(batch_size, num_hiddens, device) l_sum, n, start = 0.0, 0, time.time() data_iter = data_iter_fn(corpus_indices, batch_size, num_steps, device) for X, Y in data_iter: if is_random_iter: # 如使用隨機採樣,在每一個小批量更新前初始化隱藏狀態 state = init_rnn_state(batch_size, num_hiddens, device) else: # 不然須要使用detach函數從計算圖分離隱藏狀態 for s in state: s.detach_() # inputs是num_steps個形狀爲(batch_size, vocab_size)的矩陣 inputs = to_onehot(X, vocab_size) # outputs有num_steps個形狀爲(batch_size, vocab_size)的矩陣 (outputs, state) = rnn(inputs, state, params) # 拼接以後形狀爲(num_steps * batch_size, vocab_size) outputs = torch.cat(outputs, dim=0) # Y的形狀是(batch_size, num_steps),轉置後再變成形狀爲 # (num_steps * batch_size,)的向量,這樣跟輸出的行一一對應 y = torch.flatten(Y.T) # 使用交叉熵損失計算平均分類偏差 l = loss(outputs, y.long()) # 梯度清0 if params[0].grad is not None: for param in params: param.grad.data.zero_() l.backward() grad_clipping(params, clipping_theta, device) # 裁剪梯度 d2l.sgd(params, lr, 1) # 由於偏差已經取過均值,梯度不用再作平均 l_sum += l.item() * y.shape[0] n += y.shape[0] if (epoch + 1) % pred_period == 0: print('epoch %d, perplexity %f, time %.2f sec' % ( epoch + 1, math.exp(l_sum / n), time.time() - start)) for prefix in prefixes: print(' -', predict_rnn(prefix, pred_len, rnn, params, init_rnn_state, num_hiddens, vocab_size, device, idx_to_char, char_to_idx))
如今咱們能夠訓練模型了。首先,設置模型超參數。咱們將根據前綴「分開」和「不分開」分別創做長度爲50個字符(不考慮前綴長度)的一段歌詞。咱們每過50個迭代週期便根據當前訓練的模型創做一段歌詞。
num_epochs, num_steps, batch_size, lr, clipping_theta = 250, 35, 32, 1e2, 1e-2 pred_period, pred_len, prefixes = 50, 50, ['分開', '不分開']
下面採用隨機採樣訓練模型並創做歌詞。
train_and_predict_rnn(rnn, get_params, init_rnn_state, num_hiddens, vocab_size, device, corpus_indices, idx_to_char, char_to_idx, True, num_epochs, num_steps, lr, clipping_theta, batch_size, pred_period, pred_len, prefixes)
咱們使用Pytorch中的nn.RNN
來構造循環神經網絡。在本節中,咱們主要關注nn.RNN
的如下幾個構造函數參數:
input_size
- The number of expected features in the input xhidden_size
– The number of features in the hidden state hnonlinearity
– The non-linearity to use. Can be either 'tanh' or 'relu'. Default: 'tanh'batch_first
– If True, then the input and output tensors are provided as (batch_size, num_steps, input_size). Default: False這裏的batch_first
決定了輸入的形狀,咱們使用默認的參數False
,對應的輸入形狀是 (num_steps, batch_size, input_size)。
forward
函數的參數爲:
input
of shape (num_steps, batch_size, input_size): tensor containing the features of the input sequence.h_0
of shape (num_layers * num_directions, batch_size, hidden_size): tensor containing the initial hidden state for each element in the batch. Defaults to zero if not provided. If the RNN is bidirectional, num_directions should be 2, else it should be 1.forward
函數的返回值是:
output
of shape (num_steps, batch_size, num_directions * hidden_size): tensor containing the output features (h_t) from the last layer of the RNN, for each t.h_n
of shape (num_layers * num_directions, batch_size, hidden_size): tensor containing the hidden state for t = num_steps.如今咱們構造一個nn.RNN
實例,並用一個簡單的例子來看一下輸出的形狀。
rnn_layer = nn.RNN(input_size=vocab_size, hidden_size=num_hiddens) num_steps, batch_size = 35, 2 X = torch.rand(num_steps, batch_size, vocab_size) state = None Y, state_new = rnn_layer(X, state) print(Y.shape, state_new.shape)
咱們定義一個完整的基於循環神經網絡的語言模型。
class RNNModel(nn.Module): def __init__(self, rnn_layer, vocab_size): super(RNNModel, self).__init__() self.rnn = rnn_layer self.hidden_size = rnn_layer.hidden_size * (2 if rnn_layer.bidirectional else 1) self.vocab_size = vocab_size self.dense = nn.Linear(self.hidden_size, vocab_size) def forward(self, inputs, state): # inputs.shape: (batch_size, num_steps) X = to_onehot(inputs, vocab_size) X = torch.stack(X) # X.shape: (num_steps, batch_size, vocab_size) hiddens, state = self.rnn(X, state) hiddens = hiddens.view(-1, hiddens.shape[-1]) # hiddens.shape: (num_steps * batch_size, hidden_size) output = self.dense(hiddens) return output, state
相似的,咱們須要實現一個預測函數,與前面的區別在於前向計算和初始化隱藏狀態。
def predict_rnn_pytorch(prefix, num_chars, model, vocab_size, device, idx_to_char, char_to_idx): state = None output = [char_to_idx[prefix[0]]] # output記錄prefix加上預測的num_chars個字符 for t in range(num_chars + len(prefix) - 1): X = torch.tensor([output[-1]], device=device).view(1, 1) (Y, state) = model(X, state) # 前向計算不須要傳入模型參數 if t < len(prefix) - 1: output.append(char_to_idx[prefix[t + 1]]) else: output.append(Y.argmax(dim=1).item()) return ''.join([idx_to_char[i] for i in output])
使用權重爲隨機值的模型來預測一次。
model = RNNModel(rnn_layer, vocab_size).to(device) predict_rnn_pytorch('分開', 10, model, vocab_size, device, idx_to_char, char_to_idx)
接下來實現訓練函數,這裏只使用了相鄰採樣。
def train_and_predict_rnn_pytorch(model, num_hiddens, vocab_size, device, corpus_indices, idx_to_char, char_to_idx, num_epochs, num_steps, lr, clipping_theta, batch_size, pred_period, pred_len, prefixes): loss = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), lr=lr) model.to(device) for epoch in range(num_epochs): l_sum, n, start = 0.0, 0, time.time() data_iter = d2l.data_iter_consecutive(corpus_indices, batch_size, num_steps, device) # 相鄰採樣 state = None for X, Y in data_iter: if state is not None: # 使用detach函數從計算圖分離隱藏狀態 if isinstance (state, tuple): # LSTM, state:(h, c) state[0].detach_() state[1].detach_() else: state.detach_() (output, state) = model(X, state) # output.shape: (num_steps * batch_size, vocab_size) y = torch.flatten(Y.T) l = loss(output, y.long()) optimizer.zero_grad() l.backward() grad_clipping(model.parameters(), clipping_theta, device) optimizer.step() l_sum += l.item() * y.shape[0] n += y.shape[0] if (epoch + 1) % pred_period == 0: print('epoch %d, perplexity %f, time %.2f sec' % ( epoch + 1, math.exp(l_sum / n), time.time() - start)) for prefix in prefixes: print(' -', predict_rnn_pytorch( prefix, pred_len, model, vocab_size, device, idx_to_char, char_to_idx))
訓練模型。
num_epochs, batch_size, lr, clipping_theta = 250, 32, 1e-3, 1e-2 pred_period, pred_len, prefixes = 50, 50, ['分開', '不分開'] train_and_predict_rnn_pytorch(model, num_hiddens, vocab_size, device, corpus_indices, idx_to_char, char_to_idx, num_epochs, num_steps, lr, clipping_theta, batch_size, pred_period, pred_len, prefixes)