开始使用免费开始使用

第 1 部分:文本反转模型 - Encoder

创建一个简单的文本反转模型,是理解编码器-解码器(encoder-decoder)模型机制及其连接方式的有效方法。接下来,您将实现文本反转模型的编码器部分。

本节把编码器的实现拆分为两个练习。在本练习中,您将定义辅助函数 words2onehot()。该函数应接收一个单词列表和字典 word2index,并将该单词列表转换为由 one-hot 向量组成的数组。工作区中已提供 word2index 字典。

本练习是课程的一部分

使用 Keras 的机器翻译

查看课程

练习说明

  • words2onehot() 函数中,使用字典 word2index 将单词转换为 ID。
  • 将单词 ID 转换为长度为 3 的 one-hot 向量(使用 num_classes 参数),并返回结果数组。
  • 调用 words2onehot() 函数,传入单词 Ilikecats,并将结果赋给 onehot
  • 使用 print()zip() 函数打印单词及其对应的 one-hot 向量。zip() 函数可同时遍历多个列表。

交互式实操练习

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

import numpy as np

def words2onehot(word_list, word2index):
  # Convert words to word IDs
  word_ids = [____[w] for w in ____]
  # Convert word IDs to onehot vectors and return the onehot array
  onehot = ____(____, num_classes=3)
  return ____

words = ["I", "like", "cats"]
# Convert words to onehot vectors using words2onehot
onehot = ____(____, ____)
# Print the result as (, ) tuples
print([(w,ohe.tolist()) for ____,____ in zip(words, ____)])
编辑并运行代码