在这个部分,我们将探讨Transformer 模型的功能,并使用Transformers库的第一个工具: pipeline()
函数。
Transformers are everywhere!
Transformer模型被用于解决各种自然语言处理任务,如前一节中提到的。以下是使用Hugging Face和Transformer模型的一些公司和组织,他们也通过分享模型为社区做出了贡献:
Transformers库提供了创建和使用这些共享模型的功能。模型仓库包含数千个预训练模型,任何人都可以下载和使用。你也可以将自己的模型上传到仓库!
在深入了解Transformer模型的内部工作原理之前,让我们先看看它们如何用于解决一些有趣的自然语言问题。
Working with 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 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被称为零样本,因为你不需要在你的数据上微调模型就可以使用它。它可以直接为你想要的任何标签列表返回概率分数!
Text generation
现在让我们看看如何使用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控制输出文本的总长度。
Using any model from the Hub in a pipeline
之前的示例使用了手头任务的默认模型,但您也可以选择特定模型,将其用于特定任务的pipeline中,比如 text generation。前往模型库,点击左侧相应的标签,只显示该任务支持的模型。例如,您会看到类似这样的页面。
让我们尝试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'}]
您可以根据语言标签进行更精确的搜索,选择一个能生成其他语言文本的模型。模型库甚至包含支持多种语言的多语言检查点。
选择模型后,您会看到一个在线试用的控件。这样可以在下载模型之前快速测试其功能。
The Inference API
所有模型都可以通过Hugging Face网站的Inference API直接在浏览器中测试。您可以通过输入自定义文本,观察模型处理输入数据,来直接在这个页面上使用模型。
驱动这个控件的 Inference API 也作为付费产品提供,如果您在工作流程中需要它,这会非常有用。有关详细信息,请查看定价页面。
Mask filling
下一个要尝试的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>
词,这通常称为掩码令牌。其他填充空缺的模型可能有不同的掩码词,所以在探索其他模型时,最好核实正确的掩码词。一种检查方法是查看在控件中使用的掩码词。
Named entity recognition
命名实体识别(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
, and ##in
.。在后处理步骤中,pipeline成功地将这些部分重新组合。
✏️ Try it out! 在模型库中搜索一个能进行英语词性标注(通常缩写为POS)的模型。这个模型对上述例子中的句子有何预测?
Question answering
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'}
请注意,这个管道通过从提供的上下文中提取信息来工作,它不会生成答案。
Summarization
摘要任务是将文本缩短为较短的文本,同时保留文本中的所有(或大部分)重要信息。看一个例子:
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
对于翻译,如果您在任务名称中提供语言对(如"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主要用于演示目的。它们是为特定任务编写的,无法执行其变体。在下一章中,你将学习pipelines函数内部的结构,以及如何自定义其行为。