見出し画像

Huggingface Transformers 入門 (1) - 事始め

「Huggingface Transformers」の使い方をまとめました。

・Python 3.6
・PyTorch 1.6 
・Huggingface Transformers 3.1.0

1. Huggingface Transformers

Huggingface ransformers」(🤗Transformers)は、「自然言語理解」と「自然言語生成」の最先端の汎用アーキテクチャ(BERT、GPT-2など)と何千もの事前学習済みモデルを提供するライブラリです。

Huggingface Transformersのドキュメント

2. Transformer

Transformer」は、2017年にGoogleが発表した深層学習モデルで、2021年現在、自然言語処理に利用する深層学習モデルのデファクトスタンダードになっています。

「Transformer」は、過去に自然言語処理分野で多く使われていた「RNN」(Recurrent Neural Network)や「CNN」(Convolutional Neural Network)を「Self-Attention Layer」に入れ替えたモデルで、発表以来、多くの自然言語処理モデルが「Transformer」で再構築され、過去を上回る結果を上げました。

2018年にGoogleが発表した「BERT」は教師なしで学習した「Transformer」、2019年にOpenAIが発表した「GPT-2」は「Masked Self-Attention Layer」を使用した「BERT」になります。

3. インストール

「Huggingface Transformers」は、「Python 3.6」以降、「PyTorch 1.0」以降、「TensorFlow 2.0」で動作します。pipでインストールすることもできますが、サンプルを試す場合はソースからインストールする必要があります。

◎ pipでインストール

$ pip install transformers

◎ ソースからインストール

$ git clone https://github.com/huggingface/transformers
$ cd transformers
$ pip install .

4. オンラインデモ

◎ モデルハブ
推論APIを試すことができます。

Masked word completion with BERT
NER with Electra
Text generation with GPT-2
NLI with RoBERTa
Summarization with BART
Question answering with DistilBERT
Translation with T5

Write With Transformer
公式のデモになります。

5. サンプル

サンプルを 試すには、「Huggingface Transformers」をソースからインストールする必要があります。

・language-modeling(言語モデル)
・text-classification(テキスト分類)
・token-classification(固有表現抽出)
・multiple-choice
・question-answering(質問応答)
・text-generation(テキスト生成)
・distillation
・summarization(要約)
・translation(翻訳)
・bertology
・adversarial

詳しくは、「README」を参照してください。

6. モデルアーキテクチャ

「Huggingface Transformers」が提供するモデルアーキテクチャは、次のとおりです。

(1) ALBERT (Google Research and the Toyota Technological Institute at Chicago) - 2019/9
(2) BART (Facebook) - 2019/10
(3) BARThez (École polytechnique) -2020/10
(4) BERT (Google) - 2018/11
(5) BERT For Sequence Generation (Google) - 2019/7
(6) Blenderbot (Facebook) - 2020/4
(7) BlenderbotSmall (Facebook) - 2020/4
(8) CamemBERT (Inria/Facebook/Sorbonne) - 2019/11
(9) CTRL (Salesforce) - 2019/9
(10) DeBERTa (Microsoft Research) - 2020/6
(11) DialoGPT (Microsoft Research) - 2019/11
(12) DistilBERT (HuggingFace) - 2019/10
(13) DPR (Facebook) - 2020/4
(14) ELECTRA (Google Research/Stanford University) - 2020/3
(15) FlauBERT (CNRS) - 2019/12
(16) Funnel Transformer (CMU/Google Brain) - 2020/6
(17) GPT (OpenAI) - 2018/6
(18) GPT-2 (OpenAI) - 2019/2
(19) LayoutLM (Microsoft Research Asia) - 2019/12
(20) LED (AllenAI) - 2020/4
(21) Longformer (AllenAI) - 2020/4
(22) LXMERT (UNC Chapel Hill) - 2019/8
(23) MarianMT
(24) MBart (Facebook) - 2020/1
(25) MPNet (Microsoft Research) - 2020/4
(26) MT5 (Google AI) - 2020/10
(27) Pegasus (Google) - 2019/12
(28) ProphetNet (Microsoft Research) -2020/1
(29) Reformer (Google Research) - 2020/2
(30) RoBERTa (Facebook) - 2019/6
(31) SqueezeBert - 2020/1
(32) T5 (Google AI) - 2019/10
(33) TAPAS (Google AI) - 2020/4
(34) Transformer-XL (Google/CMU)  - 2019/1
(35) XLM (Facebook) - 2019/1
(36) XLM-ProphetNet (Microsoft Research) - 2020/1
(37) XLM-RoBERTa (Facebook AI) - 2019/11
(38) XLNet (Google/CMU) - 2019/6

