语言模型简介

使用 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(续)

  • 嵌入层

显示模型各层的宏观结构。嵌入层应在输入层之后的第一层,生成词的稠密表示。

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

Vamos praticar!

使用 Keras 构建语言建模的循环神经网络(RNN)

Preparing Video For Download...