百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
T

tner

> 数据库
开源

语言模型在 NER 上的微调,具有简单的接口和跨域评估。"T-NER: 一套适用于基于 Transformer 的命名实体识别的全能 Python 库

397 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

语言模型在 NER 上的微调,具有简单的接口和跨域评估。"T-NER: 一套适用于基于 Transformer 的命名实体识别的全能 Python 库

T-NER: An All-Round Python Library for Transformer-based Named Entity Recognition

T-NER is a Python tool for language model finetuning on named-entity-recognition (NER) implemented in pytorch, available via pip. It has an easy interface to finetune models and test on cross-domain and multilingual datasets. T-NER currently integrates high coverage of publicly available NER datasets and enables an easy integration of custom datasets. All models finetuned with T-NER can be deployed on our web app for visualization. Our paper demonstrating T-NER has been accepted to EACL 2021. All the models and datasets are shared via T-NER HuggingFace group.

NEW (September 2022): We released new NER dataset based on Twitter tweetner7 and the paper got accepted by AACL 2022 main conference! We release the dataset along with fine-tuned models, and more details can be found at the paper, repository and dataset page. The Twitter NER model has also been integrated into TweetNLP, and a demo is available here.

  • Resources: MODEL_CARD, DATASET_CARD, Gradio Online DEMO
  • HuggingFace: https://huggingface.co/tner
  • GitHub: https://github.com/asahi417/tner
  • Papers
    • T-NER (EACL2021): acl anthology, arxiv
    • TweetNER7 (AACL 2022): arxiv

Install tner via pip to get started!

bash
pip install tner

Table of Contents

  1. Dataset
    1.1 Preset Dataset
    1.2 Custom Dataset
  2. Model
  3. Fine-Tuning Language Model on NER
  4. Evaluating NER Model
  5. Web API
  6. Colab Examples
  7. Reference

Google Colab Examples

Description Link
Model Finetuning & Evaluation
Model Prediction
Multilingual NER Workflow

Dataset

An NER dataset contains a sequence of tokens and tags for each split (usually train/validation/test),

…

with a dictionary to map a label to its index (label2id) as below.

python
{"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}

Preset Dataset

A variety of public NER datasets are available on our HuggingFace group, which can be used as below (see DATASET CARD for full dataset lists).

python
from tner import get_dataset
data, label2id = get_dataset(dataset="tner/wnut2017")

User can specify multiple datasets to get a concatenated dataset.

python
data, label2id = get_dataset(dataset=["tner/conll2003", "tner/ontonotes5"])

In concatenated datasets, we use the unified label set to unify the entity label. The idea is to share all the available NER datasets on the HuggingFace in a unified format, so let us know if you want any NER datasets to be added there!

Custom Dataset

To go beyond the public datasets, users can use their own datasets by formatting them into the IOB format described in CoNLL 2003 NER shared task paper, where all data files contain one word per line with empty lines representing sentence boundaries. At the end of each line there is a tag which states whether the current word is inside a named entity or not. The tag also encodes the type of named entity. Here is an example sentence:

EU B-ORG
rejects O
German B-MISC
call O
to O
boycott O
British B-MISC
lamb O
. O

Words tagged with O are outside of named entities and the I-XXX tag is used for words inside a named entity of type XXX. Whenever two entities of type XXX are immediately next to each other, the first word of the second entity will be tagged B-XXX in order to show that it starts another entity. Please take a look sample custom data. Those custom files can be loaded in a same way as HuggingFace dataset as below.

python
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"
})

Same as the HuggingFace dataset, one can concatenate dataset.

python
data, label2id = get_dataset(local_dataset=[
   {"train": "...", "valid": "...", "test": "..."},
   {"train": "...", "valid": "...", "test": "..."}
   ]
)

Model

T-NER currently has shared more than 100 NER models on HuggingFace group, as shown in the above table, which reports the major models only and see MODEL_CARD for full model lists. All the models can be used with tner as below.

…

The model.predict takes a list of sentences and batch size batch_size optionally, and tokenizes the sentence by a half-space or the symbol specified by separator, which is returned as input in its output object. Optionally, user can tokenize the inputs beforehand with any tokenizer (spacy, nltk, etc) and the prediction will follow the tokenization.

…

A local model checkpoint can be specified instead of model alias TransformersNER("path-to-checkpoint"). Script to re-produce those released models is here.

command-line tool

Following command-line tool is available for model prediction.

bash
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 checkpoint
  • Example
bash
tner-predict -m "tner/roberta-large-wnut2017"

Web App

To install dependencies to run the web app, add option at installation.

bash
pip install tner[app]

Then, clone the repository

bash
git clone https://github.com/asahi417/tner
cd tner

and launch the server.

bash
uvicorn app:app --reload --log-level debug --host 0.0.0.0 --port 8000

Open your browser http://0.0.0.0:8000 once ready. You can specify model to deploy by an environment variable NER_MODEL, which is set as tner/roberta-large-wnut2017 as a default. NER_MODEL can be either path to your local model checkpoint directory or model name on transformers model hub.

Acknowledgement The App interface is heavily inspired by this repository.

Fine-Tuning Language Model on NER

T-NER provides an easy API to run language model fine-tuning on NER with an efficient parameter-search as described above. It consists of 2 stages: (i) fine-tuning with every possible configurations for a small epoch and compute evaluation metric (micro F1 as default) on the validation set for all the models, and (ii) pick up top-K models to continue fine-tuning till L epoch. The best model in the second stage will continue fine-tuning till the validation metric get decreased.

This fine-tuning with two-stage parameter search can be achieved in a few lines with tner.

…

Following parameters are tunable at the moment.

  • gradient_accumulation_steps: the number of gradient accumulation
  • crf: use CRF on top of output embedding
  • lr: learning rate
  • weight_decay: coefficient for weight decay
  • random_seed: random seed
  • lr_warmup_step_ratio: linear warmup ratio of learning rate, eg) if it's 0.3, the learning rate will warmup linearly till 30% of the total step (no decay after all)
  • max_grad_norm: norm for gradient clipping

See source for more information about each argument.

command-line tool

Following command-line tool is available for fine-tuning.

…
  • Example
bash
tner-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-7

Evaluating NER Model

Evaluation of NER models is done by model.evaluate function that takes dataset or local_dataset as the dataset to evaluate on.

python
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')

An example of the output object metric can be found here.

entity span prediction

For better understanding of out-of-domain accuracy, we provide the entity span prediction pipeline, which ignores the entity type and compute metrics only on the IOB entity position (binary sequence labeling).

python
metric = model.evaluate(datasets='tner/wnut2017', dataset_split='test', span_detection_mode=True)

Command line tool

Following command-line tool is available for model prediction.

…
  • Example
bash
tner-evaluate -m "tner/roberta-large-wnut2017" -e "metric.json" -d "tner/conll2003" -b "32"

Reference

If you use any of these resources, please cite the following paper:

…

Issues· 18 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Pythonlanguage-modelnamed-entity-recognitionnlptransformers

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类数据库
定价开源

> 相关工具

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库