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

如何计算迁移学习BERT模型的准确率?相关代码问题求助

检查JointBERT意图分类准确率的实操方案

针对你用joint_model.predict()未得到预期结果的问题,核心原因是模型输入未遵循训练时的预处理逻辑,且需要明确意图分类准确率的计算步骤。以下是具体解决方法:

1. 对齐输入预处理逻辑

模型基于BERT预训练权重构建,预测前必须对文本做和训练完全一致的编码处理:

  • 加载训练时使用的Tokenizer:
from transformers import BertTokenizer

# 对应Colab中使用的bert-base-uncased预训练模型
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
  • 编写预处理函数,生成模型可识别的输入格式:
def preprocess_input(text, tokenizer, max_seq_len=64):
    encoding = tokenizer.encode_plus(
        text,
        add_special_tokens=True,
        max_length=max_seq_len,
        return_token_type_ids=False,
        padding='max_length',
        truncation=True,
        return_attention_mask=True,
        return_tensors='pt'
    )
    return {
        'input_ids': encoding['input_ids'].flatten(),
        'attention_mask': encoding['attention_mask'].flatten()
    }

2. 准备测试数据与真实标签

如果使用Colab中拆分好的测试集,先提取文本和对应意图标签,并将标签转换为模型可匹配的索引:

import torch
from sklearn.preprocessing import LabelEncoder

# 假设test_df是你的测试数据集,包含text和intent列
test_texts = test_df['text'].tolist()
true_intents = test_df['intent'].tolist()

# 复用训练时的LabelEncoder(若训练时已保存,直接加载即可)
label_encoder = LabelEncoder()
label_encoder.fit(true_intents)
true_intent_ids = label_encoder.transform(true_intents)

3. 批量预测并计算准确率

切换模型到评估模式,批量处理测试数据后计算准确率:

from sklearn.metrics import accuracy_score

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
joint_model.to(device)
joint_model.eval()

predicted_intent_ids = []

with torch.no_grad():
    for text in test_texts:
        inputs = preprocess_input(text, tokenizer)
        # 添加batch维度,适配模型输入要求
        input_ids = inputs['input_ids'].unsqueeze(0).to(device)
        attention_mask = inputs['attention_mask'].unsqueeze(0).to(device)
        
        # JointBERT输出为(意图分类logits, 槽填充logits)
        intent_logits, _ = joint_model(input_ids=input_ids, attention_mask=attention_mask)
        
        # 取logits最大值对应的索引作为预测结果
        pred_id = torch.argmax(intent_logits, dim=1).item()
        predicted_intent_ids.append(pred_id)

# 计算并打印准确率
accuracy = accuracy_score(true_intent_ids, predicted_intent_ids)
print(f"意图分类准确率: {accuracy:.4f}")

修复joint_model.predict()的使用方式

若要直接调用predict方法,需将测试数据封装为Dataset和DataLoader,匹配模型训练时的输入批量格式:

from torch.utils.data import Dataset, DataLoader

class IntentTestDataset(Dataset):
    def __init__(self, texts, tokenizer, max_seq_len=64):
        self.texts = texts
        self.tokenizer = tokenizer
        self.max_seq_len = max_seq_len
    
    def __len__(self):
        return len(self.texts)
    
    def __getitem__(self, idx):
        return preprocess_input(self.texts[idx], self.tokenizer, self.max_seq_len)

# 构建测试数据集与加载器
test_dataset = IntentTestDataset(test_texts, tokenizer)
test_dataloader = DataLoader(test_dataset, batch_size=8)

# 批量预测
predicted_intent_ids = []
joint_model.eval()
with torch.no_grad():
    for batch in test_dataloader:
        input_ids = batch['input_ids'].to(device)
        attention_mask = batch['attention_mask'].to(device)
        intent_logits, _ = joint_model(input_ids=input_ids, attention_mask=attention_mask)
        pred_ids = torch.argmax(intent_logits, dim=1).tolist()
        predicted_intent_ids.extend(pred_ids)

# 计算准确率
accuracy = accuracy_score(true_intent_ids, predicted_intent_ids)
print(f"意图分类准确率: {accuracy:.4f}")

关键注意点

  • 必须复用训练时的Tokenizer和LabelEncoder,否则会出现标签映射错误或输入格式不兼容问题。
  • 预测前务必调用joint_model.eval(),关闭训练时的dropout等正则化层。
  • 单条文本预测时,需用unsqueeze(0)添加batch维度,否则模型会报错。

内容的提问来源于stack exchange,提问作者Lahiru Sammika

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 16:09:25