第 2 部分:探索 to_categorical() 函数
在第 1 部分中,您实现了 compute_onehot_length() 函数,但在计算独热向量时没有使用 num_classes 参数。
to_categorical() 函数中的 num_classes 参数用于控制生成的独热编码向量的长度。您将看到,当有两个语料库(即文本集合)且它们的词汇表不同,如果不指定 num_classes,就可能得到长度不一致的独热向量。
本练习已为您提供 compute_onehot_length() 函数和 word2index 字典。
本练习是课程的一部分
使用 Keras 的机器翻译
练习说明
- 对
words_1调用compute_onehot_length()。 - 对
words_2调用compute_onehot_length()。 - 打印
words_1和words_2得到的独热向量长度。
交互式实操练习
通过完成这段示例代码来试试这个练习。
words_1 = ["I", "like", "cats", "We", "like", "dogs", "He", "hates", "rabbits"]
# Call compute_onehot_length on words_1
length_1 = ____(____, ____)
words_2 = ["I", "like", "cats", "We", "like", "dogs", "We", "like", "cats"]
# Call compute_onehot_length on words_2
length_2 = ____(____, ____)
# Print length_1 and length_2
print("length_1 =>", ____, " and length_2 => ", ____)