他に、コミュニティによって提供されたモデルもあります。

7. 事前学習済みモデル

「Huggingface Transformers」が提供する事前学習済みモデルは、以下で確認できます。

Pretrained models

8. 自然言語処理のタスク

利用可能な自然言語処理のタスクは、次のとおりです。

・テキスト分類 (カテゴライズ・感情解析)
・質問応答
・言語モデル
・テキスト生成
・要約
・固有表現抽出
・翻訳

9. パイプラインとトークナイザー

「Huggingface Transformers」は、推論を行うために、2つの手法が提供されています。

パイプライン : 簡単に使える(2行で実装可能)抽象化モデルを提供。
トークナイザー : 直接モデルを操作して完全な推論を提供。

パイプラインで利用可能なタスクは、次のとおりです。

・feature-extraction : テキストを与えると、特徴を表すベクトルを返す。
・sentiment-analysis : テキストを与えると、感情分析の結果を返す。
・ner
: テキストを与えると、固有表現抽出の結果を返す。
・question-answering : 質問と記事を与えると、回答を返す。
・fill-mask : 空欄ありのテキストを与えると、空欄に当てはまる単語を返す。
・summarization : 入力したテキストを要約して返す。
・translation_xx_to_yy : テキストを与えると、翻訳して返す。
・text-generation : テキストを与えると、それに続くテキストを返す。
・conversation : テキストを与えると、それに続く会話を返す。

10. テキスト分類

テキスト分類」は、テキストをクラス分類するタスクです。データセットの例は、「GLUE」です。ファインチューニングしたい場合は、「run_glue.py」または「run_tf_glue.py」を利用できます。

以下は、パイプラインで「テキスト分類」を行う例です。

from transformers import pipeline

# 感情分析
nlp = pipeline("sentiment-analysis")

# 推論
print(nlp("I love you")) # ポジティブ
print(nlp("I hate you")) # ネガティブ

結果は、次のとおりです。

[{'label': 'POSITIVE', 'score': 0.9998656511306763}]
[{'label': 'NEGATIVE', 'score': 0.9991129040718079}]

以下は、トークナイザーで「テキスト分類」を行う例です。

from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch

# トークナイザーとモデルの準備
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased-finetuned-mrpc")
model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased-finetuned-mrpc")

# クラス
classes = ["not paraphrase", "is paraphrase"]
# 言い換えでない
# 言い換えである

# テキスト
sequence_0 = "The company HuggingFace is based in New York City"
sequence_1 = "Apples are especially bad for your health"
sequence_2 = "HuggingFace's headquarters are situated in Manhattan"
# HuggingFace社はニューヨークに拠点を置く
# リンゴは特に健康に悪い
# HuggingFaceの本社はマンハッタンにある

# 前処理
paraphrase = tokenizer.encode_plus(sequence_0, sequence_2, return_tensors="pt")
not_paraphrase = tokenizer.encode_plus(sequence_0, sequence_1, return_tensors="pt")

# 推論
paraphrase_classification_logits = model(**paraphrase)[0]
not_paraphrase_classification_logits = model(**not_paraphrase)[0]

# 結果
paraphrase_results = torch.softmax(paraphrase_classification_logits, dim=1).tolist()[0]
not_paraphrase_results = torch.softmax(not_paraphrase_classification_logits, dim=1).tolist()[0]

# 言い換えである
print("Should be paraphrase")
for i in range(len(classes)):
  print(f"{classes[i]}: {round(paraphrase_results[i] * 100)}%")

# 言い換えでない
print("\nShould not be paraphrase")
for i in range(len(classes)):
    print(f"{classes[i]}: {round(not_paraphrase_results[i] * 100)}%")

結果は、次のとおりです。

Should be paraphrase
not paraphrase: 10%
is paraphrase: 90%

Should not be paraphrase
not paraphrase: 94%
is paraphrase: 6%

