1. 其他教程
  2. 命名实体识别

命名实体识别

简介

命名实体识别 (NER),也称为词语分类或文本标记,是将一个句子并将其每个词(或“词元”)分类到不同类别中的任务,例如人名、地名或不同的词性。

例如,给定句子

芝加哥有巴基斯坦餐馆吗?

命名实体识别算法可能会识别出

  • "芝加哥" 为 地点
  • "巴基斯坦" 为 族裔

等等。

使用 gradio(特别是 HighlightedText 组件),您可以轻松构建 NER 模型 Web 演示并与团队共享。

以下是您可以构建的演示示例

本教程将展示如何使用预训练的 NER 模型,并用 Gradio 界面进行部署。我们将展示使用 HighlightedText 组件的两种不同方式——根据您的 NER 模型,这两种方式中的任何一种都可能更容易学习!

前提条件

请确保您已 安装 gradio Python 包。您还需要一个预训练的命名实体识别模型。您可以使用自己的模型,而在本教程中,我们将使用 transformers 库中的一个。

方法一:实体字典列表

许多命名实体识别模型会输出一个字典列表。每个字典包含一个“实体”、“开始”索引和“结束”索引。例如,transformers 库中的 NER 模型就是这样操作的。

from transformers import pipeline
ner_pipeline = pipeline("ner")
ner_pipeline("Does Chicago have any Pakistani restaurants")

输出

[{'entity': 'I-LOC',
  'score': 0.9988978,
  'index': 2,
  'word': 'Chicago',
  'start': 5,
  'end': 12},
 {'entity': 'I-MISC',
  'score': 0.9958592,
  'index': 5,
  'word': 'Pakistani',
  'start': 22,
  'end': 31}]

如果您有这样的模型,将其连接到 Gradio 的 HighlightedText 组件非常容易。您只需要将这个实体列表原始文本一起作为字典传入模型,键分别为 "entities""text"

这是一个完整的示例

from transformers import pipeline

import gradio as gr

ner_pipeline = pipeline("ner")  

examples = [
    "Does Chicago have any stores and does Joe live here?",
]

def ner(text):
    output = ner_pipeline(text)
    return {"text": text, "entities": output}

demo = gr.Interface(ner,
             gr.Textbox(placeholder="Enter sentence here..."),
             gr.HighlightedText(),
             examples=examples,
             api_name="predict")

demo.launch()

方法二:元组列表

将数据传入 HighlightedText 组件的另一种方式是使用元组列表。每个元组的第一个元素应该是被分类为特定实体的词或词语。第二个元素应该是实体标签(如果应标记为无标签,则为 None)。HighlightedText 组件会自动将词语和标签连接起来以显示实体。

在某些情况下,这比第一种方法更容易。下面是一个使用 Spacy 的词性标注器演示此方法的示例

import gradio as gr
import os
os.system('python -m spacy download en_core_web_sm')
import spacy  
from spacy import displacy  

nlp = spacy.load("en_core_web_sm")

def text_analysis(text):
    doc = nlp(text)
    html = displacy.render(doc, style="dep", page=True)
    html = (
        "<div style='max-width:100%; max-height:360px; overflow:auto'>"
        + html
        + "</div>"
    )
    pos_count = {
        "char_count": len(text),
        "token_count": 0,
    }
    pos_tokens = []

    for token in doc:
        pos_tokens.extend([(token.text, token.pos_), (" ", None)])

    return pos_tokens, pos_count, html

demo = gr.Interface(
    text_analysis,
    gr.Textbox(placeholder="Enter sentence here..."),
    ["highlight", "json", "html"],
    examples=[
        ["What a beautiful morning for a walk!"],
        ["It was the best of times, it was the worst of times."],
    ],
    api_name="predict",
)

demo.launch()


您就完成了!这就是构建 NER 模型 Web GUI 所需了解的一切。

趣味提示:您可以通过将 launch() 中的 share=True 设置为 True,立即与他人分享您的 NER 演示。

gradio