Transformers documentation

選択問題

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

選択問題

選択問題タスクは、質問応答に似ていますが、コンテキストとともに複数の候補解答が提供され、モデルは正しい解答を選択するように学習されます。

このガイドでは、次の方法について説明します:

  1. SWAG データセットのregular設定で、複数の選択肢と一部のコンテキストが与えられたときに最良の答えを選択するよう、BERTをファインチューニングします。
  2. ファインチューニングしたモデルを推論に使用します。

開始前に、必要なライブラリがすべてインストールされていることを確認してください。

pip install transformers datasets evaluate

Hugging Face アカウントにログインして、モデルをアップロードし、コミュニティと共有できるようにすることを推奨します。プロンプトが表示されたら、ログイン用のトークンを入力してください:

>>> from huggingface_hub import notebook_login

>>> notebook_login()

SWAG データセットを読み込む

🤗 Datasets ライブラリから SWAG データセットのregular設定を読み込むことから始めます:

>>> from datasets import load_dataset

>>> swag = load_dataset("allenai/swag", "regular")

次に、例を見てみましょう。

>>> swag["train"][0]
{'ending0': 'passes by walking down the street playing their instruments.',
 'ending1': 'has heard approaching them.',
 'ending2': "arrives and they're outside dancing and asleep.",
 'ending3': 'turns the lead singer watches the performance.',
 'fold-ind': '3416',
 'gold-source': 'gold',
 'label': 0,
 'sent1': 'Members of the procession walk down the street holding small horn brass instruments.',
 'sent2': 'A drum line',
 'startphrase': 'Members of the procession walk down the street holding small horn brass instruments. A drum line',
 'video-id': 'anetv_jkn6uvmqwh4'}

ここには多くのフィールドがあるように見えますが、実際にはかなりシンプルです:

  • sent1 と sent2: これらのフィールドは文の始まりを示しており、これらを組み合わせると startphrase フィールドが得られます。
  • ending: 文の終わりの可能性を示唆しますが、正しいものは1つだけです。
  • label: 正しい文の終わりを識別します。

前処理

次のステップは、BERTのトークナイザーを読み込み、文の開始部分と4つの候補の結尾を処理することです。

>>> from transformers import AutoTokenizer

>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")

作成する前処理関数は、次のことを必要とします。

  1. sent1 フィールドを4つ複製し、それぞれを sent2 と結合して、文の始まりを再現します。
  2. sent2を、4つの文の終わりの候補それぞれと組み合わせます。
  3. これら2つのリストをフラット化してトークナイズし、その後、各サンプルに対応するinput_ids、attention_mask、labelsフィールドが得られるようにアンフラット化します。
>>> ending_names = ["ending0", "ending1", "ending2", "ending3"]


>>> def preprocess_function(examples):
...     first_sentences = [[context] * 4 for context in examples["sent1"]]
...     question_headers = examples["sent2"]
...     second_sentences = [
...         [f"{header} {examples[end][i]}" for end in ending_names] for i, header in enumerate(question_headers)
...     ]

...     first_sentences = sum(first_sentences, [])
...     second_sentences = sum(second_sentences, [])

...     tokenized_examples = tokenizer(first_sentences, second_sentences, truncation=True)
...     return {k: [v[i : i + 4] for i in range(0, len(v), 4)] for k, v in tokenized_examples.items()}

データセット全体に前処理関数を適用するには、🤗 Datasets の map メソッドを使用します。map 関数に batched=True を設定すると、データセットの複数の要素を一度に処理できるため、処理を高速化できます:

>>> tokenized_swag = swag.map(preprocess_function, batched=True)

バッチの例を作成する際は、データセット全体を最大長にパディングするのではなく、コラレーション時にバッチ内の最長長に合わせて動的にパディングする方が効率的です。DataCollatorForMultipleChoiceは、すべてのモデル入力をフラット化し、パディングを適用した後に、結果をアンフラット化します。

>>> from transformers import DataCollatorForMultipleChoice
>>> collator = DataCollatorForMultipleChoice(tokenizer=tokenizer)

評価

