固有表現抽出のタスクでは、CoNLL2003というShared Taskのデータセットがある。
今回はCoNLL2003のデータセットを用いて、BERT-baseのモデルをfine-tuningする。
paperswithcode.com
CoNLL2003のデータセットを取得
wget https://data.deepai.org/conll2003.zip
unzip conll2003.zip
ls -l
train.txt valid.txt test.txt
使用する事前学習済みモデル
今回は、事前学習済みモデルとして、BERT-baseのuncasedモデルを利用する。
uncasedは、大文字と小文字を区別せずに学習されたモデルである。
例えば、englishとEnglishを区別しない。
一方、casedは、大文字と小文字を区別して学習されたモデルである。
例えば、englishとEnglishを区別する。
BERT-base-uncasedは、BookCorpusとEnglish Wikipediaのコーパスを用いて、自己教師あり学習で事前学習されたモデルである。
huggingface.co
transformersライブラリのv3.4.0をclone
手順については、前回の記事を参考に、Huggingfaceのtransformersライブラリのv3.4.0を用いる。
sktshk.hatenablog.com
なお、https://github.com/huggingface/transformers/tree/v3.4.0/examples/token-classificationの手順を参考にしている。
v3.4.0のタグのファイル一式をcloneしてくる。
git clone git@github.com:huggingface/transformers.git -b v3.4.0
cd transformers/examples/token-classification
実行前の準備
実行前の準備を行う。
export MAX_LENGTH=128
export BERT_MODEL=bert-base-uncased
python3 scripts/preprocess.py train.txt $BERT_MODEL $MAX_LENGTH > train.txt_new
python3 scripts/preprocess.py valid.txt $BERT_MODEL $MAX_LENGTH > dev.txt_new
python3 scripts/preprocess.py test.txt $BERT_MODEL $MAX_LENGTH > test.txt_new
mv train.txt_new train.txt
mv dev.txt_new dev.txt
mv test.txt_new test.txt
cat train.txt dev.txt test.txt | cut -d " " -f 4 | grep -v "^$"| sort | uniq > labels.txt
configファイルとしてjson形式のファイルを作成。
ちなみに、fine-tuningで学習させたモデルを使って予測のみをする場合は、do_train, do_evalをfalseにすればよい。
{
"data_dir": ".",
"labels": "./labels.txt",
"model_name_or_path": "bert-base-uncased",
"output_dir": "outputmodel",
"max_seq_length": 128,
"num_train_epochs": 3,
"per_device_train_batch_size": 32,
"save_steps": 750,
"seed": 1,
"do_train": true,
"do_eval": true,
"do_predict": true
}
学習させる前には、run_ner.pyのis_world_masterをis_world_process_zeroに変更しておく。
fine-tuningを行う
bert-base-uncasedモデルのfine-tuningを実行する。
GPU環境であれば、10分程度で完了する。
python run_ner.py config.json
***** Running training *****
Num examples = 14042
Num Epochs = 3
Instantaneous batch size per device = 32
Total train batch size (w. parallel, distributed & accumulation) = 32
Gradient Accumulation steps = 1
Total optimization steps = 1317
実行結果を確認する
実行が終わると、結果が出力される。
***** Running Prediction *****
Num examples = 3454
Batch size = 8
01/09/2022 13:16:05 - INFO - __main__ - test_accuracy_score = 0.9805534618283622
01/09/2022 13:16:05 - INFO - __main__ - test_precision = 0.8953206239168111
01/09/2022 13:16:05 - INFO - __main__ - test_recall = 0.9146600566572238
01/09/2022 13:16:05 - INFO - __main__ - test_f1 = 0.904887020493957
01/09/2022 13:16:05 - INFO - __main__ - test_runtime = 20.6979
01/09/2022 13:16:05 - INFO - __main__ - test_samples_per_second = 166.877
01/09/2022 13:16:05 - INFO - __main__ - test_steps_per_second = 20.872
タグ付け結果の確認
実際のタグ付け結果は、結果のディレクトリのtest_predictions.txtに記載されている。
more test_predictions.txt
-DOCSTART- -X- -X- O
SOCCER O
- O
JAPAN B-LOC
GET O
LUCKY O
WIN O
, O
CHINA B-LOC
IN O
SURPRISE O
DEFEAT O
. O