命名实体识别(NER),也称为标记分类或文本标注,是将句子中的每个单词(或“标记”)分类为不同类别的任务,例如人名或地名,或不同的词性。
例如,给定句子:
芝加哥有巴基斯坦餐厅吗?
一个命名实体识别算法可以识别:
等等。
使用gradio(特别是HighlightedText组件),你可以轻松构建你的NER模型的网页演示,并与团队的其他成员分享。
这是一个你将能够构建的演示示例:
本教程将展示如何采用预训练的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)
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."],
],
)
demo.launch()
你已经完成了!这就是你需要知道的,为你的NER模型构建一个基于Web的GUI。
有趣提示:你可以通过简单地在launch()中设置share=True来立即与他人分享你的NER演示。