Huggingface Transformers 入門 (13) - 英語の質問応答の学習
「Huggingface Transformers」による英語の質問応答の学習手順をまとめました。
・Huggingface Transformers 4.1.1
・Huggingface Datasets 1.2
前回
1. 英語の質問応答の学習
「SQuAD」を使って英語の質問応答を学習します。
(1) Googleドライブのフォルダの準備
「Google Colab」のディスクサイズ(68.40GB)では足りないので、Googleドライブ 100GB(¥250/月)で学習します。
# Googleドライブのフォルダの準備
from google.colab import drive
drive.mount('/content/drive')
!mkdir -p /content/drive/'My Drive'/bert/
%cd /content/drive/'My Drive'/bert/
(2) Huggingface Transformersのインストール。
# Huggingface Transformersのインストール
!git clone https://github.com/huggingface/transformers
%cd transformers
!pip install .
(3) 「Huggingface Datasets」のインストール。
# Huggingface Datasetsのインストール
!pip install datasets
(4) run_qa.pyで学習を実行。
「output」フォルダにモデルが出力されます。
!python ./examples/question-answering/run_qa.py \
--model_name_or_path=bert-base-uncased \
--dataset_name=squad \
--do_train \
--do_eval \
--per_device_train_batch_size=12 \
--learning_rate=3e-5 \
--num_train_epochs=2 \
--max_seq_length=384 \
--output_dir=output/ \
--overwrite_output_dir \
--doc_stride=128
***** Eval results *****
epoch = 2.0
exact_match = 81.06906338694418
f1 = 88.4361941603758
【注】 「run_qa.py」は、Huggingface TokenizerのFast Tokenizerを備えたモデルでのみ機能します。このテーブルで、モデルにFast Tokenizerがあるかどうかを確認できます。ない場合でも、旧版のスクリプトを使用できます。
「run_qa.py」の詳細は、次のとおりです。
2. 英語の質問応答モデルの推論
from transformers import pipeline, AutoModelForQuestionAnswering, AutoTokenizer
# 入力テキスト
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`.
"""
# モデルとトークナイザーの準備
model = AutoModelForQuestionAnswering.from_pretrained('output/')
tokenizer = AutoTokenizer.from_pretrained("bert-large-uncased-whole-word-masking-finetuned-squad")
nlp = pipeline("question-answering",model=model,tokenizer=tokenizer)
# 推論の実行
print(nlp(question="What is a good example of a question answering dataset?", context=context))
{'score': 0.6514624357223511, 'start': 147, 'end': 160, 'answer': 'SQuAD dataset'}
次回
この記事が気に入ったらサポートをしてみませんか?