# 選択問題

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

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

1. [SWAG](https://huggingface.co/datasets/allenai/swag) データセットの`regular`設定で、複数の選択肢と一部のコンテキストが与えられたときに最良の答えを選択するよう、[BERT](https://huggingface.co/google-bert/bert-base-uncased)をファインチューニングします。
2. ファインチューニングしたモデルを推論に使用します。

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

```bash
pip install transformers datasets evaluate
```

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

```py
>>> from huggingface_hub import notebook_login

>>> notebook_login()
```

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

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

```py
>>> from datasets import load_dataset

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

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

```py
>>> 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つの候補の結尾を処理することです。

```py
>>> 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`フィールドが得られるようにアンフラット化します。

```py
>>> 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](https://huggingface.co/docs/datasets/v5.2.0/en/package_reference/main_classes#datasets.Dataset.map) メソッドを使用します。`map` 関数に `batched=True` を設定すると、データセットの複数の要素を一度に処理できるため、処理を高速化できます:

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

バッチの例を作成するには、データセット全体を最大長にパディングするのではなく、コラレーション時にバッチ内の最長長に合わせて*動的にパディング*する方が効率的です。[DataCollatorForMultipleChoice](/docs/transformers/v5.24.0/ja/main_classes/data_collator#transformers.DataCollatorForMultipleChoice)は、すべてのモデル入力をフラットにし、パディングを適用してから、結果をアンフラットします。

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

## 評価

学習中にメトリクスを含めることは、モデルの性能を評価する上でしばしば役立ちます。🤗 [Evaluate](https://huggingface.co/docs/evaluate/index) ライブラリを使用すると、評価メソッドをすばやく読み込むことができます。このタスクでは、[accuracy](https://huggingface.co/spaces/evaluate-metric/accuracy) メトリクスを読み込みます（メトリクスの読み込みと計算方法の詳細については、🤗 Evaluate の [クイックツアー](https://huggingface.co/docs/evaluate/a_quick_tour) を参照してください）：

```py
>>> import evaluate

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

次に、予測値とラベルを[compute](https://huggingface.co/docs/evaluate/v0.4.6/en/package_reference/main_classes#evaluate.EvaluationModule.compute)に渡して正解率を計算する関数を作成します。

```py
>>> 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](/docs/transformers/v5.24.0/ja/main_classes/trainer#transformers.Trainer)によるモデルのファインチューニングに慣れていない場合は、[こちら](../training)の基本的なチュートリアルをご覧ください!

いよいよモデルの学習を開始できます![AutoModelForMultipleChoice](/docs/transformers/v5.24.0/ja/model_doc/auto#transformers.AutoModelForMultipleChoice)でBERTを読み込みましょう:

```py
>>> from transformers import AutoModelForMultipleChoice, TrainingArguments, Trainer

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

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

1. [TrainingArguments](/docs/transformers/v5.24.0/ja/main_classes/trainer#transformers.TrainingArguments) で学習ハイパーパラメータを定義します。必須のパラメータは `output_dir` だけで、モデルの保存先を指定します。`push_to_hub=True` を設定することで、このモデルを Hub にプッシュできます（モデルをアップロードするには Hugging Face にサインインしている必要があります）。各エポックの終了時、[Trainer](/docs/transformers/v5.24.0/ja/main_classes/trainer#transformers.Trainer) は精度を評価し、学習チェックポイントを保存します。
2. モデル、データセット、トークナイザー、データコラテーター、`compute_metrics` 関数とともに、学習引数を [Trainer](/docs/transformers/v5.24.0/ja/main_classes/trainer#transformers.Trainer) に渡します。
3. [train()](/docs/transformers/v5.24.0/ja/main_classes/trainer#transformers.Trainer.train)を呼び出して、モデルをファインチューニングします。

```py
>>> 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()](/docs/transformers/v5.24.0/ja/main_classes/trainer#transformers.Trainer.push_to_hub) メソッドでモデルを Hub に共有し、誰でもそのモデルを利用できるようにしてください。

```py
>>> trainer.push_to_hub()
```

複数選択問題へのモデルのファインチューニング方法について、より詳細な例を確認するには、対応する[PyTorchノートブック](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/multiple_choice.ipynb)をご覧ください。

## 推論

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

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

```py
>>> 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`も作成する必要があります。

```py
>>> 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`を返します:

```py
>>> 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
```

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

```py
>>> predicted_class = logits.argmax().item()
>>> predicted_class
0
```