11. 質問応答

質問応答」は、与えられたテキストから質問の回答を抽出するタスクです。データセットの例は、「SQuAD」です。ファインチューニングしたい場合は「run_squad.py」を利用できます。

以下は、パイプラインで「質問応答」を行う例です。

from transformers import pipeline

# 質疑応答
nlp = pipeline("question-answering")

# テキスト
context = r"""
Extractive Question Answering is the task of extracting an answer from a text given a question. An example of a
question answering dataset is the SQuAD dataset, which is entirely based on that task. If you would like to fine-tune
a model on a SQuAD task, you may leverage the `run_squad.py`.
"""
# 質問回答とは、与えられたtテキストから質問の回答を抽出するタスクです。
# データセットの例は、「SQuAD」です。
# ファインチューニングしたい場合は「run_squad.py」を利用できます。

# 推論
print(nlp(question="What is extractive question answering?", context=context))
print(nlp(question="What is a good example of a question answering dataset?", context=context))
# 質問回答とは?
# データセットの例は?

結果は、次のとおりです。

{'score': 0.6222445964813232, 'start': 34, 'end': 96, 'answer': 'the task of extracting an answer from a text given a question.'}
{'score': 0.5115318894386292, 'start': 147, 'end': 161, 'answer': 'SQuAD dataset,'}
# 質問の回答を抽出するタスク
# SQuADデータベース

以下は、トークナイザーで「質問応答」を行う例です。

from transformers import AutoTokenizer, AutoModelForQuestionAnswering
import torch

# トークナイザーとモデルの準備
tokenizer = AutoTokenizer.from_pretrained("bert-large-uncased-whole-word-masking-finetuned-squad")
model = AutoModelForQuestionAnswering.from_pretrained("bert-large-uncased-whole-word-masking-finetuned-squad")

# テキスト
text = r"""
🤗 Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides general-purpose
architectures (BERT, GPT-2, RoBERTa, XLM, DistilBert, XLNet…) for Natural Language Understanding (NLU) and Natural
Language Generation (NLG) with over 32+ pretrained models in 100+ languages and deep interoperability between
TensorFlow 2.0 and PyTorch.
"""
# 🤗 Transformers(旧称:pytorch-transformers、pytorch-pretrained-bert)は、
# 自然言語理解(NLU)と自然言語生成(NLG)のための汎用アーキテクチャ
# (BERT、GPT-2、RoBERTa、XLM、DistilBert、XLNet...)を100以上の言語で
# 32以上の事前学習モデルと
# TensorFlow 2.0とPyTorchの間の相互運用性を提供します。

# 質問
questions = [
    "How many pretrained models are available in Transformers?",
    "What does Transformers provide?",
    "Transformers provides interoperability between which frameworks?",
]
# Transformersには何種類の事前学習モデルがあるのか?
# Transformersは何を提供しているのか?
# Transformersはどのフレームワーク間の相互運用性を提供していますか?

for question in questions:
    # 前処理
    inputs = tokenizer.encode_plus(question, text, add_special_tokens=True, return_tensors="pt")
    input_ids = inputs["input_ids"].tolist()[0]

    # 推論
    text_tokens = tokenizer.convert_ids_to_tokens(input_ids)
    answer_start_scores, answer_end_scores = model(**inputs)

    # 可能性の高い回答の取得
    answer_start = torch.argmax(answer_start_scores)  
    answer_end = torch.argmax(answer_end_scores) + 1 
    answer = tokenizer.convert_tokens_to_string(tokenizer.convert_ids_to_tokens(input_ids[answer_start:answer_end]))

    # 出力
    print(f"Question: {question}")
    print(f"Answer: {answer}\n")

結果は、次のとおりです。

Question: How many pretrained models are available in Transformers?
Answer: over 32 +
# 32以上

Question: What does Transformers provide?
Answer: general - purpose architectures
# 汎用アーキテクチャ

Question: Transformers provides interoperability between which frameworks?
Answer: tensorflow 2 . 0 and pytorch
# TensorFlow 2.0とPyTorch

12. 言語モデル

言語モデル」は、テキストの自然な単語の並びを学習するするタスクです。一般的なTransformerモデルは、言語モデルで事前学習を行います。「BERT」では「Masked Language Modeling」使用し、「GPT-2」では「Causal Language Modeling」を使用します。

