第 2 部分:寻宝
现在给寻宝游戏加一点变化。您忘了带笔记本电脑,手头只有一台内存有限的设备。您编写的代码必须少于 4 行(不含注释)。由于需要尽可能精简代码,您将使用列表推导式。
列表推导式可以用一行代码遍历数据。例如,若要从一组数字中取出所有偶数,可以写 [n for n in range(100) if n%2==0]。由此可见,列表推导式可以把 for 循环和 if 语句合并到一行代码中。
本练习是课程的一部分
使用 Keras 的机器翻译
练习说明
- 获取
treasure_map中独热编码向量对应的词 ID。 - 获取 treasure map 的批量大小(最前面的维度),并据此创建一个 for 循环。
- 通过遍历
word_ids的第 i 行来获得第 i 个句子的词,同时忽略等于 0 的词 ID。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Get the word IDs from the treasure map
word_ids = np.argmax(____, axis=-1)
# Get the batch size from the treasure map
for i in range(treasure_map.shape[____]):
# Get all the words of the i-th sentence using list comprehension
words = [index2word[____] for wid in word_ids[____] if wid != ____]
print("Instruction ", i+1, ": ", ' '.join(words))