Huggingface Transformers 入門 (14) - 日本語の質問応答の学習
「Huggingface Transformers」による日本語の質問応答の学習手順をまとめました。
・Huggingface Transformers 4.1.1
・Huggingface Datasets 1.2
前回
1. データセットの準備
「SQuAD」と同じ書式である日本語の質問応答データセット「運転ドメインQAデータセット」を使います。
・DDQA-1.0_RC-QA_train.json
・DDQA-1.0_RC-QA_dev.json
2. 日本語の質問応答の学習
(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) 日本語対応パッケージのインストール。
# 日本語対応パッケージのインストール
!pip install fugashi[unidic-lite]
!pip install ipadic
(4) 「Huggingface Datasets」のインストール。
# Huggingface Datasetsのインストール
!pip install datasets
(5) 「DDQA-1.0_RC-QA_train.json」と「DDQA-1.0_RC-QA_dev.json」をbert/transformersに配置。
(6) run_squad.pyで学習を実行。
「run_qa.py」は、「Tokenizer check: this script requires a fast tokenizer.」で引っかかったので、旧版である「run_squad.py」を使います。「output」フォルダにモデルが出力されます。
%%time
# 質問応答の学習
!python ./examples/legacy/question-answering/run_squad.py \
--model_type=bert \
--model_name_or_path=cl-tohoku/bert-base-japanese-whole-word-masking \
--do_train \
--do_eval \
--train_file=DDQA-1.0_RC-QA_train.json \
--predict_file=DDQA-1.0_RC-QA_dev.json \
--per_gpu_train_batch_size 12 \
--learning_rate 3e-5 \
--num_train_epochs 10 \
--max_seq_length 384 \
--doc_stride 128 \
--overwrite_output_dir \
--output_dir output/
***** Running evaluation *****
Num examples = 1057
Batch size = 8
Evaluation done in total 30.879026 secs (0.029214 sec per example)
Results: {'exact': 22.854387656702023, 'f1': 22.854387656702023, 'total': 1037, 'HasAns_exact': 22.854387656702023, 'HasAns_f1': 22.854387656702023, 'HasAns_total': 1037, 'best_exact': 22.854387656702023, 'best_exact_thresh': 0.0, 'best_f1': 22.854387656702023, 'best_f1_thresh': 0.0}
CPU times: user 38.7 s, sys: 6.52 s, total: 45.3 s
Wall time: 4h 3min 44s
3. 日本語の質問応答の実行
from transformers import BertJapaneseTokenizer, AutoModelForQuestionAnswering
import torch
# 入力テキスト
context = "本日お昼頃、高崎方面へ自転車で出かけました。"
question="どこへ出かけた?"
# モデルとトークナイザーの準備
model = AutoModelForQuestionAnswering.from_pretrained('output/')
tokenizer = BertJapaneseTokenizer.from_pretrained('cl-tohoku/bert-base-japanese-whole-word-masking')
# 推論の実行
inputs = tokenizer.encode_plus(question, context, add_special_tokens=True, return_tensors="pt")
input_ids = inputs["input_ids"].tolist()[0]
output = model(**inputs)
answer_start = torch.argmax(output.start_logits)
answer_end = torch.argmax(output.end_logits) + 1
answer = tokenizer.convert_tokens_to_string(tokenizer.convert_ids_to_tokens(input_ids[answer_start:answer_end]))
# 結果出力
print("質問: "+question)
print("応答: "+answer)
質問: どこへ出かけた?
応答: 高崎 方面
次回
この記事が気に入ったらサポートをしてみませんか?