Gradio 月用户量达到 100 万的历程!
阅读更多Gradio 月用户量达到 100 万的历程!
阅读更多命名实体识别 (NER),也称为 token 分类或文本标记,是将句子中的每个词(或“token”)分类到不同类别的任务,例如人名或地名,或不同的词性。
例如,给定句子
芝加哥有巴基斯坦餐厅吗?
一个命名实体识别算法可能会识别出
等等。
使用 `gradio`(特别是 `HighlightedText` 组件),你可以轻松构建 NER 模型的 Web 演示,并与你的团队其他成员分享。
这是一个你可以构建的演示示例
本教程将展示如何使用预训练的 NER 模型,并使用 Gradio 界面进行部署。我们将展示使用 `HighlightedText` 组件的两种不同方法 —— 根据你的 NER 模型,这两种方法中的任何一种都可能更容易学习!
确保你已经 安装 了 gradio
Python 包。你还需要一个预训练的命名实体识别模型。你可以使用你自己的模型,在本教程中,我们将使用来自 transformers
库的模型。
许多命名实体识别模型输出一个字典列表。每个字典都包含一个 _实体_、一个“start”索引和一个“end”索引。例如,这是 `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 演示。