开始使用免费开始使用

动态类别分配

动态类别分配使模型即使未针对某些类别进行过训练,也能将文本归入预定义类别。

使用 Hugging Face 的 pipeline() 并选择 zero-shot-classification 任务,提供文本和预定义类别来找出最佳匹配。

构建一个分类器来预测输入 text 的标签。该输入是一条已为您加载的新闻标题。

已为您预加载 transformers 库中的 pipelines 以便使用。

注意: 我们使用了自定义版本的 pipeline,帮助您在无需下载模型的情况下学习如何使用这些函数。

本练习是课程的一部分

使用 Hugging Face

查看课程

练习说明

  • 构建 pipeline 并保存为 classifier
  • 创建标签列表:"politics""science""sports",并保存为 categories
  • 使用分类器和预定义类别预测 text 的标签。

交互式实操练习

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

text = "AI-powered robots assist in complex brain surgeries with precision."

# Create the pipeline
____ = pipeline(____="zero-shot-classification", ____="facebook/bart-large-mnli")

# Create the categories list
categories = ["politics", "____", "____"]

# Predict the output
output = ____(____, ____)

# Print the top label and its score
print(f"Top Label: {output['labels'][0]} with score: {output['scores'][0]}")
编辑并运行代码