從零開始學Pytorch(十)之循環神經網絡基礎

本節介紹循環神經網絡,下圖展示瞭如何基於循環神經網絡實現語言模型。我們的目的是基於當前的輸入與過去的輸入序列,預測序列的下一個字符。循環神經網絡引入一個隱藏變量HH,用HtH_{t}表示HH在時間步tt的值。HtH_{t}的計算基於XtX_{t}Ht1H_{t-1},可以認爲HtH_{t}記錄了到當前字符爲止的序列信息,利用HtH_{t}對序列的下一個字符進行預測。
Image Name

循環神經網絡的構造

我們先看循環神經網絡的具體構造。假設XtRn×d\boldsymbol{X}_t \in \mathbb{R}^{n \times d}是時間步tt的小批量輸入,HtRn×h\boldsymbol{H}_t \in \mathbb{R}^{n \times h}是該時間步的隱藏變量,則:

Ht=ϕ(XtWxh+Ht1Whh+bh). \boldsymbol{H}_t = \phi(\boldsymbol{X}_t \boldsymbol{W}_{xh} + \boldsymbol{H}_{t-1} \boldsymbol{W}_{hh} + \boldsymbol{b}_h).

其中,WxhRd×h\boldsymbol{W}_{xh} \in \mathbb{R}^{d \times h}WhhRh×h\boldsymbol{W}_{hh} \in \mathbb{R}^{h \times h}bhR1×h\boldsymbol{b}_{h} \in \mathbb{R}^{1 \times h}ϕ\phi函數是非線性激活函數。由於引入了Ht1Whh\boldsymbol{H}_{t-1} \boldsymbol{W}_{hh}HtH_{t}能夠捕捉截至當前時間步的序列的歷史信息,就像是神經網絡當前時間步的狀態或記憶一樣。由於HtH_{t}的計算基於Ht1H_{t-1},上式的計算是循環的,使用循環計算的網絡即循環神經網絡(recurrent neural network)。

在時間步tt,輸出層的輸出爲:

Ot=HtWhq+bq. \boldsymbol{O}_t = \boldsymbol{H}_t \boldsymbol{W}_{hq} + \boldsymbol{b}_q.

其中WhqRh×q\boldsymbol{W}_{hq} \in \mathbb{R}^{h \times q}bqR1×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/input")
import d2l_jay4504 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向量

我們需要將字符表示成向量,這裏採用one-hot向量。假設詞典大小是NN,每次字符對應一個從00N1N-1的唯一的索引,則該字符的向量是一個長度爲NN的向量,若字符的索引是ii,則該向量的第ii個位置爲11,其他位置爲00。下面分別展示了索引爲0和2的one-hot向量,向量長度等於詞典大小。

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))

輸出:
tensor([[1., 0., 0., …, 0., 0., 0.],
[0., 0., 1., …, 0., 0., 0.]])
torch.Size([2, 1027])
tensor([1., 1.])

我們每次採樣的小批量的形狀是(批量大小, 時間步數)。下面的函數將這樣的小批量變換成數個形狀爲(批量大小, 詞典大小)的矩陣,矩陣個數等於時間步數。也就是說,時間步tt的輸入爲XtRn×d\boldsymbol{X}_t \in \mathbb{R}^{n \times d},其中nn爲批量大小,dd爲詞向量大小,即one-hot向量長度(詞典大小)。

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)

初始化模型參數

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)

輸出:torch.Size([2, 5])
256
1027
5 torch.Size([2, 1027])
5 torch.Size([2, 1027])
1 torch.Size([2, 256])
1 torch.Size([2, 256])

裁剪梯度

循環神經網絡中較容易出現梯度衰減或梯度爆炸,這會導致網絡幾乎無法訓練。裁剪梯度(clip gradient)是一種應對梯度爆炸的方法。假設我們把所有模型參數的梯度拼接成一個向量 g\boldsymbol{g},並設裁剪的閾值是θ\theta。裁剪後的梯度

min(θg,1)g \min\left(\frac{\theta}{\|\boldsymbol{g}\|}, 1\right)\boldsymbol{g}

L2L_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迴歸”一節中交叉熵損失函數的定義。困惑度是對交叉熵損失函數做指數運算後得到的值。特別地,

  • 最佳情況下,模型總是把標籤類別的概率預測爲1,此時困惑度爲1;
  • 最壞情況下,模型總是把標籤類別的概率預測爲0,此時困惑度爲正無窮;
  • 基線情況下,模型總是預測所有類別的概率都相同,此時困惑度爲類別個數。

顯然,任何一個有效模型的困惑度必須小於類別個數。在本例中,困惑度必須小於詞典大小vocab_size

定義模型訓練函數

跟之前章節的模型訓練函數相比,這裏的模型訓練函數有以下幾點不同:

  1. 使用困惑度評價模型。
  2. 在迭代模型參數前裁剪梯度。
  3. 對時序數據採用不同採樣方法將導致隱藏狀態初始化的不同。
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 x
  • hidden_size – The number of features in the hidden state h
  • nonlinearity – 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)
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)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章