nlp - 使用 Huggingface TextClassificationPipeline 时如何设置标签名称?
问题描述
我正在使用带有 TextClassificationPipeline 的微调 Huggingface 模型(在我的公司数据上)来进行类预测。现在,此Pipeline
预测的标签默认为LABEL_0
,LABEL_1
依此类推。有没有办法为TextClassificationPipeline
对象提供标签映射,以便输出反映相同?
环境:
- 张量流==2.3.1
- 变压器==4.3.2
示例代码:
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # or any {'0', '1', '2'}
from transformers import TextClassificationPipeline, TFAutoModelForSequenceClassification, AutoTokenizer
MODEL_DIR = "path\to\my\fine-tuned\model"
# Feature extraction pipeline
model = TFAutoModelForSequenceClassification.from_pretrained(MODEL_DIR)
tokenizer = AutoTokenizer.from_pretrained(MODEL_DIR)
pipeline = TextClassificationPipeline(model=model,
tokenizer=tokenizer,
framework='tf',
device=0)
result = pipeline("It was a good watch. But a little boring.")[0]
输出:
In [2]: result
Out[2]: {'label': 'LABEL_1', 'score': 0.8864616751670837}
解决方案
添加此类映射最简单的方法是编辑模型的 config.json 以包含:id2label
字段,如下所示:
{
"_name_or_path": "distilbert-base-uncased",
"activation": "gelu",
"architectures": [
"DistilBertForMaskedLM"
],
"id2label": [
"negative",
"positive"
],
"attention_dropout": 0.1,
.
.
}
设置此映射的代码内方法是id2label
在调用中添加参数,from_pretrained
如下所示:
model = TFAutoModelForSequenceClassification.from_pretrained(MODEL_DIR, id2label={0: 'negative', 1: 'positive'})
这是我为此提出的Github 问题,以添加到 transformers.XForSequenceClassification 的文档中。
推荐阅读
- python - 使用 Python 编辑 CSV 文件
- svg - html2canvas 不渲染 svg(图表行)
- node.js - nodejs api post方法不起作用,无法/post错误
- mongodb - 在 3.6 之前的 mongo 版本中,$expr 的替代品是什么?
- mysql - 选择表中值的定义出现次数
- reactjs - 如何解决 - 组件重叠
- azure-logic-apps - 有没有办法回到 Azure Logic Apps Actions 的稳定版本?
- python - Pygments 和 ImageFormatter:将输出设置为 80 列
- graphql - 为什么我在运行 Cypress.io 测试时在 GraphQL 查询上被拒绝访问?
- javascript - 如何在我的查询中包含自定义 SELECT