Traffine I/O

日本語

2023-02-03

Hugging Face Transformers:Pipeline

Hugging Face Transformers Pipeline

Hugging face TransformersのPipelineを使うと、わずか数行のコードでNLPのタスクを実行することができます。

Pipelineでは、生のテキストデータを受け取ったときに内部的に以下の3つのステップが実行されます。

  1. Tokenizer: モデルへの入力形式に変換するための前処理が実行される
  2. Model: 変換された入力テキストがモデルへ入力される
  3. Post Processing: モデルの推論結果が扱いやすい形に後処理されて出力される

Pipeline flow
Behind the pipeline

Pipeline の使い方

以下のコマンドでHugging Face Transformersをインストールします。

$ pip install transformers

pipeline("question-answering")のように、行いたいタスク名をpipelineに指定します。タスクは例えば以下のようなものがあります。

  • feature-extraction (get the vector representation of a text)
  • fill-mask
  • ner (named entity recognition)
  • question-answering
  • sentiment-analysis
  • summarization
  • text-generation
  • translation
  • zero-shot-classification

詳細は以下のリンクから確認することができます。

https://huggingface.co/docs/transformers/main_classes/pipelines

例えば、テキスト分類を行いたいときは以下のように記述します。

from transformers import pipeline

pipe = pipeline("text-classification")
pipe("This restaurant is awesome")

以下の結果が返ってきます。

[{'label': 'POSITIVE', 'score': 0.9998743534088135}]

Hub から特定のモデルを使用したい場合、Hub上のモデルがすでにそのタスクを定義しているときに限り、タスク名を省略することができます。

from transformers import pipeline

pipe = pipeline(model="roberta-large-mnli")
pipe("This restaurant is awesome")

>> [{'label': 'NEUTRAL', 'score': 0.7313136458396912}]

入力にリストを渡すことも可能です。

from transformers import pipeline

pipe = pipeline("text-classification")
pipe(["This restaurant is awesome", "This restaurant is awful"])

>> [{'label': 'POSITIVE', 'score': 0.9998743534088135},
>>  {'label': 'NEGATIVE', 'score': 0.9996669292449951}]

カスタムのPipelineを定義することも可能です。

class MyPipeline(TextClassificationPipeline):
    def postprocess():
        # Your code goes here
        scores = scores * 100
        # And here

my_pipeline = MyPipeline(model=model, tokenizer=tokenizer, ...)
# or if you use *pipeline* function, then:
my_pipeline = pipeline(model="xxxx", pipeline_class=MyPipeline)

Pipeline の例

以下のNLPタスクの例を紹介します。

  • Zero-shot classification
  • Text generation
  • Mask filling

Zero-shot classification

Zero-shot classificationは、ラベリングされたテキストを用意することなく、分類したいラベルをPipelineに直接与えるだけで、そのラベルに対する推論結果を返すというタスクです。テキストにアノテーションを付けるのは通常時間がかかり、専門知識が必要になります。このような場合にZero-shot classificationは有効です。

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.8445988297462463, 0.11197440326213837, 0.04342682659626007]}

Text generation

Text generationは、プロンプトを与えるとモデルが残りのテキストを生成してそれをオートコンプリートするタスクです。

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'}]

Hubから特定のモデルを選択することも可能です。

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'}]

Mask filling

Mask fillingは、与えられたテキストの空白を埋めるタスクです。

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'}]

参考

https://huggingface.co/course/chapter1/3
https://huggingface.co/course/chapter2/2?fw=pt
https://huggingface.co/docs/transformers/main_classes/pipelines
https://huggingface.co/docs/transformers/quicktour#use-another-model-and-tokenizer-in-the-pipeline

Ryusei Kakujo

researchgatelinkedingithub

Focusing on data science for mobility

Bench Press 100kg!