◎ Masked Language Modeling
テキスト内のマスクしたトークンを予測するタスクです。モデルは、右側のトークンと左型のトークンの両方に対応できます。

以下は、パイプラインで「Masked Language Modeling」を行う例です。

from transformers import pipeline

# Masked Lanuage Modeling
nlp = pipeline("fill-mask")

# 推論
print(nlp(f"HuggingFace is creating a {nlp.tokenizer.mask_token} that the community uses to solve NLP tasks."))
# HuggingFaceは、コミュニティがNLPのタスクを解くために使う{nlp.tokenizer.mask_token}を作成しています。

結果は、次のとおりです。

[
    {'sequence': '<s>HuggingFace is creating a tool that the community uses to solve NLP tasks.</s>', 'score': 0.17927460372447968, 'token': 3944, 'token_str': 'Ġtool'},
    {'sequence': '<s>HuggingFace is creating a framework that the community uses to solve NLP tasks.</s>', 'score': 0.1134939044713974, 'token': 7208, 'token_str': 'Ġframework'},
    {'sequence': '<s>HuggingFace is creating a library that the community uses to solve NLP tasks.</s>', 'score': 0.05243545398116112, 'token': 5560, 'token_str': 'Ġlibrary'},
    {'sequence': '<s>HuggingFace is creating a database that the community uses to solve NLP tasks.</s>', 'score': 0.03493543714284897, 'token': 8503, 'token_str': 'Ġdatabase'},
    {'sequence': '<s>HuggingFace is creating a prototype that the community uses to solve NLP tasks.</s>', 'score': 0.02860247902572155, 'token': 17715, 'token_str': 'Ġprototype'}
]
# HuggingFaceはコミュニティがNLPタスクを解決するために使用する[ツール]を作成しています。
# HuggingFaceはコミュニティがNLPタスクを解決するために使用する[フレームワーク]を作成しています。
# HuggingFaceはコミュニティがNLPタスクを解決するために使用する[ライブラリ]を作成しています。
# HuggingFaceはコミュニティがNLPタスクを解決するために使用する[データベース]を作成しています。
# HuggingFaceはコミュニティがNLPタスクを解決するために使用する[プロトタイプ]を作成しています。

以下は、トークナイザーで「Masked Language Modeling」を行う例です。 

from transformers import AutoModelWithLMHead, AutoTokenizer
import torch

# トークナイザとモデルの準備
tokenizer = AutoTokenizer.from_pretrained("distilbert-base-cased")
model = AutoModelWithLMHead.from_pretrained("distilbert-base-cased")

# テキスト
sequence = f"Distilled models are smaller than the models they mimic. Using them instead of the large versions would help {tokenizer.mask_token} our carbon footprint."
# 蒸留されたモデルは、模倣するモデルよりも小さくなります。
# 大型のモデルの代わりに使用することで、二酸化炭素排出量を{tokenizer.mask_token}ことができます。

# 前処理
input = tokenizer.encode(sequence, return_tensors="pt")
mask_token_index = torch.where(input == tokenizer.mask_token_id)[1]

# 推論
token_logits = model(input)[0]
mask_token_logits = token_logits[0, mask_token_index, :]

# 上位5トークンの出力
top_5_tokens = torch.topk(mask_token_logits, 5, dim=1).indices[0].tolist()
for token in top_5_tokens:
    print(sequence.replace(tokenizer.mask_token, tokenizer.decode([token])))

結果は、次のとおりです。

Distilled models are smaller than the models they mimic. Using them instead of the large versions would help reduce our carbon footprint.
Distilled models are smaller than the models they mimic. Using them instead of the large versions would help increase our carbon footprint.
Distilled models are smaller than the models they mimic. Using them instead of the large versions would help decrease our carbon footprint.
Distilled models are smaller than the models they mimic. Using them instead of the large versions would help offset our carbon footprint.
Distilled models are smaller than the models they mimic. Using them instead of the large versions would help improve our carbon footprint.
# 大型モデルの代わりに使用することで、二酸化炭素排出量を[削る]ことができます。
# 大型モデルの代わりに使用することで、二酸化炭素排出量を[増加する]ことができます。
# 大型モデルの代わりに使用することで、二酸化炭素排出量を[削減する]ことができます。
# 大型モデルの代わりに使用することで、二酸化炭素排出量を[相殺する]ことができます。
# 大型モデルの代わりに使用することで、二酸化炭素排出量を[改善する]ことができます。

