在Bert文本分类任务中如何计算并获取预测准确率得分?
BERT分类器预测结果准确率/置信度获取方案
首先修正你现有代码的核心错误:当前你存入true_labels列表的是b_input_mask(注意力掩码,用于标记有效token和padding位),并非样本真实标签,这部分逻辑需要根据你的使用场景调整。
场景1:持有测试集真实标签,计算整体预测准确率
如果是要统计模型在整个测试集上的分类准确率,按以下步骤修改代码:
- 准备和
test_texts一一对应的真实标签列表test_labels - 构造数据集时把真实标签传入:
prediction_data = TensorDataset(input_ids, attention_masks, torch.tensor(test_labels))
- 遍历dataloader时读取真实标签存入
true_labels:
for batch in prediction_dataloader: batch = tuple(t.to(device) for t in batch) b_input_ids, b_input_mask, b_labels = batch with torch.no_grad(): outputs = model(b_input_ids, token_type_ids=None, attention_mask=b_input_mask) logits = outputs[0].detach().cpu().numpy() # 存入真实标签,而非注意力掩码 label_ids = b_labels.detach().cpu().numpy() predictions.append(logits) true_labels.append(label_ids)
- 计算整体准确率百分比:
all_preds = np.concatenate(predictions, axis=0) all_true = np.concatenate(true_labels, axis=0) pred_classes = np.argmax(all_preds, axis=1) # 计算准确率并转百分比格式 accuracy = (np.sum(pred_classes == all_true) / len(all_true)) * 100 print(f"测试集整体准确率:{accuracy:.2f}%")
场景2:线上单条文本预测,获取结果置信度百分比(用于判断是否响应用户)
如果是线上推理场景没有真实标签,你需要的是单条样本预测类别的置信度百分比,按以下逻辑实现:
- 对模型输出的logits做softmax归一化,得到每个类别的概率值
- 取预测类别对应的概率,乘以100得到百分比置信度
代码示例:
# 合并所有预测logits all_logits = np.concatenate(predictions, axis=0) # softmax归一化得到概率分布 probs = torch.nn.functional.softmax(torch.tensor(all_logits), dim=1).numpy() # 单条样本的置信度获取(以第0条为例) pred_class = np.argmax(probs[0]) confidence = probs[0][pred_class] * 100 print(f"预测类别:{pred_class},置信度:{confidence:.2f}%") # 按阈值判断是否响应用户,比如设置阈值为80% if confidence >= 80: # 执行响应用户逻辑 pass else: # 跳过请求,可配置转人工或默认回复 pass
内容的提问来源于stack exchange,提问作者Erdem Eminağa
相关产品推荐
相关产品推荐

