# Data
data = ["Two little dicky birds",
"Sat on a wall,",
"One called Peter,",
"One called Paul.",
"Fly away, Peter,",
"Fly away, Paul!",
"Come back, Peter,",
"Come back, Paul."]
def prepare_sentence(seq, maxlen):
# Pads seq and slides windows
x = []
y = []
for i, w in enumerate(seq):
x_padded = pad_sequences([seq[:i]],
maxlen=maxlen - 1,
padding='pre')[0] # Pads before each sequence
x.append(x_padded)
y.append(w)
return x, y
# Pad sequences and slide windows
maxlen = max([len(seq) for seq in seqs])
x = []
y = []
for seq in seqs:
x_windows, y_windows = prepare_sentence(seq, maxlen)
x += x_windows
y += y_windows
x = np.array(x)
y = np.array(y) - 1 # The word <PAD> does not constitute a class
y = np.eye(len(vocab))[y] # One hot encoding
# Define model
model = Sequential()
model.add(Embedding(input_dim=len(vocab) + 1, # vocabulary size. Adding an
# extra element for <PAD> word
output_dim=5, # size of embeddings
input_length=maxlen - 1)) # length of the padded sequences
model.add(LSTM(10))
model.add(Dense(len(vocab), activation='softmax'))
model.compile('rmsprop', 'categorical_crossentropy')
# Train network
model.fit(x, y, epochs=1000)
# Compute probability of occurence of a sentence
sentence = "One called Peter,"
tok = tokenizer.texts_to_sequences([sentence])[0]
x_test, y_test = prepare_sentence(tok, maxlen)
x_test = np.array(x_test)
y_test = np.array(y_test) - 1 # The word <PAD> does not constitute a class
p_pred = model.predict(x_test) # array of conditional probabilities
vocab_inv = {v: k for k, v in vocab.items()}
# Compute product
# Efficient version: np.exp(np.sum(np.log(np.diag(p_pred[:, y_test]))))
log_p_sentence = 0
for i, prob in enumerate(p_pred):
word = vocab_inv[y_test[i]+1] # Index 0 from vocab is reserved to <PAD>
history = ' '.join([vocab_inv[w] for w in x_test[i, :] if w != 0])
prob_word = prob[y_test[i]]
log_p_sentence += np.log(prob_word)
print('P(w={}|h={})={}'.format(word, history, prob_word))
print('Prob. sentence: {}'.format(np.exp(log_p_sentence)))
1条答案
按热度按时间uidvcgyl1#
我刚刚编写了一个非常简单的例子,展示了如何用LSTM模型计算句子出现的概率。完整的代码可以在here中找到。
假设我们想要预测以下数据集的句子出现概率(这首诗发表在1765年左右伦敦的《鹅妈妈的旋律》上):
首先,让我们使用keras.preprocessing.text.Tokenizer来创建一个词汇表,并将句子标记化:
我们的模型将一个单词序列作为输入(上下文),并输出给定上下文的词汇表中每个单词的条件概率分布。为此,我们通过填充序列和在其上滑动窗口来准备训练数据:
我决定为每一节单独滑动窗口,但这可以用不同的方式来完成。
接下来,我们用Keras定义并训练一个简单的LSTM模型,该模型由一个嵌入层、一个LSTM层和一个带有softmax激活的密集层组成(softmax激活使用LSTM最后一个时间步的输出来产生给定上下文的词汇表中每个单词的概率):
句子
w_1 ... w_n
的出现的联合概率P(w_1, ..., w_n)
可以使用条件概率的规则来计算:P(w_1, ..., w_n)=P(w_1)*P(w_2|w_1)*...*P(w_n|w_{n-1}, ..., w_1)
其中每个条件概率都由LSTM模型给出。请注意,它们可能非常小,因此在对数空间中工作以避免数值不稳定性问题是明智的。将所有这些放在一起:
注意:这是一个非常小的玩具数据集,我们可能会过度拟合。
**UPDATE 29/10/2022:**对于更大的数据集,如果一次性处理整个数据集,很可能会出现内存不足的情况。在这种情况下,我建议使用生成器来训练模型。请参见this gist,了解使用数据生成器的修改版本。