开始使用免费开始使用

训练基于词嵌入的模型

在这里,您将学习如何为使用词嵌入的机器翻译模型实现训练过程。与之前练习使用独热编码向量不同,这里每个词用一个单独的数字表示。您将以小批量遍历完整数据集,并训练多个 epoch。

本练习为您提供了训练数据(tr_entr_fr),形式为句子列表。为避免训练时间过长,您只会使用一个很小的样本(1000 个句子)。您还将使用上一个练习中实现的 sents2seqs() 函数和模型 nmt_emb。请记住,我们用 en_x 表示编码器输入,用 de_x 表示解码器输入。

本练习是课程的一部分

使用 Keras 的机器翻译

查看课程

练习说明

  • 使用 sents2seqs() 函数,在不进行独热编码的情况下获取一批法语句子。
  • de_xy 中获取除「最后一个」以外的所有词。
  • de_xy_oh(使用独热编码的法语词)中获取除「第一个」以外的所有词。
  • 使用这一批数据训练模型。

交互式实操练习

通过完成这段示例代码来试试这个练习。

for ei in range(3):
  for i in range(0, train_size, bsize):    
    en_x = sents2seqs('source', tr_en[i:i+bsize], onehot=False, reverse=True)
    # Get a single batch of French sentences with no onehot encoding
    de_xy = ____('target', ____[i:i+bsize], ____=____)
    # Get all words except the last word in that batch
    de_x = de_xy[:,____]
    de_xy_oh = sents2seqs('target', tr_fr[i:i+bsize], onehot=True)
    # Get all words except the first from de_xy_oh
    de_y = de_xy_oh[____,____,____]
    # Training the model on a single batch of data
    nmt_emb.train_on_batch([____,____], ____)    
    res = nmt_emb.evaluate([en_x, de_x], de_y, batch_size=bsize, verbose=0)
    print("{} => Loss:{}, Train Acc: {}".format(ei+1,res[0], res[1]*100.0))
编辑并运行代码