You need to enable JavaScript to run this app. 如何向DistilBERT传递候选类别名称以完成文本分类任务
优惠活动
大模型
产品
解决方案
定价
更多

如何向DistilBERT传递候选类别名称以完成文本分类任务

基于DistilBERT-MNLI获取三分类蕴含度的PyTorch实现

你使用的typeform/distilbert-base-uncased-mnli是基于MNLI数据集微调的零样本分类模型,核心输入格式为「前提-假设」配对:待分类文本作为前提,单个候选类别作为假设,模型输出对应假设和前提的蕴含、中立、矛盾三类概率,我们取蕴含概率作为对应类别的匹配分值。你之前拼接所有类别的输入方式不符合模型训练时的输入规范,无法得到正确结果。

完整实现代码

import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification

# 加载模型与分词器,参数替换为你本地的模型存储路径即可
tokenizer = AutoTokenizer.from_pretrained("typeform/distilbert-base-uncased-mnli")
model = AutoModelForSequenceClassification.from_pretrained("typeform/distilbert-base-uncased-mnli")
model.eval()

# 待分类文本与自定义候选类别
input_text = "which stocks will go down during new years"
candidate_labels = ["positive", "neutral", "negative"]
entailment_scores = {}

# 推理阶段关闭梯度计算,降低显存占用
with torch.no_grad():
    for label in candidate_labels:
        # 构造前提-假设配对输入
        encoded_input = tokenizer(
            input_text,
            f"This text is {label}",
            return_tensors="pt",
            truncation=True,
            max_length=512
        )
        outputs = model(**encoded_input)
        # softmax归一化后取ENTAILMENT对应索引0的概率作为蕴含度
        probs = torch.nn.functional.softmax(outputs.logits, dim=-1)
        entailment_scores[label] = probs[0][0].item()

print("各候选类别蕴含度:", entailment_scores)

批量优化版本

如果候选类别较多,可以用批量输入的方式省略循环,提升推理效率:

with torch.no_grad():
    encoded_input = tokenizer(
        [input_text] * len(candidate_labels),
        [f"This text is {label}" for label in candidate_labels],
        return_tensors="pt",
        truncation=True,
        max_length=512,
        padding=True
    )
    outputs = model(**encoded_input)
    probs = torch.nn.functional.softmax(outputs.logits, dim=-1)
    entailment_scores = dict(zip(candidate_labels, probs[:, 0].tolist()))

print("批量处理结果:", entailment_scores)

内容的提问来源于stack exchange,提问作者William Gazeley

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 00:54:03