pytorch_Task2(文本預處理、語言模型、循環神經網絡)

文本預處理

文本是一類序列數據,一篇文章可以看作是字符或單詞的序列,本節將介紹文本數據的常見預處理步驟,預處理通常包括四個步驟:

讀入文本

strip移除字符串頭尾指定的字符(默認爲空格或換行符)或字符序列。

import collections
import re

def read_time_machine():
    with open('/home/kesci/input/timemachine7163/timemachine.txt', 'r') as f:
        lines = [re.sub('[^a-z]+', ' ', line.strip().lower()) for line in f]
    return lines


lines = read_time_machine()
print('# sentences %d' % len(lines))

分詞

split方法以空格分隔成詞

def tokenize(sentences, token='word'):
    """Split sentences into word or char tokens"""
    if token == 'word':
        return [sentence.split(' ') for sentence in sentences]
    elif token == 'char':
        return [list(sentence) for sentence in sentences]
    else:
        print('ERROR: unkown token type '+token)

tokens = tokenize(lines)
tokens[0:2]

建立字典,將每個詞映射到一個唯一的索引(index)

class Vocab(object):
    def __init__(self, tokens, min_freq=0, use_special_tokens=False):
        counter = count_corpus(tokens)  # : 
        self.token_freqs = list(counter.items())
        self.idx_to_token = []
        if use_special_tokens:
            # padding, begin of sentence, end of sentence, unknown
            self.pad, self.bos, self.eos, self.unk = (0, 1, 2, 3)
            self.idx_to_token += ['', '', '', '']
        else:
            self.unk = 0
            self.idx_to_token += ['']
        self.idx_to_token += [token for token, freq in self.token_freqs
                        if freq >= min_freq and token not in self.idx_to_token]
        self.token_to_idx = dict()
        for idx, token in enumerate(self.idx_to_token):
            self.token_to_idx[token] = idx

    def __len__(self):
        return len(self.idx_to_token)

    def __getitem__(self, tokens):
        if not isinstance(tokens, (list, tuple)):
            return self.token_to_idx.get(tokens, self.unk)
        return [self.__getitem__(token) for token in tokens]

    def to_tokens(self, indices):
        if not isinstance(indices, (list, tuple)):
            return self.idx_to_token[indices]
        return [self.idx_to_token[index] for index in indices]

def count_corpus(sentences):
    tokens = [tk for st in sentences for tk in st]
    return collections.Counter(tokens)  # 返回一個字典,記錄每個詞的出現次數
    
vocab = Vocab(tokens)
print(list(vocab.token_to_idx.items())[0:10])

其他分詞工具

我們前面介紹的分詞方式非常簡單,它至少有以下幾個缺點:

標點符號通常可以提供語義信息,但是我們的方法直接將其丟棄了
類似“shouldn’t", “doesn’t"這樣的詞會被錯誤地處理
類似"Mr.”, "Dr."這樣的詞會被錯誤地處理
我們可以通過引入更復雜的規則來解決這些問題,但是事實上,有一些現有的工具可以很好地進行分詞,我們在這裏簡單介紹其中的兩個:spaCy和NLTK。

下面是一個簡單的例子:

text = "Mr. Chen doesn't agree with my suggestion."
import spacy
nlp = spacy.load('en_core_web_sm')
doc = nlp(text)
print([token.text for token in doc])

from nltk.tokenize import word_tokenize
from nltk import data
data.path.append('/home/kesci/input/nltk_data3784/nltk_data')
print(word_tokenize(text))

語言模型

一段自然語言文本可以看作是一個離散時間序列,給定一個長度爲T的詞的序列W1,W2,…WT。語言模型的目標就是評估該序列是否合理,即計算該序列的概率:
在這裏插入圖片描述
概率大序列合理,概率小序列不合理。

本節我們介紹基於統計的語言模型,主要是n元語法(N-gram)。在後續內容中,我們將會介紹基於神經網絡的語言模型。
在這裏插入圖片描述

n元語法

在這裏插入圖片描述
缺陷:
1、參數空間過大
2、數據稀疏

時序數據採樣

在這裏插入圖片描述

隨機採樣

import torch
import random
def data_iter_random(corpus_indices, batch_size, num_steps, device=None):
    # 減1是因爲對於長度爲n的序列,X最多隻有包含其中的前n - 1個字符
    num_examples = (len(corpus_indices) - 1) // num_steps  # 下取整,得到不重疊情況下的樣本個數
    example_indices = [i * num_steps for i in range(num_examples)]  # 每個樣本的第一個字符在corpus_indices中的下標
    random.shuffle(example_indices)

    def _data(i):
        # 返回從i開始的長爲num_steps的序列
        return corpus_indices[i: i + num_steps]
    if device is None:
        device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    
    for i in range(0, num_examples, batch_size):
        # 每次選出batch_size個隨機樣本
        batch_indices = example_indices[i: i + batch_size]  # 當前batch的各個樣本的首字符的下標
        X = [_data(j) for j in batch_indices]
        Y = [_data(j + 1) for j in batch_indices]
        yield torch.tensor(X, device=device), torch.tensor(Y, device=device)

相鄰採樣

def data_iter_consecutive(corpus_indices, batch_size, num_steps, device=None):
    if device is None:
        device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    corpus_len = len(corpus_indices) // batch_size * batch_size  # 保留下來的序列的長度
    corpus_indices = corpus_indices[: corpus_len]  # 僅保留前corpus_len個字符
    indices = torch.tensor(corpus_indices, device=device)
    indices = indices.view(batch_size, -1)  # resize成(batch_size, )
    batch_num = (indices.shape[1] - 1) // num_steps
    for i in range(batch_num):
        i = i * num_steps
        X = indices[:, i: i + num_steps]
        Y = indices[:, i + 1: i + num_steps + 1]
        yield X, Y

RNN

循環神經網絡

我們的目的是基於當前的輸入與過去的輸入序列,預測序列的下一個字符。
循環神經網絡引入一個隱藏變量 H ,用 Ht 表示 H 在時間步 t 的值。 Ht 的計算基於 Xt 和 Ht−1 ,可以認爲 Ht 記錄了到當前字符爲止的序列信息,利用 Ht 對序列的下一個字符進行預測。
在這裏插入圖片描述

裁剪梯度

在這裏插入圖片描述

困惑度

我們通常使用困惑度(perplexity)來評價語言模型的好壞。回憶一下交叉熵損失函數的定義。困惑度是對交叉熵損失函數做指數運算後得到的值。特別地,

最佳情況下,模型總是把標籤類別的概率預測爲1,此時困惑度爲1;
最壞情況下,模型總是把標籤類別的概率預測爲0,此時困惑度爲正無窮;
基線情況下,模型總是預測所有類別的概率都相同,此時困惑度爲類別個數。
顯然,任何一個有效模型的困惑度必須小於類別個數。在本例中,困惑度必須小於詞典大小vocab_size。

定義模型訓練函數

跟之前章節的模型訓練函數相比,這裏的模型訓練函數有以下幾點不同:
使用困惑度評價模型。
在迭代模型參數前裁剪梯度。
對時序數據採用不同採樣方法將導致隱藏狀態初始化的不同。

代碼實現

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