Task02:文本預處理;語言模型;循環神經網絡基礎
簡介
文本是一類序列數據,一篇文章可以看作是字符或單詞的序列,本節將介紹文本數據的常見預處理步驟,預處理通常包括四個步驟:
1.讀入文本
我們用一部英文小說,即H. G. Well的Time Machine,作爲示例,展示文本預處理的具體過程。
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))
2.分詞
我們對每個句子進行分詞,也就是將一個句子劃分成若干個詞(token),轉換爲一個詞的序列。
"""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]
3.建立字典,將每個詞映射到一個唯一的索引(index)
爲了方便模型處理,我們需要將字符串轉換爲數字。因此我們需要先構建一個字典(vocabulary),將每個詞映射到一個唯一的索引編號。
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) # 返回一個字典,記錄每個詞的出現次數
4.將文本從詞的序列轉換爲索引的序列,方便輸入模型
使用字典,我們可以將原文本中的句子從單詞序列轉換爲索引序列
for i in range(8, 10):
print('words:', tokens[i])
print('indices:', vocab[tokens[i]])
用現有工具進行分詞
我們前面介紹的分詞方式非常簡單,它至少有以下幾個缺點:
1.標點符號通常可以提供語義信息,但是我們的方法直接將其丟棄了
2.類似“shouldn’t", “doesn’t"這樣的詞會被錯誤地處理
3.類似"Mr.”, "Dr."這樣的詞會被錯誤地處理
我們可以通過引入更復雜的規則來解決這些問題,但是事實上,有一些現有的工具可以很好地進行分詞,我們在這裏簡單介紹其中的兩個:spaCy和NLTK。
text = “Mr. Chen doesn’t agree with my suggestion.”
spaCy
import spacy
nlp = spacy.load('en_core_web_sm')
doc = nlp(text)
print([token.text for token in doc])
NLTK
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 ,語言模型的目標就是評估該序列是否合理,即計算該序列的概率:
P(w1,w2,…,wT).
語言模型
假設序列 w1,w2,…,wT 中的每個詞是依次生成的,我們有
P(w1,w2,…,wT)=∏t=1TP(wt∣w1,…,wt−1)=P(w1)P(w2∣w1)⋯P(wT∣w1w2⋯wT−1)
例如,一段含有4個詞的文本序列的概率
P(w1,w2,w3,w4)=P(w1)P(w2∣w1)P(w3∣w1,w2)P(w4∣w1,w2,w3).
語言模型的參數就是詞的概率以及給定前幾個詞情況下的條件概率。設訓練數據集爲一個大型文本語料庫,如維基百科的所有條目,詞的概率可以通過該詞在訓練數據集中的相對詞頻來計算,例如, w1 的概率可以計算爲:
P^(w1)=n(w1)n
其中 n(w1) 爲語料庫中以 w1 作爲第一個詞的文本的數量, n 爲語料庫中文本的總數量。
類似的,給定 w1 情況下, w2 的條件概率可以計算爲:
P^(w2∣w1)=n(w1,w2)n(w1)
其中 n(w1,w2) 爲語料庫中以 w1 作爲第一個詞, w2 作爲第二個詞的文本的數量。
n元語法
序列長度增加,計算和存儲多個詞共同出現的概率的複雜度會呈指數級增加。 n 元語法通過馬爾可夫假設簡化模型,馬爾科夫假設是指一個詞的出現只與前面 n 個詞相關,即 n 階馬爾可夫鏈(Markov chain of order n ),如果 n=1 ,那麼有 P(w3∣w1,w2)=P(w3∣w2) 。基於 n−1 階馬爾可夫鏈,我們可以將語言模型改寫爲
P(w1,w2,…,wT)=∏t=1TP(wt∣wt−(n−1),…,wt−1).
以上也叫 n 元語法( n -grams),它是基於 n−1 階馬爾可夫鏈的概率語言模型。例如,當 n=2 時,含有4個詞的文本序列的概率就可以改寫爲:
P(w1,w2,w3,w4)=P(w1)P(w2∣w1)P(w3∣w1,w2)P(w4∣w1,w2,w3)=P(w1)P(w2∣w1)P(w3∣w2)P(w4∣w3)
當 n 分別爲1、2和3時,我們將其分別稱作一元語法(unigram)、二元語法(bigram)和三元語法(trigram)。例如,長度爲4的序列 w1,w2,w3,w4 在一元語法、二元語法和三元語法中的概率分別爲
P(w1,w2,w3,w4)P(w1,w2,w3,w4)P(w1,w2,w3,w4)=P(w1)P(w2)P(w3)P(w4),=P(w1)P(w2∣w1)P(w3∣w2)P(w4∣w3),=P(w1)P(w2∣w1)P(w3∣w1,w2)P(w4∣w2,w3).
當 n 較小時, n 元語法往往並不準確。例如,在一元語法中,由三個詞組成的句子“你走先”和“你先走”的概率是一樣的。然而,當 n 較大時, n 元語法需要計算並存儲大量的詞頻和多詞相鄰頻率。
n 元語法可能有的缺陷
1.參數空間過大
2.數據稀疏
語言模型數據集
1.讀取數據集
2.建立字符索引
3.時序數據的採樣
4.隨機採樣
5.相鄰採樣
循環神經網絡
下圖展示瞭如何基於循環神經網絡實現語言模型。我們的目的是基於當前的輸入與過去的輸入序列,預測序列的下一個字符。循環神經網絡引入一個隱藏變量H,用Ht表示H在時間步t的值。Ht的計算基於Xt和Ht−1,可以認爲Ht記錄了到當前字符爲止的序列信息,利用Ht對序列的下一個字符進行預測。
參考鏈接:
https://www.boyuai.com/elites/course/cZu18YmweLv10OeV/jupyter/74GLt4f6G9GgtnuK_Y7SJ