开始使用免费开始使用

为模型输入准备文本数据

在前面,您已经学习了如何创建"索引到单词"和"单词到索引"的字典。在本练习中,您将按字符拆分文本,并继续为监督学习准备数据。

把文本拆成字符看起来有些奇怪,但在文本生成任务中很常见。而且,准备数据的流程相同,唯一的变化是如何拆分文本。

您将创建训练数据,其中包含定长文本的列表及其标签,标签是对应的下一个字符。

您将继续使用包含 Sheldon(《The Big Bang Theory》)台词的数据集,存放在变量 sheldon_quotes 中。

函数 print_examples() 会打印这些配对,便于您查看数据是如何被转换的。详情请使用 help()

本练习是课程的一部分

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

查看课程

练习说明

  • step 设为 2,将 chars_window 设为 10
  • 将下一个句子追加到变量 sentences
  • 将文本 sheldon 中的正确位置追加到变量 next_chars
  • 使用函数 print_examples() 打印 10 个句子及其下一个字符。

交互式实操练习

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

# Create lists to keep the sentences and the next character
sentences = []   # ~ Training data
next_chars = []  # ~ Training labels

# Define hyperparameters
step = ____          # ~ Step to take when reading the texts in characters
chars_window = ____ # ~ Number of characters to use to predict the next one  

# Loop over the text: length `chars_window` per time with step equal to `step`
for i in range(0, len(sheldon_quotes) - chars_window, step):
    sentences.____(sheldon_quotes[i:i + chars_window])
    next_chars.append(sheldon_quotes[____])

# Print 10 pairs
print_examples(____, ____, 10)
编辑并运行代码