开始使用免费开始使用

准备输出文本

在本练习中,您将准备用于翻译模型的输出文本。除了将文本转换为索引序列外,还需要对每个索引进行独热编码(one-hot encoding)。

英文文本已加载到变量 en_sentences,已拟合的分词器(tokenizer)在变量 output_tokenizer 中,英文词表大小在 en_vocab_size 中。

此外,已为输出语言转换(将文本转换为索引序列)的前几步创建了函数。该函数已作为 transform_text_to_sequences() 加载到环境中,包含两个参数:sentences(期望传入英文句子列表)和 tokenizer(期望传入来自 keras.preprocessing.text 模块、已拟合的 Tokenizer 对象)。

numpy 已以 np 导入。

本练习是课程的一部分

使用 Keras 构建语言建模的循环神经网络(RNN)

查看课程

练习说明

  • en_sentencesoutput_tokenizer 传入 transform_text_to_sequences() 函数,初始化变量 Y
  • 使用 to_categorical() 函数对句子进行独热编码,类别数使用变量 en_vocab_size
  • 将临时列表转换为 numpy 数组,并重塑为形状 (num_sentences, sentences_len, en_vocab_size)
  • 打印原始文本及其转换结果。

交互式实操练习

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

# Initialize the variable
Y = transform_text_to_sequences(____, ____)

# Temporary list
ylist = list()
for sequence in Y:
  	# One-hot encode sentence and append to list
    ylist.append(____(sequence, num_classes=____))

# Update the variable
Y = np.array(ylist).reshape(____, Y.shape[1], en_vocab_size)

# Print the raw sentence and its transformed version
print("Raw sentence: {0}\nTransformed: {1}".format(____, Y[0]))
编辑并运行代码