語言模型導論

使用 Keras 建立語言模型的循環神經網路(RNN)

David Cecchini

Data Scientist

句子機率

可用模型很多

  • 「I loved this movie」的機率。
  • Unigram
    • $$P(\text{sentence}) = P(\text{I})P(\text{loved})P(\text{this})P(\text{movie})$$
  • N-gram
    • N = 2(bigram):$$P(\text{sentence}) = P(\text{I})P(\text{loved} | \text{I})P(\text{this} | \text{loved})P(\text{movie} | \text{this})$$
    • N = 3(trigram):$$P(\text{sentence}) = P(\text{I})P(\text{loved} | \text{I})P(\text{this} | \text{I loved})P(\text{movie} | \text{loved this})$$
使用 Keras 建立語言模型的循環神經網路(RNN)

句子機率(續)

  • Skip gram
    • $$P(\text{sentence}) = P(\text{context of I} | \text{I})P(\text{context of loved} | \text{loved}) \ $$ $$P(\text{context of this} | \text{this})P(\text{context of movie} | \text{movie})$$
  • 類神經網路
    • 句子機率由網路輸出層的 softmax 函式給出。
使用 Keras 建立語言模型的循環神經網路(RNN)

連結到 RNN

語言模型遍佈於 RNN!

  • 網路本身

RNN 可視為語言模型,因為它可用來預測下一個字。

使用 Keras 建立語言模型的循環神經網路(RNN)

連結到 RNN(續)

  • Embedding 層

顯示模型層的概觀。Embedding 層需位在輸入層之後,並產生詞彙的稠密表示。

使用 Keras 建立語言模型的循環神經網路(RNN)

建立詞彙字典

# Get unique words
unique_words = list(set(text.split(' ')))
# Create dictionary: word is key, index is value
word_to_index = {k:v for (v,k) in enumerate(unique_words)}
# Create dictionary: index is key, word is value
index_to_word = {k:v for (k,v) in enumerate(unique_words)}
使用 Keras 建立語言模型的循環神經網路(RNN)

前處理輸入

# Initialize variables X and y
X = []
y = []

# Loop over the text: length `sentence_size` per time with step equal to `step` for i in range(0, len(text) - sentence_size, step):
X.append(text[i:i + sentence_size]) y.append(text[i + sentence_size])
# Example (numbers are numerical indexes of vocabulary):
# Sentence is: "i loved this movie" -> (["i", "loved", "this"], "movie")
X[0],y[0] = ([10, 444, 11], 17)
使用 Keras 建立語言模型的循環神經網路(RNN)

轉換新文本

# Create list to keep the sentences of indexes
new_text_split = []

# Loop and get the indexes from dictionary for sentence in new_text:
sent_split = []
for wd in sentence.split(' '):
ix = wd_to_index[wd]
sent_split.append(ix)
new_text_split.append(sent_split)
使用 Keras 建立語言模型的循環神經網路(RNN)

一起來練習吧!

使用 Keras 建立語言模型的循環神經網路(RNN)

Preparing Video For Download...