You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否基于NVIDIA NeMo文本分类模型计算预测置信度分数?

可以计算预测结果的置信度分数

NeMo文本分类模型的前向输出本身就包含计算置信度需要的全部信息,不需要额外修改模型结构。
你现有代码里outputs[0]是模型输出的每个类别的原始logits值,对这部分张量在类别维度做softmax归一化,就能得到样本属于每个类别的概率分布,预测标签对应的概率值就是该预测结果的置信度。

代码修改方法

你原有的准确率计算逻辑不需要调整,只需要补充softmax计算、提取对应概率的步骤即可,修改后的参考代码:

import torch
import torch.nn.functional as F

# Test the model
with torch.no_grad():
    correct = 0
    total = 0
    # 按需新增列表存储所有样本的预测结果、对应置信度
    pred_results = []
    conf_scores = []
    for i, batch in enumerate(validation_dataloader):
        batch = tuple(t.to(device) for t in batch)
        # Unpack the inputs from our dataloader
        b_input_ids, b_input_mask, b_labels = batch
        # Forward pass
        outputs = model(b_input_ids, token_type_ids=None, attention_mask=b_input_mask)
        logits = outputs[0]
        # 在类别维度做softmax得到概率分布
        cls_probs = F.softmax(logits, dim=1)
        # 同时取最大概率值(置信度)和对应预测类别
        prediction_conf, prediction = torch.max(cls_probs, dim=1)
        total += b_labels.size(0)
        correct += (prediction==b_labels).sum().item()
        # 保存结果,移到CPU方便后续处理
        pred_results.extend(prediction.cpu().tolist())
        conf_scores.extend(prediction_conf.cpu().tolist())

print('Test Accuracy of the model on the data is: {} %'.format(100 * correct / total))

注意事项

  • 做softmax时必须指定dim=1,这个维度对应类别维度,如果传错维度会得到完全错误的概率值。
  • 如果你需要获取TopN个类别的标签和对应置信度,把torch.max替换为torch.topk(cls_probs, k=N, dim=1)即可,会返回前N个概率值和对应类别索引。
  • 输出的置信度取值范围为0~1,数值越接近1代表模型对当前预测结果的确定程度越高。

内容的提问来源于stack exchange,提问作者Rashmi Yadav

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 06:54:30