◎ Causal Language Modeling
一連のトークンに続くトークンを予測するタスクです。モデル、左側のトークンのみに対応します。

以下は、トークナイザーで「Causal Language Modeling」を行う例です。 

from transformers import AutoModelWithLMHead, AutoTokenizer, top_k_top_p_filtering
import torch
from torch.nn import functional as F

# トークナーザーとモデルの準備
tokenizer = AutoTokenizer.from_pretrained("gpt2")
model = AutoModelWithLMHead.from_pretrained("gpt2")

# テキスト
sequence = f"Hugging Face is based in DUMBO, New York City, and "
# Hugging FaceはニューヨークのDUMBOを拠点にしており 

# 前処理
input_ids = tokenizer.encode(sequence, return_tensors="pt")

# 推論 (最後の隠れた状態のロジットを取得)
next_token_logits = model(input_ids)[0][:, -1, :]

# フィルタ
filtered_next_token_logits = top_k_top_p_filtering(next_token_logits, top_k=50, top_p=1.0)

# サンプル
probs = F.softmax(filtered_next_token_logits, dim=-1)
next_token = torch.multinomial(probs, num_samples=1)
generated = torch.cat([input_ids, next_token], dim=-1)

# デコードと出力
resulting_string = tokenizer.decode(generated.tolist()[0])
print(resulting_string)

結果は、次のとおりです。

Hugging Face is based in DUMBO, New York City, and has

13. テキスト生成

テキスト生成」は、与えられたテキストに続くテキストを生成するタスクです。

以下は、パイプラインで「テキスト生成」を行う例です。

from transformers import pipeline

# テキスト生成
text_generator = pipeline("text-generation")

# 推論
print(text_generator("As far as I am concerned, I will", max_length=50))

結果は、次のとおりです。

[{'generated_text': 'As far as I am concerned, I will give my time to any and all organizations which will share these resources and which might be helpful to me.\n\n1) People: Helping the Children\n\nThis is something which, on its own'}]

以下は、トークナイザーで「テキスト生成」を行う例です。

from transformers import AutoModelWithLMHead, AutoTokenizer

# モデルとトークナイザー
model = AutoModelWithLMHead.from_pretrained("xlnet-base-cased")
tokenizer = AutoTokenizer.from_pretrained("xlnet-base-cased")

# テキストをパディングすることで XLNetの短いプロンプトを補助 
# https://github.com/rusiaaman/XLNet-gen#methodology
PADDING_TEXT = """In 1991, the remains of Russian Tsar Nicholas II and his family
(except for Alexei and Maria) are discovered.
The voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the
remainder of the story. 1883 Western Siberia,
a young Grigori Rasputin is asked by his father and a group of men to perform magic.
Rasputin has a vision and denounces one of the men as a horse thief. Although his
father initially slaps him for making such an accusation, Rasputin watches as the
man is chased outside and beaten. Twenty years later, Rasputin sees a vision of
the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous,
with people, even a bishop, begging for his blessing. <eod> </s> <eos>"""

# プロンプト
prompt = "Today the weather is really nice and I am planning on "

# 前処理
inputs = tokenizer.encode(PADDING_TEXT + prompt, add_special_tokens=False, return_tensors="pt")

# 推論
prompt_length = len(tokenizer.decode(inputs[0], skip_special_tokens=True, clean_up_tokenization_spaces=True))
outputs = model.generate(inputs, max_length=250, do_sample=True, top_p=0.95, top_k=60)
generated = prompt + tokenizer.decode(outputs[0])[prompt_length:]

# 出力
print(generated)

現在、「テキスト生成」は、PyTorchの「GPT-2」「OpenAi-GPT」「CTRL」「XLNet」「Transfo-XL」「Reformer」で、またTensorflowのほとんどのモデルでも可能です。上記の例に見られるように、「XLNet」「Transfo-xl」は、うまく機能するためにパディングが必要になることがよくあります。「GPT-2」は、「Causal Language Modeling」目的の何百万ものWebページで訓練されているため、オープンエンドのテキスト生成に適しています。

