named-entity-recognition - 如何使用经过训练的 BERT NER(命名实体识别)模型来预测新示例?
问题描述
我在这篇 Medium 帖子之后训练了自己的 BERT NER:https://medium.com/@yingbiao/ner-with-bert-in-action-936ff275bc73
我将模型保存到光盘并成功加载。
model = BertForTokenClassification.from_pretrained(bert_out_address, num_labels=len(tag2idx))
model.eval() 有效:
model.eval()
我是 BERT 和变压器库的新手。我希望有类似的东西
model.predict('Hello I am an example sentence')
会向我展示公认的实体。
我也试过:
input_ids = torch.tensor([tokenizer.encode("Here is some text to encode")])
output = model(input_ids)
其中输出给了我一个很大的张量,我不知道如何处理它。
我现在如何使用模型来预测例句中的实体?我应该如何处理输出?
谢谢!
解决方案
的文档BertForTokenClassification
说它在softmax之前返回分数,即标签的非标准化概率。
您可以通过从分布中获取最大值来解码标签(应该是维度 2)。这将为您提供最可能标签的索引。在训练模型之前,您将标签转换为索引(使用tag2idx
表格),现在您需要执行相反的过程和 id 的标签。
推荐阅读
- c++ - 要求包括
代替 在链接到 mylibrary 的 Cmake 项目中 - c# - 无法修改 WebRequest 的代理凭据
- vue.js - 我想隐藏我的 API 密钥,但我想同时在 GitHub 页面部署中使用这些密钥
- python-3.x - 解决预算规划师的问题(学校项目)
- java - 字段注入与构造函数注入 - 它对我编写单元测试的方式有何影响?
- nginx - 启用“httpd_can_network_connect”后,将其用作 Grafana 的反向代理时发生 Nginx Bad Gatway 错误
- reactjs - 使用带有动态数据的网格
- amazon-web-services - 无法删除的 EC2 经典资源 - 现在怎么办?
- javascript - 属性分配的Javascript不起作用
- typescript - node_module 中的类型文件夹