开始使用免费开始使用

文本生成示例

在本练习中,您将体验两个用于文本生成的预训练模型。

第一个模型会基于《The Big Bang Theory》(生活大爆炸)中角色 Sheldon 的说话风格生成一句话;第二个模型会生成一段莎士比亚风格的诗歌,长度最多 400 个字符。

模型分别加载在变量 sheldon_modelpoem_model 中。此外,还提供了两个用于生成文本的自定义函数:generate_sheldon_phrase()generate_poem()。这两个函数都接收预训练模型和上下文字串作为参数。

本练习是课程的一部分

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

查看课程

练习说明

  • 使用预定义函数 generate_sheldon_phrase(),传入参数 sheldon_modelsheldon_context,并将输出保存到变量 sheldon_phrase
  • 打印生成的这句话。
  • 将给定文本保存到变量 poem_context
  • 使用函数 generate_poem(),传入 poem_modelpoem_context 参数,打印生成的诗歌。

交互式实操练习

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

# Context for Sheldon phrase
sheldon_context = "I’m not insane, my mother had me tested. "

# Generate one Sheldon phrase
sheldon_phrase = ____(sheldon_model, sheldon_context)

# Print the phrase
print(____)

# Context for poem
____ = "May thy beauty forever remain"

# Print the poem
print(generate_poem(____, poem_context))
编辑并运行代码