「テキスト生成」にデコード戦略を適用する方法の詳細については、こちらのブログ投稿も参照してください。

14. 固有表現抽出

固有表現抽出」は、トークンをクラス分類するタスクです。たとえば、トークンを「個人」「組織」「場所」として識別します。固有表現抽出のデータセットの例は、「CoNLL-2003」です。ファインチューニングしたい場合は、「ner/run_ner.py」「ner/run_pl_ner.py」「ner/run_tf_ner.py」を利用できます。

以下は、トークンを9つのクラスに分類しようとする例です。

・O : 固有表現外
・B-MIS : 別のその他の直後のその他の始まり
・I-MIS : その他
・B-PER : 別の人物名の直後の人物名の始まり
・I-PER : 人物名
・B-ORG : 別の組織の直後の組織の始まり
・I-ORG : 組織
・B-LOC : 別の場所の直後の場所の始まり
・I-LOC : 場所

以下は、パイプラインで「固有表現抽出」を行う例です。

from transformers import pipeline

# 固有表現抽出
nlp = pipeline("ner")

# テキスト
sequence = "Hugging Face Inc. is a company based in New York City. Its headquarters are in DUMBO, therefore very" \
         "close to the Manhattan Bridge which is visible from the window."

# 出力
print(nlp(sequence))

結果は、次のとおりです。

[
    {'word': 'Hu', 'score': 0.9995632767677307, 'entity': 'I-ORG'},
    {'word': '##gging', 'score': 0.9915938973426819, 'entity': 'I-ORG'},
    {'word': 'Face', 'score': 0.9982671737670898, 'entity': 'I-ORG'},
    {'word': 'Inc', 'score': 0.9994403719902039, 'entity': 'I-ORG'},
    {'word': 'New', 'score': 0.9994346499443054, 'entity': 'I-LOC'},
    {'word': 'York', 'score': 0.9993270635604858, 'entity': 'I-LOC'},
    {'word': 'City', 'score': 0.9993864893913269, 'entity': 'I-LOC'},
    {'word': 'D', 'score': 0.9825621843338013, 'entity': 'I-LOC'},
    {'word': '##UM', 'score': 0.936983048915863, 'entity': 'I-LOC'},
    {'word': '##BO', 'score': 0.8987102508544922, 'entity': 'I-LOC'},
    {'word': 'Manhattan', 'score': 0.9758241176605225, 'entity': 'I-LOC'},
    {'word': 'Bridge', 'score': 0.990249514579773, 'entity': 'I-LOC'}
]

「Hugging Face」が組織として識別され、「New York City」「DUMBO」「Manhattan Bridge」が場所として識別されています。

以下は、トークナイザーで「固有表現抽出」を行う例です。

from transformers import AutoModelForTokenClassification, AutoTokenizer
import torch

# モデルとトークナイザーの準備
model = AutoModelForTokenClassification.from_pretrained("dbmdz/bert-large-cased-finetuned-conll03-english")
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")

# クラス一覧
label_list = [
   "O",      
   "B-MISC",  
   "I-MISC", 
   "B-PER", 
   "I-PER",  
   "B-ORG", 
   "I-ORG", 
   "B-LOC", 
   "I-LOC" 
]

# テキスト
sequence = "Hugging Face Inc. is a company based in New York City. Its headquarters are in DUMBO, therefore very" \
          "close to the Manhattan Bridge."

# 前処理 (スペシャルトークンでトークンを取得)
tokens = tokenizer.tokenize(tokenizer.decode(tokenizer.encode(sequence)))
inputs = tokenizer.encode(sequence, return_tensors="pt")

# 推論
outputs = model(inputs)[0]
predictions = torch.argmax(outputs, dim=2)

# 出力
print([(token, label_list[prediction]) for token, prediction in zip(tokens, predictions[0].tolist())])

結果は、次のとおりです。

