开始使用免费开始使用

构建文本生成 pipeline

Hugging Face 的 pipeline 让您可以轻松调用机器学习模型完成多种任务。在本练习中,您将使用 gpt2 模型构建文本生成 pipeline,并通过调整参数来自定义输出。

欢迎在 pipeline 中尝试不同的提示语,例如:"What if …?""How to …?",或任何您想探索的创意开头。

本练习是课程的一部分

使用 Hugging Face

查看课程

练习说明

  • 补全缺失代码,使用 "gpt2" 模型构建一个文本生成 pipeline。
  • 提供一条您自选的自定义短句作为输入提示,尽量简短以避免超时。
  • 将 pipeline 配置为生成最多 10 个 token,并产生2 个输出

交互式实操练习

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

from transformers import ____ 

gpt2_pipeline = ____(task="____", model="openai-community/gpt2")

# Generate three text outputs with a maximum length of 10 tokens
results = gpt2_pipeline("What if AI", max_new_tokens=____, num_return_sequences=____)

for result in results:
    print(result['generated_text'])
编辑并运行代码