第 1 部分:寻宝
您刚刚赢得了一次全额资助的热带海岛之旅。四处漫步时,您发现了一张指向巨大宝藏的古老藏宝图,上面用 1 和 0 写着几条秘密信息。刚学完本课程的您立刻认出,那是一串 onehot 编码的向量。您还很幸运地找到了词到索引的映射,能知道每个单词对应哪个 ID。
现在,您需要解密这条密语,弄清这张地图在说什么。我们为您提供了一个 treasure_map,它是一个由 句子数 × 单词数 × onehot 向量长度 组成的矩阵。我们还提供了 index2word 这个 Python 字典,用于将 ID 映射到单词。
本练习是课程的一部分
使用 Keras 的机器翻译
练习说明
- 从
treasure_map中获取 onehot 编码向量对应的词 ID(onehot 向量维度在最后一个维度)。 - 从
treasure_map中获取序列长度(即时间步数),并赋值给seq_len。 - 获取第
i个句子中第t个位置的词 ID。 - 将与
wid对应的字符串单词(即不是词 ID)追加到列表words中。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Get the word IDs from the treasure map
word_ids = ____.____(____, axis=____)
# Get the sequence length from the treasure map
seq_len = treasure_map.shape[____]
for i in range(treasure_map.shape[0]):
words = []
for t in range(seq_len):
# Get the word ID for the i-th sentence and t-th position
wid = word_ids[i, ____]
if wid != 0:
# Append the word corresponding to wid
words.append(____[____])
print("Instruction ", i+1, ": ", ' '.join(words))