LLM 课程文档
Transformers,它们能做什么?
并获得增强的文档体验
开始入门
Transformers,它们能做什么?
在本节中,我们将了解 Transformer 模型能做什么,并使用 🤗 Transformers 库中的第一个工具:pipeline()
函数。
如果您想在本地运行示例,我们建议您查看设置。
Transformers 无处不在!
Transformer 模型用于解决各种 NLP 任务,例如上一节中提到的那些。以下是一些使用 Hugging Face 和 Transformer 模型,并通过共享其模型回馈社区的公司和组织
🤗 Transformers 库提供了创建和使用这些共享模型的功能。模型中心包含数千个预训练模型,任何人都可以下载和使用。您也可以将自己的模型上传到 Hub!
在深入了解 Transformer 模型的工作原理之前,让我们看一些示例,了解如何使用它们来解决一些有趣的 NLP 问题。
使用 pipelines
🤗 Transformers 库中最基本的对象是 pipeline()
函数。它将模型与其必要的预处理和后处理步骤连接起来,使我们能够直接输入任何文本并获得可理解的答案
from transformers import pipeline
classifier = pipeline("sentiment-analysis")
classifier("I've been waiting for a HuggingFace course my whole life.")
[{'label': 'POSITIVE', 'score': 0.9598047137260437}]
我们甚至可以传递多个句子!
classifier(
["I've been waiting for a HuggingFace course my whole life.", "I hate this so much!"]
)
[{'label': 'POSITIVE', 'score': 0.9598047137260437},
{'label': 'NEGATIVE', 'score': 0.9994558095932007}]
默认情况下,此 pipeline 选择一个特定的预训练模型,该模型已针对英语情感分析进行了微调。当您创建 classifier
对象时,模型将被下载并缓存。如果您重新运行命令,将使用缓存的模型,无需再次下载模型。
当您将一些文本传递给 pipeline 时,涉及三个主要步骤
- 文本被预处理成模型可以理解的格式。
- 预处理后的输入被传递给模型。
- 模型的预测结果经过后处理,以便您可以理解它们。
目前可用的 pipelines 有
feature-extraction
(获取文本的向量表示)fill-mask
ner
(命名实体识别)question-answering
sentiment-analysis
summarization
text-generation
translation
zero-shot-classification
让我们看看其中的几个!
Zero-shot 分类
我们将从处理更具挑战性的任务开始,我们需要对未标记的文本进行分类。这是现实世界项目中的常见场景,因为文本注释通常耗时且需要领域专业知识。对于此用例,zero-shot-classification
pipeline 非常强大:它允许您指定用于分类的标签,因此您不必依赖预训练模型的标签。您已经了解了模型如何使用这两个标签将句子分类为正面或负面——但它也可以使用您喜欢的任何其他标签集对文本进行分类。
from transformers import pipeline
classifier = pipeline("zero-shot-classification")
classifier(
"This is a course about the Transformers library",
candidate_labels=["education", "politics", "business"],
)
{'sequence': 'This is a course about the Transformers library',
'labels': ['education', 'business', 'politics'],
'scores': [0.8445963859558105, 0.111976258456707, 0.043427448719739914]}
此 pipeline 称为zero-shot,因为您无需在数据上微调模型即可使用它。它可以直接返回您想要的任何标签列表的概率分数!
✏️ 试试看! 尝试使用您自己的序列和标签,看看模型的表现如何。
文本生成
现在让我们看看如何使用 pipeline 生成一些文本。这里的中心思想是您提供一个提示,模型将通过生成剩余文本来自动完成它。这类似于在许多手机上找到的预测文本功能。文本生成涉及随机性,因此如果您没有获得与下面显示的结果相同的结果,这是正常的。
from transformers import pipeline
generator = pipeline("text-generation")
generator("In this course, we will teach you how to")
[{'generated_text': 'In this course, we will teach you how to understand and use '
'data flow and data interchange when handling user data. We '
'will be working with one or more of the most commonly used '
'data flows — data flows of various types, as seen by the '
'HTTP'}]
您可以使用参数 num_return_sequences
控制生成多少个不同的序列,并使用参数 max_length
控制输出文本的总长度。
✏️ 试试看! 使用 num_return_sequences
和 max_length
参数生成两个句子,每个句子 15 个单词。
在 pipeline 中使用 Hub 中的任何模型
之前的示例使用了手头任务的默认模型,但您也可以从 Hub 中选择一个特定模型,用于 pipeline 中的特定任务——例如,文本生成。转到模型中心并单击左侧的相应标签,以仅显示该任务支持的模型。您应该进入类似此页面的页面。
让我们试试 distilgpt2
模型!以下是如何在与之前相同的 pipeline 中加载它
from transformers import pipeline
generator = pipeline("text-generation", model="distilgpt2")
generator(
"In this course, we will teach you how to",
max_length=30,
num_return_sequences=2,
)
[{'generated_text': 'In this course, we will teach you how to manipulate the world and '
'move your mental and physical capabilities to your advantage.'},
{'generated_text': 'In this course, we will teach you how to become an expert and '
'practice realtime, and with a hands on experience on both real '
'time and real'}]
您可以通过单击语言标签来优化模型搜索,并选择一个将生成其他语言文本的模型。模型中心甚至包含支持多种语言的多语言模型的检查点。
选择模型后,单击它,您将看到一个 widget,使您能够直接在线试用它。这样,您可以在下载模型之前快速测试模型的功能。
✏️ 试试看! 使用过滤器查找另一种语言的文本生成模型。随意使用 widget 并在 pipeline 中使用它!
Inference API
所有模型都可以通过浏览器使用 Inference API 直接进行测试,Inference API 在 Hugging Face 网站上可用。您可以在此页面上直接使用模型,方法是输入自定义文本并观看模型处理输入数据。
为 widget 提供支持的 Inference API 也作为付费产品提供,如果您需要在工作流程中使用它,这将非常方便。有关更多详细信息,请参阅定价页面。
Mask 填充
您将尝试的下一个 pipeline 是 fill-mask
。此任务的想法是填写给定文本中的空白
from transformers import pipeline
unmasker = pipeline("fill-mask")
unmasker("This course will teach you all about <mask> models.", top_k=2)
[{'sequence': 'This course will teach you all about mathematical models.',
'score': 0.19619831442832947,
'token': 30412,
'token_str': ' mathematical'},
{'sequence': 'This course will teach you all about computational models.',
'score': 0.04052725434303284,
'token': 38163,
'token_str': ' computational'}]
top_k
参数控制您要显示多少种可能性。请注意,此处模型填充了特殊的 <mask>
单词,该单词通常称为掩码标记。其他 mask 填充模型可能具有不同的掩码标记,因此在探索其他模型时,最好始终验证正确的掩码词。检查它的一种方法是查看 widget 中使用的掩码词。
✏️ 试试看! 在 Hub 上搜索 bert-base-cased
模型,并在 Inference API widget 中识别其掩码词。此模型对我们上面 pipeline
示例中的句子预测什么?
命名实体识别
命名实体识别 (NER) 是一项任务,模型必须在其中找到输入文本的哪些部分对应于实体,例如人、地点或组织。让我们看一个例子
from transformers import pipeline
ner = pipeline("ner", grouped_entities=True)
ner("My name is Sylvain and I work at Hugging Face in Brooklyn.")
[{'entity_group': 'PER', 'score': 0.99816, 'word': 'Sylvain', 'start': 11, 'end': 18},
{'entity_group': 'ORG', 'score': 0.97960, 'word': 'Hugging Face', 'start': 33, 'end': 45},
{'entity_group': 'LOC', 'score': 0.99321, 'word': 'Brooklyn', 'start': 49, 'end': 57}
]
在这里,模型正确地识别出 Sylvain 是一个人 (PER),Hugging Face 是一个组织 (ORG),而 Brooklyn 是一个地点 (LOC)。
我们在 pipeline 创建函数中传递选项 grouped_entities=True
,以告诉 pipeline 将句子中对应于同一实体的部分重新组合在一起:在这里,模型正确地将“Hugging”和“Face”组合为一个组织,即使该名称由多个单词组成。事实上,正如我们将在下一章中看到的那样,预处理甚至将一些单词拆分成更小的部分。例如,Sylvain
被拆分为四个部分:S
、##yl
、##va
和 ##in
。在后处理步骤中,pipeline 成功地重新组合了这些部分。
✏️ 试试看! 在模型中心搜索能够以英语进行词性标注(通常缩写为 POS)的模型。此模型对上面示例中的句子预测什么?
问答
question-answering
pipeline 使用给定上下文中的信息回答问题
from transformers import pipeline
question_answerer = pipeline("question-answering")
question_answerer(
question="Where do I work?",
context="My name is Sylvain and I work at Hugging Face in Brooklyn",
)
{'score': 0.6385916471481323, 'start': 33, 'end': 45, 'answer': 'Hugging Face'}
请注意,此 pipeline 通过从提供的上下文中提取信息来工作;它不会生成答案。
摘要
摘要是将文本缩减为较短文本的任务,同时保留文本中引用的所有(或大部分)重要方面。这是一个例子
from transformers import pipeline
summarizer = pipeline("summarization")
summarizer(
"""
America has changed dramatically during recent years. Not only has the number of
graduates in traditional engineering disciplines such as mechanical, civil,
electrical, chemical, and aeronautical engineering declined, but in most of
the premier American universities engineering curricula now concentrate on
and encourage largely the study of engineering science. As a result, there
are declining offerings in engineering subjects dealing with infrastructure,
the environment, and related issues, and greater concentration on high
technology subjects, largely supporting increasingly complex scientific
developments. While the latter is important, it should not be at the expense
of more traditional engineering.
Rapidly developing economies such as China and India, as well as other
industrial countries in Europe and Asia, continue to encourage and advance
the teaching of engineering. Both China and India, respectively, graduate
six and eight times as many traditional engineers as does the United States.
Other industrial countries at minimum maintain their output, while America
suffers an increasingly serious decline in the number of engineering graduates
and a lack of well-educated engineers.
"""
)
[{'summary_text': ' America has changed dramatically during recent years . The '
'number of engineering graduates in the U.S. has declined in '
'traditional engineering disciplines such as mechanical, civil '
', electrical, chemical, and aeronautical engineering . Rapidly '
'developing economies such as China and India, as well as other '
'industrial countries in Europe and Asia, continue to encourage '
'and advance engineering .'}]
与文本生成一样,您可以为结果指定 max_length
或 min_length
。
翻译
对于翻译,如果您在任务名称中提供语言对(例如 "translation_en_to_fr"
),则可以使用默认模型,但最简单的方法是在模型中心选择要使用的模型。在这里,我们将尝试从法语翻译成英语
from transformers import pipeline
translator = pipeline("translation", model="Helsinki-NLP/opus-mt-fr-en")
translator("Ce cours est produit par Hugging Face.")
[{'translation_text': 'This course is produced by Hugging Face.'}]
与文本生成和摘要一样,您可以为结果指定 max_length
或 min_length
。
✏️ 试试看! 搜索其他语言的翻译模型,并尝试将上一句话翻译成几种不同的语言。
到目前为止显示的 pipelines 主要用于演示目的。它们是为特定任务而编程的,无法执行它们的变体。在下一章中,您将了解 pipeline()
函数的内部结构以及如何自定义其行为。