NLP Course documentation

Transformers能做什麼?

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Transformers能做什麼?

Ask a Question Open In Colab Open In Studio Lab

在本節中,我們將看看 Transformer 模型可以做什麼,並使用 🤗 Transformers 庫中的第一個工具:pipeline() 函數。

👀 看到那個右上角的 在Colab中打開的按鈕了嗎? 單擊它就可以打開一個包含本節所有代碼示例的 Google Colab 筆記本。 每一個有實例代碼的小節都會有它。

如果您想在本地運行示例,我們建議您查看準備.

Transformer被應用於各個方面!

Transformer 模型用於解決各種 NLP 任務,就像上一節中提到的那樣。以下是一些使用 Hugging Face 和 Transformer 模型的公司和組織,他們也通過分享他們的模型回饋社區:

使用 Hugging Face 的公司 🤗 Transformers 庫提供了創建和使用這些共享模型的功能。模型中心(hub)包含數千個任何人都可以下載和使用的預訓練模型。您還可以將自己的模型上傳到 Hub!

⚠️ Hugging Face Hub 不限於 Transformer 模型。任何人都可以分享他們想要的任何類型的模型或數據集!創建一個 Huggingface.co 帳戶(https://huggingface.co/join)以使用所有可用功能!

在深入研究 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選擇一個特定的預訓練模型,該模型已針對英語情感分析進行了微調。創建分類器對象時,將下載並緩存模型。如果您重新運行該命令,則將使用緩存的模型,無需再次下載模型。

將一些文本傳遞到pipeline時涉及三個主要步驟:

  1. 文本被預處理為模型可以理解的格式。
  2. 預處理的輸入被傳遞給模型。
  3. 模型處理後輸出最終人類可以理解的結果。

目前可用的一些pipeline是:

  • 特徵提取(獲取文本的向量表示)
  • 填充空缺
  • ner(命名實體識別)
  • 問答
  • 情感分析
  • 文本摘要
  • 文本生成
  • 翻譯
  • 零樣本分類

讓我們來看看其中的一些吧!

零樣本分類

我們將首先處理一項非常具挑戰性的任務,我們需要對尚未標記的文本進行分類。這是實際項目中的常見場景,因為注釋文本通常很耗時並且需要領域專業知識。對於這項任務zero-shot-classificationpipeline非常強大:它允許您直接指定用於分類的標籤,因此您不必依賴預訓練模型的標籤。下面的模型展示瞭如何使用這兩個標籤將句子分類為正面或負面——但也可以使用您喜歡的任何其他標籤集對文本進行分類。

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中使用 - 例如,文本生成。轉到模型中心(hub)並單擊左側的相應標籤將會只顯示該任務支持的模型。例如這樣

讓我們試試 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)甚至包含支持多種語言的多語言模型。

通過單擊選擇模型後,您會看到有一個小組件,可讓您直接在線試用。通過這種方式,您可以在下載之前快速測試模型的功能。

✏️**快來試試吧!**使用標籤篩選查找另一種語言的文本生成模型。使用小組件測試並在pipeline中使用它!

推理 API

所有模型都可以使用 Inference API 直接通過瀏覽器進行測試,該 API 可在 Hugging Face 網站上找到。通過輸入自定義文本並觀察模型的輸出,您可以直接在此頁面上使用模型。

小組件形式的推理 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 >詞,它通常被稱為掩碼標記。其他掩碼填充模型可能有不同的掩碼標記,因此在探索其他模型時要驗證正確的掩碼字是什麼。檢查它的一種方法是查看小組件中使用的掩碼。

✏️**快來試試吧!**在 Hub 上搜索基於 bert 的模型並在推理 API 小組件中找到它的掩碼。這個模型對上面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),而布魯克林是一個位置 (LOC)。

我們在pipeline創建函數中傳遞選項 grouped_entities=True 以告訴pipeline將對應於同一實體的句子部分重新組合在一起:這裡模型正確地將「Hugging」和「Face」分組為一個組織,即使名稱由多個詞組成。事實上,正如我們即將在下一章看到的,預處理甚至會將一些單詞分成更小的部分。例如,Sylvain 分割為了四部分:S、##yl、##va##in。在後處理步驟中,pipeline成功地重新組合了這些部分。

✏️**快來試試吧!**在模型中心(hub)搜索能夠用英語進行詞性標注(通常縮寫為 POS)的模型。這個模型對上面例子中的句子預測了什麼?

問答系統

問答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'}
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_lengthmin_length

翻譯

對於翻譯,如果您在任務名稱中提供語言對(例如「translation_en_to_fr」),則可以使用默認模型,但最簡單的方法是在模型中心(hub)選擇要使用的模型。在這裡,我們將嘗試從法語翻譯成英語:

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_lengthmin_length

✏️快來試試吧!搜索其他語言的翻譯模型,嘗試將前一句翻譯成幾種不同的語言。

到目前為止顯示的pipeline主要用於演示目的。它們是為特定任務而編程的,不能對他們進行自定義的修改。在下一章中,您將瞭解 pipeline() 函數內部的內容以及如何進行自定義的修改。