huggingface-transformers - 如何从拥抱脸应用预训练的变压器模型?
问题描述
我有兴趣将 Huggingface 的预训练模型用于命名实体识别 (NER) 任务,而无需进一步训练或测试模型。
在HuggingFace 的模型页面上,模型复用的唯一信息如下:
from transformers import AutoTokenizer, AutoModel
tokenizer = AutoTokenizer.from_pretrained("emilyalsentzer/Bio_ClinicalBERT")
model = AutoModel.from_pretrained("emilyalsentzer/Bio_ClinicalBERT")
我尝试了以下代码,但我得到的是张量输出,而不是每个命名实体的类标签。
from transformers import AutoTokenizer, AutoModel
tokenizer = AutoTokenizer.from_pretrained("emilyalsentzer/Bio_ClinicalBERT")
model = AutoModel.from_pretrained("emilyalsentzer/Bio_ClinicalBERT")
text = "my text for named entity recognition here."
input_ids = torch.tensor(tokenizer.encode(text, padding=True, truncation=True,max_length=50, add_special_tokens = True)).unsqueeze(0)
with torch.no_grad():
output = model(input_ids, output_attentions=True)
关于如何将模型应用于 NER 文本的任何建议?
解决方案
您正在寻找命名实体识别管道(令牌分类):
from transformers import AutoTokenizer, pipeline, AutoModelForTokenClassification
tokenizer = AutoTokenizer.from_pretrained("emilyalsentzer/Bio_ClinicalBERT")
model = AutoModelForTokenClassification.from_pretrained("emilyalsentzer/Bio_ClinicalBERT")
nerpipeline = pipeline('ner', model=model, tokenizer=tokenizer)
text = "my text for named entity recognition here."
nerpipeline(text)
输出:
[{'word': 'my',
'score': 0.5209763050079346,
'entity': 'LABEL_0',
'index': 1,
'start': 0,
'end': 2},
{'word': 'text',
'score': 0.5161970257759094,
'entity': 'LABEL_0',
'index': 2,
'start': 3,
'end': 7},
{'word': 'for',
'score': 0.5297629237174988,
'entity': 'LABEL_1',
'index': 3,
'start': 8,
'end': 11},
{'word': 'named',
'score': 0.5258920788764954,
'entity': 'LABEL_1',
'index': 4,
'start': 12,
'end': 17},
{'word': 'entity',
'score': 0.5415489673614502,
'entity': 'LABEL_1',
'index': 5,
'start': 18,
'end': 24},
{'word': 'recognition',
'score': 0.5396601557731628,
'entity': 'LABEL_1',
'index': 6,
'start': 25,
'end': 36},
{'word': 'here',
'score': 0.5165827870368958,
'entity': 'LABEL_0',
'index': 7,
'start': 37,
'end': 41},
{'word': '.',
'score': 0.5266348123550415,
'entity': 'LABEL_0',
'index': 8,
'start': 41,
'end': 42}]
请注意,您需要使用AutoModelForTokenClassification
而不是,AutoModel
并且并非所有模型都具有经过训练的令牌分类头(即您将获得令牌分类头的随机权重)。
推荐阅读
- selenium - 如何在 selenium web 驱动程序中切换到框架内的框架集
- javascript - 不能使用 If - Else 元素存在于 Javascript 中
- tensorflow - 如何在 keras 中定义和使用自定义损失函数
- select - SQL 更改所有项目
- python - 在 Greenplum(Postgres 8.4)中进行多行更新时跟踪错误记录?
- flutter - 添加 'value:' 参数时出现 DropdownButton 异常。“package:flutter/material.dart/dropdown.dart 断言失败”
- gcc - 我需要使用哪些 C 指令来让 gcc 的 x86-64 自动矢量化器输出 pshufb 操作码?
- windows - .text 和 .itext 内存段有什么区别?
- python - 如何将 Pandas DataFrame 的列转换为单独的 dicts,其中 dictnames 是列名?
- firebase - 如何使用 Flutter 和 Firebase 创建条带标准帐户