求助:XLNetForQuestionAnsweringOutput无法获取start_logits/end_logits属性
解决XLNet问答模型评估中的AttributeError问题
问题背景
使用Transformers库中的XLNet进行问答模型评估时,触发AttributeError错误,提示'XLNetForQuestionAnsweringOutput' object has no attribute 'start_logits'。排查后发现该输出对象仅包含start_top_index、end_top_index等属性,需要获取start_logits和end_logits以完成后续准确率计算。
原评估代码
import torch from torch.utils.data import DataLoader, TensorDataset, random_split from transformers import get_linear_schedule_with_warmup import time import datetime import numpy as np # 补充原代码遗漏的numpy导入 # 将模型切换为评估模式 model.eval() # 跟踪用于计算准确率和损失的变量 total_eval_accuracy = 0 total_eval_loss = 0 nb_eval_steps = 0 # 记录开始时间 t0 = time.time() # 无需计算或保存梯度 with torch.no_grad(): for batch in test_dataloader: batch = tuple(t.to(device) for t in batch) b_input_ids, b_attention_mask, b_start_positions, b_end_positions, _ = batch outputs = model(b_input_ids, attention_mask=b_attention_mask, start_positions=b_start_positions, end_positions=b_end_positions) loss = outputs.loss total_eval_loss += loss.item() # 获取起始和结束位置的预测logits start_logits = outputs.start_logits.detach().cpu().numpy() end_logits = outputs.end_logits.detach().cpu().numpy() start_positions = b_start_positions.to('cpu').numpy() end_positions = b_end_positions.to('cpu').numpy() # 将logits转换为预测索引 start_preds = np.argmax(start_logits, axis=-1) end_preds = np.argmax(end_logits, axis=-1) # 计算当前批次的准确率 eval_accuracy = (np.sum(start_preds == start_positions) + np.sum(end_preds == end_positions)) / (len(start_preds) + len(end_preds)) total_eval_accuracy += eval_accuracy # 计算并输出评估指标 avg_loss = total_eval_loss / len(test_dataloader) avg_accuracy = total_eval_accuracy / len(test_dataloader) total_time = format_time(time.time() - t0) print(f"Accuracy: {avg_accuracy:.2f}") print(f"Average Test Loss: {avg_loss:.2f}") print(f"Testing took: {total_time}")
报错信息
Bug: Cell In[18], line 26 23 total_eval_loss += loss.item() 25 # 获取起始和结束位置的预测logits ---> 26 start_logits = outputs.start_logits.detach().cpu().numpy() 27 end_logits = outputs.end_logits.detach().cpu().numpy() 28 start_positions = b_start_positions.to('cpu').numpy() AttributeError: 'XLNetForQuestionAnsweringOutput' object has no attribute 'start_logits'
解决方案
问题原因
XLNetForQuestionAnswering默认采用beam search策略返回top-k的预测结果(对应start_top_index、end_top_index等属性),而非完整的logits矩阵,因此直接访问start_logits会触发属性不存在的错误。
修改步骤
在调用模型时添加start_n_top=0和end_n_top=0参数,强制模型返回完整的起始/结束位置logits,同时明确设置return_dict=True确保输出结构规范:
outputs = model( b_input_ids, attention_mask=b_attention_mask, start_positions=b_start_positions, end_positions=b_end_positions, start_n_top=0, # 获取完整的start logits,而非top-k结果 end_n_top=0, # 获取完整的end logits,而非top-k结果 return_dict=True )
补充说明
- 设置
start_n_top=0和end_n_top=0后,模型将不再返回start_top_index、start_top_log_probs等beam search相关属性,转而返回完整的start_logits和end_logits。 - 原代码遗漏了
numpy的导入,需在开头补充import numpy as np,否则np.argmax会触发错误。
内容的提问来源于stack exchange,提问作者Huy Lâm Thiều
相关产品推荐
相关产品推荐

