T-nerは、Pytorchで実装されたNamed-Entity-Recognition(NER)でFinetuningを使用する言語モデルのPythonツールです。モデルをFINETUNEモデルとテストするための簡単なインターフェイスがあり、クロスドメインおよび多言語データセットをテストします。 T-nerは現在、公開されているNERデータセットの高いカバレッジを統合しており、カスタムデータセットを簡単に統合できるようにしています。 T-nerで微調整されたすべてのモデルは、視覚化のためにWebアプリに展開できます。 T-nerを実証する私たちの論文は、EACL 2021に受け入れられました。すべてのモデルとデータセットは、T-ner Huggingfaceグループを介して共有されています。
New(2022年9月): Twitter tweetner7に基づいて新しいNERデータセットをリリースし、AACL 2022 Main Conferenceによって紙が受け入れられました!微調整されたモデルとともにデータセットをリリースすると、詳細については、ペーパー、リポジトリ、データセットページをご覧ください。 Twitter NERモデルもTweetNLPに統合されており、ここからデモが入手できます。
PIP経由でtnerをインストールして開始してください!
pip install tner| 説明 | リンク |
|---|---|
| モデルの微調整と評価 | |
| モデル予測 | |
| 多言語NERワークフロー |
NERデータセットには、各分割のトークンとタグのシーケンスが含まれています(通常、 train / validation / test )、
{
'train' : {
'tokens' : [
[ '@paulwalk' , 'It' , "'s" , 'the' , 'view' , 'from' , 'where' , 'I' , "'m" , 'living' , 'for' , 'two' , 'weeks' , '.' , 'Empire' , 'State' , 'Building' , '=' , 'ESB' , '.' , 'Pretty' , 'bad' , 'storm' , 'here' , 'last' , 'evening' , '.' ],
[ 'From' , 'Green' , 'Newsfeed' , ':' , 'AHFA' , 'extends' , 'deadline' , 'for' , 'Sage' , 'Award' , 'to' , 'Nov' , '.' , '5' , 'http://tinyurl.com/24agj38' ], ...
],
'tags' : [
[ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 2 , 2 , 0 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ],
[ 0 , 0 , 0 , 0 , 3 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ], ...
]
},
'validation' : ...,
'test' : ...,
}以下のように、ラベルをインデックス( label2id )にマッピングする辞書を使用します。
{ "O" : 0 , "B-ORG" : 1 , "B-MISC" : 2 , "B-PER" : 3 , "I-PER" : 4 , "B-LOC" : 5 , "I-ORG" : 6 , "I-MISC" : 7 , "I-LOC" : 8 }さまざまなパブリックNERデータセットがHuggingfaceグループで使用できます。これは、以下のように使用できます(完全なデータセットリストについては、データセットカードを参照)。
from tner import get_dataset
data , label2id = get_dataset ( dataset = "tner/wnut2017" )ユーザーは複数のデータセットを指定して、連結したデータセットを取得できます。
data , label2id = get_dataset ( dataset = [ "tner/conll2003" , "tner/ontonotes5" ])連結されたデータセットでは、ユニファイドラベルセットを使用して、エンティティラベルを統合します。アイデアは、Huggingfaceで利用可能なすべてのNERデータセットを統一された形式で共有することです。NERデータセットを追加したい場合はお知らせください。
パブリックデータセットを超えるために、ユーザーはCONLL 2003 NER共有タスクペーパーで説明されているIOB形式にフォーマットすることにより、独自のデータセットを使用できます。ここでは、すべてのデータファイルには、文の境界を表す空の行がある行ごとに1つの単語が含まれています。各行の最後に、現在の単語が名前付きエンティティ内にあるかどうかを示すタグがあります。タグは、指定されたエンティティのタイプもエンコードします。これが例の文です:
EU B-ORG
rejects O
German B-MISC
call O
to O
boycott O
British B-MISC
lamb O
. O
oでタグ付けされた単語は名前付きエンティティの外側にあり、i-xxxタグは、タイプxxxの名前付きエンティティ内の単語に使用されます。タイプXXXの2つのエンティティがすぐに隣にあるときはいつでも、2番目のエンティティの最初の単語にB-XXXがタグ付けされ、別のエンティティを開始することを示します。サンプルのカスタムデータをご覧ください。これらのカスタムファイルは、以下のようにHuggingfaceデータセットと同じようにロードできます。
from tner import get_dataset
data , label2id = get_dataset ( local_dataset = {
"train" : "examples/local_dataset_sample/train.txt" ,
"valid" : "examples/local_dataset_sample/train.txt" ,
"test" : "examples/local_dataset_sample/test.txt"
})Huggingfaceデータセットと同じように、データセットを連結できます。
data , label2id = get_dataset ( local_dataset = [
{ "train" : "..." , "valid" : "..." , "test" : "..." },
{ "train" : "..." , "valid" : "..." , "test" : "..." }
]
)T-nerは現在、上記の表に示すように、Huggingfaceグループで100以上のNERモデルを共有しています。すべてのモデルは、以下のようにtnerで使用できます。
from tner import TransformersNER
model = TransformersNER ( "tner/roberta-large-wnut2017" ) # provide model alias on huggingface
output = model . predict ([ "Jacob Collier is a Grammy awarded English artist from London" ]) # give a list of sentences (or tokenized sentence)
print ( output )
{
'prediction' : [[ 'B-person' , 'I-person' , 'O' , 'O' , 'O' , 'O' , 'O' , 'O' , 'O' , 'B-location' ]],
'probability' : [[ 0.9967652559280396 , 0.9994561076164246 , 0.9986955523490906 , 0.9947081804275513 , 0.6129112243652344 , 0.9984312653541565 , 0.9868122935295105 , 0.9983410835266113 , 0.9995284080505371 , 0.9838910698890686 ]],
'input' : [[ 'Jacob' , 'Collier' , 'is' , 'a' , 'Grammy' , 'awarded' , 'English' , 'artist' , 'from' , 'London' ]],
'entity_prediction' : [[
{ 'type' : 'person' , 'entity' : [ 'Jacob' , 'Collier' ], 'position' : [ 0 , 1 ], 'probability' : [ 0.9967652559280396 , 0.9994561076164246 ]},
{ 'type' : 'location' , 'entity' : [ 'London' ], 'position' : [ 9 ], 'probability' : [ 0.9838910698890686 ]}
]]
} model.predict 、文とバッチサイズのbatch_sizeのリストをオプションで撮影し、出力オブジェクトのinputとして返されるseparatorによって指定された半スペースまたはシンボルで文をトークン化します。オプションで、ユーザーはトークン剤(スペイシー、NLTKなど)で事前に入力をトークン化でき、予測はトークン化に従います。
output = model . predict ([[ "Jacob Collier" , "is" , "a" , "Grammy awarded" , "English artist" , "from" , "London" ]])
print ( output )
{
'prediction' : [[ 'B-person' , 'O' , 'O' , 'O' , 'O' , 'O' , 'B-location' ]],
'probability' : [[ 0.9967652559280396 , 0.9986955523490906 , 0.9947081804275513 , 0.6129112243652344 , 0.9868122935295105 , 0.9995284080505371 , 0.9838910698890686 ]],
'input' : [[ 'Jacob Collier' , 'is' , 'a' , 'Grammy awarded' , 'English artist' , 'from' , 'London' ]],
'entity_prediction' : [[
{ 'type' : 'person' , 'entity' : [ 'Jacob Collier' ], 'position' : [ 0 ], 'probability' : [ 0.9967652559280396 ]},
{ 'type' : 'location' , 'entity' : [ 'London' ], 'position' : [ 6 ], 'probability' : [ 0.9838910698890686 ]}
]]
}モデルエイリアスTransformersNER("path-to-checkpoint")の代わりに、ローカルモデルのチェックポイントを指定できます。これらのリリースされたモデルを再生成するスクリプトはこちらです。
モデル予測には、次のコマンドラインツールが利用できます。
tner-predict [-h] -m MODEL
command line tool to test finetuned NER model
optional arguments:
-h, --help show this help message and exit
-m MODEL, --model MODEL
model alias of huggingface or local checkpointtner-predict -m " tner/roberta-large-wnut2017 " 依存関係をインストールするには、Webアプリを実行するには、インストール時にオプションを追加します。
pip install tner[app]次に、リポジトリをクローンします
git clone https://github.com/asahi417/tner
cd tnerサーバーを起動します。
uvicorn app:app --reload --log-level debug --host 0.0.0.0 --port 8000ブラウザを開きますhttp://0.0.0.0:8000準備ができたら。環境変数NER_MODELによって展開するモデルを指定できます。これは、デフォルトとしてtner/roberta-large-wnut2017として設定されています。 NER_MODEL 、ローカルモデルチェックポイントディレクトリへのパスまたはトランスモデルモデルハブのモデル名です。
謝辞アプリインターフェイスは、このリポジトリに深くインスピレーションを受けています。
T-nerは、上記のように効率的なパラメーター検索でNERで微調整された言語モデルを実行する簡単なAPIを提供します。 2つの段階で構成されています。(i)すべてのモデルの検証セットで、 Lエポックのすべての可能K構成を微調整し、評価メトリック(デフォルトとしてマイクロF1)を計算します。第2段階の最良のモデルは、検証メトリックが減少するまで微調整を続けます。
2段階のパラメーター検索でのこの微調整は、 tnerを使用して数行で実現できます。
from tner import GridSearcher
searcher = GridSearcher (
checkpoint_dir = './ckpt_tner' ,
dataset = "tner/wnut2017" , # either of `dataset` (huggingface dataset) or `local_dataset` (custom dataset) should be given
model = "roberta-large" , # language model to fine-tune
epoch = 10 , # the total epoch (`L` in the figure)
epoch_partial = 5 , # the number of epoch at 1st stage (`M` in the figure)
n_max_config = 3 , # the number of models to pass to 2nd stage (`K` in the figure)
batch_size = 16 ,
gradient_accumulation_steps = [ 4 , 8 ],
crf = [ True , False ],
lr = [ 1e-4 , 1e-5 ],
weight_decay = [ 1e-7 ],
random_seed = [ 42 ],
lr_warmup_step_ratio = [ 0.1 ],
max_grad_norm = [ 10 ]
)
searcher . train ()現在、次のパラメーターは調整可能です。
gradient_accumulation_steps :勾配蓄積の数crf :出力埋め込みの上にCRFを使用しますlr :学習率weight_decay :重量減衰の係数random_seed :ランダムシードlr_warmup_step_ratio :学習率の線形ウォームアップ比、例:0.3の場合、学習率は合計ステップの30%まで直線的にウォームアップします(結局減衰なし)max_grad_norm :グラデーションクリッピングの標準各引数の詳細については、ソースを参照してください。
次のコマンドラインツールは、微調整に使用できます。
tner-train-search [-h] -c CHECKPOINT_DIR [-d DATASET [DATASET ...]] [-l LOCAL_DATASET [LOCAL_DATASET ...]]
[--dataset-name DATASET_NAME [DATASET_NAME ...]] [-m MODEL] [-b BATCH_SIZE] [-e EPOCH] [--max-length MAX_LENGTH] [--use-auth-token]
[--dataset-split-train DATASET_SPLIT_TRAIN] [--dataset-split-valid DATASET_SPLIT_VALID] [--lr LR [LR ...]]
[--random-seed RANDOM_SEED [RANDOM_SEED ...]] [-g GRADIENT_ACCUMULATION_STEPS [GRADIENT_ACCUMULATION_STEPS ...]]
[--weight-decay WEIGHT_DECAY [WEIGHT_DECAY ...]] [--lr-warmup-step-ratio LR_WARMUP_STEP_RATIO [LR_WARMUP_STEP_RATIO ...]]
[--max-grad-norm MAX_GRAD_NORM [MAX_GRAD_NORM ...]] [--crf CRF [CRF ...]] [--optimizer-on-cpu] [--n-max-config N_MAX_CONFIG]
[--epoch-partial EPOCH_PARTIAL] [--max-length-eval MAX_LENGTH_EVAL]
Fine-tune transformers on NER dataset with Robust Parameter Search
optional arguments:
-h , --help show this help message and exit
-c CHECKPOINT_DIR, --checkpoint-dir CHECKPOINT_DIR
checkpoint directory
-d DATASET [DATASET ...], --dataset DATASET [DATASET ...]
dataset name (or a list of it) on huggingface tner organization eg. ' tner/conll2003 ' [ ' tner/conll2003 ' , ' tner/ontonotes5 ' ]] see
https://huggingface.co/datasets ? search = tner for full dataset list
-l LOCAL_DATASET [LOCAL_DATASET ...], --local-dataset LOCAL_DATASET [LOCAL_DATASET ...]
a dictionary (or a list) of paths to local BIO files eg.{ " train " : " examples/local_dataset_sample/train.txt " , " test " :
" examples/local_dataset_sample/test.txt " }
--dataset-name DATASET_NAME [DATASET_NAME ...]
[optional] data name of huggingface dataset (should be same length as the ` dataset ` )
-m MODEL, --model MODEL
model name of underlying language model (huggingface model)
-b BATCH_SIZE, --batch-size BATCH_SIZE
batch size
-e EPOCH, --epoch EPOCH
the number of epoch
--max-length MAX_LENGTH
max length of language model
--use-auth-token Huggingface transformers argument of ` use_auth_token `
--dataset-split-train DATASET_SPLIT_TRAIN
dataset split to be used for training ( ' train ' as default)
--dataset-split-valid DATASET_SPLIT_VALID
dataset split to be used for validation ( ' validation ' as default)
--lr LR [LR ...] learning rate
--random-seed RANDOM_SEED [RANDOM_SEED ...]
random seed
-g GRADIENT_ACCUMULATION_STEPS [GRADIENT_ACCUMULATION_STEPS ...], --gradient-accumulation-steps GRADIENT_ACCUMULATION_STEPS [GRADIENT_ACCUMULATION_STEPS ...]
the number of gradient accumulation
--weight-decay WEIGHT_DECAY [WEIGHT_DECAY ...]
coefficient of weight decay (set 0 for None)
--lr-warmup-step-ratio LR_WARMUP_STEP_RATIO [LR_WARMUP_STEP_RATIO ...]
linear warmup ratio of learning rate (no decay).eg) if it ' s 0.3, the learning rate will warmup linearly till 30% of the total step
(set 0 for None)
--max-grad-norm MAX_GRAD_NORM [MAX_GRAD_NORM ...]
norm for gradient clipping (set 0 for None)
--crf CRF [CRF ...] use CRF on top of output embedding (0 or 1)
--optimizer-on-cpu put optimizer on CPU to save memory of GPU
--n-max-config N_MAX_CONFIG
the number of configs to run 2nd phase search
--epoch-partial EPOCH_PARTIAL
the number of epoch for 1st phase search
--max-length-eval MAX_LENGTH_EVAL
max length of language model at evaluationtner-train-search -m " roberta-large " -c " ckpt " -d " tner/wnut2017 " -e 15 --epoch-partial 5 --n-max-config 3 -b 64 -g 1 2 --lr 1e-6 1e-5 --crf 0 1 --max-grad-norm 0 10 --weight-decay 0 1e-7NERモデルの評価は、評価するデータセットとしてdatasetまたはlocal_datasetを使用するmodel.evaluate関数によって行われます。
from tner import TransformersNER
model = TransformersNER ( "tner/roberta-large-wnut2017" ) # provide model alias on huggingface
# huggingface dataset
metric = model . evaluate ( 'tner/wnut2017' , dataset_split = 'test' )
# local dataset
metric = model . evaluate ( local_dataset = { "test" : "examples/local_dataset_sample/test.txt" }, dataset_split = 'test' )出力オブジェクトmetricの例は、ここにあります。
ドメイン外の精度をよりよく理解するために、エンティティスパン予測パイプラインを提供します。これは、エンティティタイプを無視し、IOBエンティティの位置でのみメトリックを計算します(バイナリシーケンスラベル付け)。
metric = model . evaluate ( datasets = 'tner/wnut2017' , dataset_split = 'test' , span_detection_mode = True )モデル予測には、次のコマンドラインツールが利用できます。
tner-evaluate [-h] -m MODEL -e EXPORT [-d DATASET [DATASET ...]] [-l LOCAL_DATASET [LOCAL_DATASET ...]]
[--dataset-name DATASET_NAME [DATASET_NAME ...]] [--dataset-split DATASET_SPLIT] [--span-detection-mode] [--return-ci] [-b BATCH_SIZE]
Evaluate NER model
optional arguments:
-h , --help show this help message and exit
-m MODEL, --model MODEL
model alias of huggingface or local checkpoint
-e EXPORT, --export EXPORT
file to export the result
-d DATASET [DATASET ...], --dataset DATASET [DATASET ...]
dataset name (or a list of it) on huggingface tner organization eg. ' tner/conll2003 ' [ ' tner/conll2003 ' , ' tner/ontonotes5 ' ]] see
https://huggingface.co/datasets ? search = tner for full dataset list
-l LOCAL_DATASET [LOCAL_DATASET ...], --local-dataset LOCAL_DATASET [LOCAL_DATASET ...]
a dictionary (or a list) of paths to local BIO files eg.{ " train " : " examples/local_dataset_sample/train.txt " , " test " :
" examples/local_dataset_sample/test.txt " }
--dataset-name DATASET_NAME [DATASET_NAME ...]
[optional] data name of huggingface dataset (should be same length as the ` dataset ` )
--dataset-split DATASET_SPLIT
dataset split to be used for test ( ' test ' as default)
--span-detection-mode
return F1 of entity span detection (ignoring entity type error and cast as binary sequence classification as below)- NER : [ " O " ,
" B-PER " , " I-PER " , " O " , " B-LOC " , " O " , " B-ORG " ]- Entity-span detection: [ " O " , " B-ENT " , " I-ENT " , " O " , " B-ENT " , " O " , " B-ENT " ]
--return-ci return confidence interval by bootstrap
-b BATCH_SIZE, --batch-size BATCH_SIZE
batch sizetner-evaluate -m " tner/roberta-large-wnut2017 " -e " metric.json " -d " tner/conll2003 " -b " 32 " これらのリソースのいずれかを使用する場合は、次の論文を引用してください。
@inproceedings{ushio-camacho-collados-2021-ner,
title = "{T}-{NER}: An All-Round Python Library for Transformer-based Named Entity Recognition",
author = "Ushio, Asahi and
Camacho-Collados, Jose",
booktitle = "Proceedings of the 16th Conference of the European Chapter of the Association for Computational Linguistics: System Demonstrations",
month = apr,
year = "2021",
address = "Online",
publisher = "Association for Computational Linguistics",
url = "https://www.aclweb.org/anthology/2021.eacl-demos.7",
pages = "53--62",
abstract = "Language model (LM) pretraining has led to consistent improvements in many NLP downstream tasks, including named entity recognition (NER). In this paper, we present T-NER (Transformer-based Named Entity Recognition), a Python library for NER LM finetuning. In addition to its practical utility, T-NER facilitates the study and investigation of the cross-domain and cross-lingual generalization ability of LMs finetuned on NER. Our library also provides a web app where users can get model predictions interactively for arbitrary text, which facilitates qualitative model evaluation for non-expert programmers. We show the potential of the library by compiling nine public NER datasets into a unified format and evaluating the cross-domain and cross- lingual performance across the datasets. The results from our initial experiments show that in-domain performance is generally competitive across datasets. However, cross-domain generalization is challenging even with a large pretrained LM, which has nevertheless capacity to learn domain-specific features if fine- tuned on a combined dataset. To facilitate future research, we also release all our LM checkpoints via the Hugging Face model hub.",
}