🚀 BERT中文命名實體識別(bert4ner)模型
BERT中文命名實體識別模型,可用於中文文本中的實體識別任務,在PEOPLE測試集上接近SOTA水平。
✨ 主要特性
- 在PEOPLE測試集上有接近SOTA的表現。
- 開源在實體識別項目
nerpy
,方便調用。
- 提供多種使用方式,支持不同場景需求。
📦 安裝指南
使用nerpy
調用模型
本項目開源在實體識別項目:nerpy,可支持bert4ner模型。若使用nerpy
,可通過如下命令調用:
pip install nerpy
使用HuggingFace Transformers調用模型
若不使用nerpy
,可按以下步驟操作。首先,你需要將輸入數據通過transformer模型處理,然後應用bio標籤來獲取實體詞。
安裝所需包:
pip install transformers seqeval
💻 使用示例
基礎用法(使用nerpy
)
from nerpy import NERModel
model = NERModel("bert", "shibing624/bert4ner-base-chinese")
predictions, raw_outputs, entities = model.predict(["常建良,男,1963年出生,工科學士,高級工程師"], split_on_space=False)
print("entities:", entities)
輸出結果:
entities: [('常建良', 'PER'), ('1963年', 'TIME')]
高級用法(使用HuggingFace Transformers)
import os
import torch
from transformers import AutoTokenizer, AutoModelForTokenClassification
from seqeval.metrics.sequence_labeling import get_entities
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
tokenizer = AutoTokenizer.from_pretrained("shibing624/bert4ner-base-chinese")
model = AutoModelForTokenClassification.from_pretrained("shibing624/bert4ner-base-chinese")
label_list = ['I-ORG', 'B-LOC', 'O', 'B-ORG', 'I-LOC', 'I-PER', 'B-TIME', 'I-TIME', 'B-PER']
sentence = "王宏偉來自北京,是個警察,喜歡去王府井遊玩兒。"
def get_entity(sentence):
tokens = tokenizer.tokenize(sentence)
inputs = tokenizer.encode(sentence, return_tensors="pt")
with torch.no_grad():
outputs = model(inputs).logits
predictions = torch.argmax(outputs, dim=2)
char_tags = [(token, label_list[prediction]) for token, prediction in zip(tokens, predictions[0].numpy())][1:-1]
print(sentence)
print(char_tags)
pred_labels = [i[1] for i in char_tags]
entities = []
line_entities = get_entities(pred_labels)
for i in line_entities:
word = sentence[i[1]: i[2] + 1]
entity_type = i[0]
entities.append((word, entity_type))
print("Sentence entity:")
print(entities)
get_entity(sentence)
輸出結果:
王宏偉來自北京,是個警察,喜歡去王府井遊玩兒。
[('王', 'B-PER'), ('宏', 'I-PER'), ('偉', 'I-PER'), ('來', 'O'), ('自', 'O'), ('北', 'B-LOC'), ('京', 'I-LOC'), (',', 'O'), ('是', 'O'), ('個', 'O'), ('警', 'O'), ('察', 'O'), (',', 'O'), ('喜', 'O'), ('歡', 'O'), ('去', 'O'), ('王', 'B-LOC'), ('府', 'I-LOC'), ('井', 'I-LOC'), ('遊', 'O'), ('玩', 'O'), ('兒', 'O'), ('。', 'O')]
Sentence entity:
[('王宏偉', 'PER'), ('北京', 'LOC'), ('王府井', 'LOC')]
📚 詳細文檔
模型評估
bert4ner-base-chinese
在PEOPLE(人民日報)測試數據上的評估結果如下:
BERT在PEOPLE測試集上的整體表現:
|
準確率 |
召回率 |
F1值 |
BertSoftmax |
0.9425 |
0.9627 |
0.9525 |
該模型在PEOPLE的測試集上達到接近SOTA水平。
網絡結構
BertSoftmax的網絡結構(原生BERT):

模型文件組成
bert4ner-base-chinese
├── config.json
├── model_args.json
├── pytorch_model.bin
├── special_tokens_map.json
├── tokenizer_config.json
└── vocab.txt
訓練數據集
中文實體識別數據集
CNER中文實體識別數據集的數據格式:
美 B-LOC
國 I-LOC
的 O
華 B-PER
萊 I-PER
士 I-PER
我 O
跟 O
他 O
若需要訓練bert4ner,請參考https://github.com/shibing624/nerpy/tree/main/examples
📄 許可證
本項目採用Apache-2.0許可證。
📚 引用
@software{nerpy,
author = {Xu Ming},
title = {nerpy: Named Entity Recognition toolkit},
year = {2022},
url = {https://github.com/shibing624/nerpy},
}