第 1 部分:探索 to_categorical() 函数
您是否知道,在真实场景中,词汇表的规模可能会非常大(例如超过十万)?
本练习分为两部分,您将学习为何需要为 to_categorical() 函数设置 num_classes 参数。在第 1 部分,您将实现函数 compute_onehot_length(),它会为给定的单词列表生成 one-hot 向量,并计算这些向量的长度。
to_categorical() 函数已为您导入。
本练习是课程的一部分
使用 Keras 的机器翻译
练习说明
- 在
compute_onehot_length()中,使用words和word2index生成单词 ID。 - 使用单词 ID 调用
to_categorical()函数创建 one-hot 向量。 - 使用
<array>.shape语法返回单个 one-hot 向量的长度。 - 使用
compute_onehot_length()计算并打印单词列表He、drank、milk的 one-hot 向量长度。
交互式实操练习
通过完成这段示例代码来试试这个练习。
def compute_onehot_length(words, word2index):
# Create word IDs for words
word_ids = [____[w] for w in ____]
# Convert word IDs to onehot vectors
onehot = ____(____)
# Return the length of a single one-hot vector
return onehot.____[1]
word2index = {"He":0, "drank": 1, "milk": 2}
# Compute and print onehot length of a list of words
print(____([____,____,____], ____))