[('[CLS]', 'O'), ('Hu', 'I-ORG'), ('##gging', 'I-ORG'), ('Face', 'I-ORG'), ('Inc', 'I-ORG'), ('.', 'O'), ('is', 'O'), ('a', 'O'), ('company', 'O'), ('based', 'O'), ('in', 'O'), ('New', 'I-LOC'), ('York', 'I-LOC'), ('City', 'I-LOC'), ('.', 'O'), ('Its', 'O'), ('headquarters', 'O'), ('are', 'O'), ('in', 'O'), ('D', 'I-LOC'), ('##UM', 'I-LOC'), ('##BO', 'I-LOC'), (',', 'O'), ('therefore', 'O'), ('very', 'O'), ('##c', 'O'), ('##lose', 'O'), ('to', 'O'), ('the', 'O'), ('Manhattan', 'I-LOC'), ('Bridge', 'I-LOC'), ('.', 'O'), ('[SEP]', 'O')]

15. 要約

要約」は、テキストをより短いテキストに要約するタスクです。データセットの例は、「CNN/Daily Mail」です。ファインチューニングしたい場合は、「examples/summarization/bart/run_train.sh」を利用できます。

以下は、パイプラインで「要約」を行う例です。

from transformers import pipeline

# 要約
summarizer = pipeline("summarization")

# テキスト
ARTICLE = """ New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County, New York.
A year later, she got married again in Westchester County, but to a different man and without divorcing her first husband.
Only 18 days after that marriage, she got hitched yet again. Then, Barrientos declared "I do" five more times, sometimes only within two weeks of each other.
In 2010, she married once more, this time in the Bronx. In an application for a marriage license, she stated it was her "first and only" marriage.
Barrientos, now 39, is facing two criminal counts of "offering a false instrument for filing in the first degree," referring to her false statements on the
2010 marriage license application, according to court documents.
Prosecutors said the marriages were part of an immigration scam.
On Friday, she pleaded not guilty at State Supreme Court in the Bronx, according to her attorney, Christopher Wright, who declined to comment further.
After leaving court, Barrientos was arrested and charged with theft of service and criminal trespass for allegedly sneaking into the New York subway through an emergency exit, said Detective
Annette Markowski, a police spokeswoman. In total, Barrientos has been married 10 times, with nine of her marriages occurring between 1999 and 2002.
All occurred either in Westchester County, Long Island, New Jersey or the Bronx. She is believed to still be married to four men, and at one time, she was married to eight men at once, prosecutors say.
Prosecutors said the immigration scam involved some of her husbands, who filed for permanent residence status shortly after the marriages.
Any divorces happened only after such filings were approved. It was unclear whether any of the men will be prosecuted.
The case was referred to the Bronx District Attorney\'s Office by Immigration and Customs Enforcement and the Department of Homeland Security\'s
Investigation Division. Seven of the men are from so-called "red-flagged" countries, including Egypt, Turkey, Georgia, Pakistan and Mali.
Her eighth husband, Rashid Rajput, was deported in 2006 to his native Pakistan after an investigation by the Joint Terrorism Task Force.
If convicted, Barrientos faces up to four years in prison.  Her next court appearance is scheduled for May 18.
"""

# 推論
print(summarizer(ARTICLE, max_length=130, min_length=30))

結果は、次のとおりです。

Liana Barrientos has been married 10 times, sometimes within two weeks of each other. Prosecutors say the marriages were part of an immigration scam. She pleaded not guilty at State Supreme Court in the Bronx on Friday.

16. 翻訳

翻訳」は、テキストをある言語から別の言語に翻訳するタスクです。データセットの例としては、「WMT」(英語→ドイツ語)があります。

以下は、パイプラインで「翻訳」を行う例です。

from transformers import pipeline

# 翻訳
translator = pipeline("translation_en_to_de")

# 推論
print(translator("Hugging Face is a technology company based in New York and Paris", max_length=40))

結果は、次のとおりです。

Hugging Face ist ein Technologieunternehmen mit Sitz in New York und Paris.

以下は、トークナイザーで「翻訳」を行う例です。

from transformers import AutoModelWithLMHead, AutoTokenizer

# モデルとトークナイザー
model = AutoModelWithLMHead.from_pretrained("t5-base")
tokenizer = AutoTokenizer.from_pretrained("t5-base")

# 前処理
inputs = tokenizer.encode("translate English to German: Hugging Face is a technology company based in New York and Paris", return_tensors="pt")

# 推論
outputs = model.generate(inputs, max_length=40, num_beams=4, early_stopping=True)

# 出力
print(outputs)

次回



この記事が気に入ったらサポートをしてみませんか?