トレーニング中にメトリクスを含めることは、モデルの性能を評価する上で多くの場合、役立ちます。🤗 Evaluate ライブラリを使用すると、評価メソッドをすばやく読み込むことができます。このタスクでは、accuracy メトリクスを読み込みます(メトリクスの読み込みと計算方法の詳細については、🤗 Evaluate の クイックツアー を参照してください):

>>> import evaluate

>>> accuracy = evaluate.load("accuracy")

次に、予測値とラベルをcomputeに渡して正解率を計算する関数を作成します。

>>> import numpy as np


>>> def compute_metrics(eval_pred):
...     predictions, labels = eval_pred
...     predictions = np.argmax(predictions, axis=1)
...     return accuracy.compute(predictions=predictions, references=labels)

compute_metrics 関数はこれで準備が整いました。学習を設定する際に、この関数に戻ります。

学習

Trainer を用いたモデルのファインチューニングに慣れていない場合は、こちらの基本的なチュートリアルをご覧ください!

いよいよモデルの学習を開始できます!AutoModelForMultipleChoiceでBERTを読み込みましょう:

>>> from transformers import AutoModelForMultipleChoice, TrainingArguments, Trainer

>>> model = AutoModelForMultipleChoice.from_pretrained("google-bert/bert-base-uncased")

この時点で、残りのステップは3つだけです:

  1. TrainingArguments で学習ハイパーパラメータを定義します。必須のパラメータは output_dir のみで、モデルの保存先を指定します。push_to_hub=True を設定することで、このモデルを Hub にプッシュできます(モデルをアップロードするには Hugging Face にサインインしている必要があります)。各エポックの終了時、Trainer は精度を評価し、学習チェックポイントを保存します。
  2. モデル、データセット、トークナイザー、データコラテーター、compute_metrics 関数とともに、学習引数を Trainer に渡します。
  3. train()を呼び出して、モデルをファインチューニングします。
>>> training_args = TrainingArguments(
...     output_dir="my_awesome_swag_model",
...     eval_strategy="epoch",
...     save_strategy="epoch",
...     load_best_model_at_end=True,
...     learning_rate=5e-5,
...     per_device_train_batch_size=16,
...     per_device_eval_batch_size=16,
...     num_train_epochs=3,
...     weight_decay=0.01,
...     push_to_hub=True,
... )

>>> trainer = Trainer(
...     model=model,
...     args=training_args,
...     train_dataset=tokenized_swag["train"],
...     eval_dataset=tokenized_swag["validation"],
...     processing_class=tokenizer,
...     data_collator=collator,
...     compute_metrics=compute_metrics,
... )

>>> trainer.train()

トレーニングが完了したら、push_to_hub() メソッドでモデルを Hub に共有し、誰でもそのモデルを利用できるようにしてください。

>>> trainer.push_to_hub()

複数選択問題へのモデルのファインチューニング方法について、より詳細な例を確認するには、対応するPyTorchノートブックをご覧ください。

推論

素晴らしいですね。モデルのファインチューニングが完了したので、推論に使用できます!

テキストと2つの候補の回答を考案します:

>>> prompt = "France has a bread law, Le Décret Pain, with strict rules on what is allowed in a traditional baguette."
>>> candidate1 = "The law does not apply to croissants and brioche."
>>> candidate2 = "The law applies to baguettes."

各プロンプトと候補の回答のペアをトークン化し、PyTorchのテンソルを返します。また、labelsも作成する必要があります。

>>> from transformers import AutoTokenizer

>>> tokenizer = AutoTokenizer.from_pretrained("username/my_awesome_swag_model")
>>> inputs = tokenizer([[prompt, candidate1], [prompt, candidate2]], return_tensors="pt", padding=True)
>>> labels = torch.tensor(0).unsqueeze(0)

入力とラベルをモデルに渡し、logitsを返します:

>>> from transformers import AutoModelForMultipleChoice

>>> model = AutoModelForMultipleChoice.from_pretrained("username/my_awesome_swag_model")
>>> outputs = model(**{k: v.unsqueeze(0) for k, v in inputs.items()}, labels=labels)
>>> logits = outputs.logits

最も高い確率を持つクラスを取得します:

>>> predicted_class = logits.argmax().item()
>>> predicted_class
0
Update on GitHub