生成翻译
现在,您将使用通过 Teacher Forcing 训练得到的推理模型来生成法语翻译。
该模型(nmt_tf)在 100,000 条句子上训练了 50 个 epoch,在 35,000+ 的验证集上达到了约 98% 的准确率。本练习初始化可能会稍慢一些,因为需要加载已训练的模型。我们已为您提供 sents2seqs() 函数。同时提供了两个新函数:
word2onehot(tokenizer, word, vocab_size),其参数为:
- tokenizer - 一个 Keras 的
Tokenizer对象 - word - 词表中的一个字符串(例如
'apple') - vocab_size - 词表大小
probs2word(probs, tok),其参数为:
- probs - 模型的输出,形状为
[1,<French Vocab Size>] - tok - 一个 Keras 的
Tokenizer对象
您可以在控制台输入 print(inspect.getsource(word2onehot)) 和 print(inspect.getsource(probs2word)) 来查看这些函数的源代码。
本练习是课程的一部分
使用 Keras 的机器翻译
练习说明
- 使用编码器预测初始解码器状态(
de_s_t)。 - 使用上一次的预测结果(输出)和上一次的状态作为输入,从解码器中预测当前输出和新状态。请记得以递归方式更新并生成新状态。
- 使用
probs2word()函数从概率输出中得到对应的词字符串。 - 使用
word2onehot()函数将该词字符串转换为独热序列。
交互式实操练习
通过完成这段示例代码来试试这个练习。
en_sent = ['the united states is sometimes chilly during december , but it is sometimes freezing in june .']
print('English: {}'.format(en_sent))
en_seq = sents2seqs('source', en_sent, onehot=True, reverse=True)
# Predict the initial decoder state with the encoder
de_s_t = ____.predict(____)
de_seq = word2onehot(fr_tok, 'sos', fr_vocab)
fr_sent = ''
for i in range(fr_len):
# Predict from the decoder and recursively assign the new state to de_s_t
de_prob, ____ = ____.predict([____,____])
# Get the word from the probability output using probs2word
de_w = probs2word(____, fr_tok)
# Convert the word to a onehot sequence using word2onehot
de_seq = word2onehot(fr_tok, ____, fr_vocab)
if de_w == 'eos': break
fr_sent += de_w + ' '
print("French (Ours): {}".format(fr_sent))
print("French (Google Translate): les etats-unis sont parfois froids en décembre, mais parfois gelés en juin")