在本節中,我們將看看 Transformer 模型可以做什麼,並使用 🤗 Transformers 庫中的第一個工具:pipeline() 函數。
如果您想在本地運行示例,我們建議您查看準備.
🤗 Transformers 庫提供了創建和使用這些共享模型的功能。模型中心(hub)包含數千個任何人都可以下載和使用的預訓練模型。您還可以將自己的模型上傳到 Hub!
在深入研究 Transformer 模型的底層工作原理之前,讓我們先看幾個示例,看看它們如何用於解決一些有趣的 NLP 問題。
🤗 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選擇一個特定的預訓練模型,該模型已針對英語情感分析進行了微調。創建分類器對象時,將下載並緩存模型。如果您重新運行該命令,則將使用緩存的模型,無需再次下載模型。
將一些文本傳遞到pipeline時涉及三個主要步驟:
目前可用的一些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,因為您不需要對數據上的模型進行微調即可使用它。它可以直接返回您想要的任何標籤列表的概率分數!
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 控制輸出文本的總長度。
讓我們試試 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'}]
您可以通過單擊語言標籤來篩選搜索結果,然後選擇另一種文本生成模型的模型。模型中心(hub)甚至包含支持多種語言的多語言模型。
通過單擊選擇模型後,您會看到有一個小組件,可讓您直接在線試用。通過這種方式,您可以在下載之前快速測試模型的功能。
小組件形式的推理 API 也可作為付費產品使用,如果您的工作流程需要它,它會派上用場。有關更多詳細信息,請參閱定價頁面。
unmasker = pipeline(“fill-mask”) unmasker(“This course will teach you all about <mask> models.”, top_k=2)
```python out
[{'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 >詞,它通常被稱為掩碼標記。其他掩碼填充模型可能有不同的掩碼標記,因此在探索其他模型時要驗證正確的掩碼字是什麼。檢查它的一種方法是查看小組件中使用的掩碼。
ner = pipeline(“ner”, grouped_entities=True) ner(“My name is Sylvain and I work at Hugging Face in Brooklyn.“)
```python out
[{'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),而布魯克林是一個位置 (LOC)。
我們在pipeline創建函數中傳遞選項 grouped_entities=True 以告訴pipeline將對應於同一實體的句子部分重新組合在一起:這裡模型正確地將「Hugging」和「Face」分組為一個組織,即使名稱由多個詞組成。事實上,正如我們即將在下一章看到的,預處理甚至會將一些單詞分成更小的部分。例如,Sylvain 分割為了四部分:S、##yl、##va 和 ##in。在後處理步驟中,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”, )
```python out
{'score': 0.6385916471481323, 'start': 33, 'end': 45, 'answer': 'Hugging Face'}
klyn",
)
請注意,此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。
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。
✏️快來試試吧!搜索其他語言的翻譯模型,嘗試將前一句翻譯成幾種不同的語言。
到目前為止顯示的pipeline主要用於演示目的。它們是為特定任務而編程的,不能對他們進行自定義的修改。在下一章中,您將瞭解 pipeline() 函數內部的內容以及如何進行自定義的修改。