Python-Flair 实现英文命名实体识别(NER)

一、什么是Flair库?

Flair是由Zalando Research开发的一个简单的自然语言处理(NLP)库。 Flair的框架直接构建在PyTorch上,PyTorch是最好的深度学习框架之一。 Zalando Research团队还为以下NLP任务发布了几个预先训练的模型:

1. 名称-实体识别(NER):它可以识别单词是代表文本中的人,位置还是名称。

2. 词性标注(PoS):将给定文本中的所有单词标记为它们所属的“词性”。

3. 文本分类:根据标准对文本进行分类(标签)。

4. 培训定制模型:制作我们自己的定制模型。

Github地址:GitHub - flairNLP/flair: A very simple framework for state-of-the-art Natural Language Processing (NLP)

二、如何使用Flair进行命名实体识别?

1. 环境安装
 

pip install flair -i https://mirrors.aliyun.com/pypi/simple/

2. 使用

from flair.data import Sentence
from flair.models import SequenceTagger

# load tagger
tagger = SequenceTagger.load("flair/ner-english-large")

# make example sentence
sentence = Sentence("George Washington went to Washington")

# predict NER tags
tagger.predict(sentence)

# print sentence
print(sentence)

# print predicted NER spans
print('The following NER tags are found:')
# iterate over entities and print
for entity in sentence.get_spans('ner'):
    print(entity)

常用模型介绍:https://huggingface.co/flair

3. 常见问题处理

Q:huggingface_hub.utils._errors.LocalEntryNotFoundError: An error happened while trying to locate the file on the Hub and we cannot find the requested files in the local cache. Please check your connection and try again or make sure your Internet connection is on.

A:huggingface不支持国内访问,所以无法直接下载模型,可以使用梯子或者手动下载模型到本地,然后更新Flari加载模型路径即可SequenceTagger.load(model_path)

     常用模型地址如下:

  •  'ner': 'https://nlp.informatik.hu-berlin.de/resources/models/ner/en-ner-conll03-v0.4.pt'
  •  'ner-pooled': 'https://nlp.informatik.hu-berlin.de/resources/models/ner-pooled/en-ner-conll03-pooled-v0.5.pt'
  • 'ner-fast': 'https://nlp.informatik.hu-berlin.de/resources/models/ner-fast/en-ner-fast-conll03-v0.4.pt'
  • 'ner-ontonotes': 'https://nlp.informatik.hu-berlin.de/resources/models/ner-ontonotes/en-ner-ontonotes-v0.4.pt'
  • 'ner-ontonotes-fast': 'https://nlp.informatik.hu-berlin.de/resources/models/ner-ontonotes-fast/en-ner-ontonotes-fast-v0.4.pt'

Q:AttributeError: 'LSTM' object has no attribute '_flat_weights'

A:更新torch版本,改为1.10.0即可

你可能感兴趣的:(NLP,python,开发语言,nlp,NER)