开始使用免费开始使用

Keras 预处理

Keras 的第二个重要模块是 keras.preprocessing。您将学习如何使用其中最关键的模块和函数,把原始数据整理为模型所需的输入形状。Keras 提供的功能可以替代您之前学到的基于字典的做法。

您将使用模块 keras.preprocessing.text.Tokenizer,先通过 .fit_on_texts() 方法基于文本语料创建词典,再用 .texts_to_sequences() 方法把文本转换为数值 id,即每个词在词典中的索引。

随后,使用 keras.preprocessing.sequence 中的 .pad_sequences() 函数,让所有序列长度一致(模型所必需):对较短的文本在末尾补 0,对较长的文本进行截断。

本练习是课程的一部分

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

查看课程

练习说明

  • 从相关模块导入 Tokenizerpad_sequences
  • 在存放示例数据的 texts 上拟合 tokenizer 对象。
  • 使用 .texts_to_sequences() 方法将文本转换为数值索引序列。
  • 通过填充序列来统一文本长度。

交互式实操练习

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

# Import relevant classes/functions
from tensorflow.keras.preprocessing.text import ____
from tensorflow.keras.preprocessing.sequence import ____

# Build the dictionary of indexes
tokenizer = Tokenizer()
tokenizer.fit_on_texts(____)

# Change texts into sequence of indexes
texts_numeric = tokenizer.____(texts)
print("Number of words in the sample texts: ({0}, {1})".format(len(texts_numeric[0]), len(texts_numeric[1])))

# Pad the sequences
texts_pad = ____(texts_numeric, 60)
print("Now the texts have fixed length: 60. Let's see the first one: \n{0}".format(texts_pad[0]))
编辑并运行代码