训练T5模型二分类时数据类定义遇解包错误求助
T5二分类任务数据类解包错误解决
问题现象
训练T5模型执行二分类任务时,数据类中batch_size, seq_length = input_shape及掩码长度计算代码触发解包错误:
- 对
input_ids和attention_mask使用unsqueeze(0)时,报错ValueError: too many values to unpack (expected 2) - 使用
squeeze(0)、flatten()或不做维度处理时,报错not enough values to unpack (expected 2, got 1)
调试发现,调用tokenizer.batch_encode_plus处理单条数据后,input_ids的形状为torch.Size([61, 1000]),不符合单条样本的张量维度要求。
核心原因
- 错误使用批量编码方法:数据类的
__getitem__方法负责返回单条样本,但代码中误用了batch_encode_plus(用于批量文本编码),导致返回的张量带批量维度(二维:[样本数, 序列长度]),而非单条样本的一维张量([序列长度])。 - 文本输入格式异常:
str(data_row['question'])将列表型文本转成了字符串形式,被batch_encode_plus误解析为多个单字符样本,导致返回的批量维度为61,进一步加剧维度不匹配问题。
解决方案
- 将单条样本的编码方法从
batch_encode_plus替换为encode_plus,该方法专门处理单条文本,返回一维张量,无需额外维度调整。 - 若
data_row['question']是列表类型,需先将其拼接为单个字符串,而非直接转成字符串(避免被拆分为字符样本)。
修正后的数据类代码
def __init__(self, df: pd.DataFrame, tokenizer:T5Tokenizer, source_max_token_length: int=1000, target_max_token_length: int=400): self.tokenizer=tokenizer self.df=df self.source_max_token_length=source_max_token_length self.target_max_token_length=target_max_token_length def __len__(self): return len(self.df) def __getitem__(self,index: int): data_row=self.df.iloc[index] # 处理源文本:若question是列表,先拼接为字符串 source_text = data_row['question'] if isinstance(source_text, list): source_text = " ".join(map(str, source_text)) else: source_text = str(source_text) source_encoding=self.tokenizer.encode_plus( source_text, max_length=self.source_max_token_length, padding='max_length', truncation=True, return_attention_mask=True, add_special_tokens=True, return_tensors=None # 返回普通列表,后续转为张量 ) # 处理目标文本 target_text = data_row['answers'] if isinstance(target_text, list): target_text = " ".join(map(str, target_text)) else: target_text = str(target_text) target_encoding=self.tokenizer.encode_plus( target_text, max_length=self.target_max_token_length, padding='max_length', truncation=True, return_attention_mask=True, add_special_tokens=True, return_tensors=None ) labels=torch.tensor(target_encoding['input_ids']) labels[labels==0]=-100 return dict( question=data_row['question'], answer_text=data_row['answers'], input_ids=torch.tensor(source_encoding['input_ids']), attention_mask=torch.tensor(source_encoding['attention_mask']), labels=labels )
补充说明
- 若设置
encode_plus的return_tensors='pt',会返回二维张量([1, seq_len]),此时需用squeeze(0)去掉多余的batch维度。 - 确保输入文本为单个字符串,避免批量编码方法误解析输入,导致维度不匹配触发解包错误。
内容的提问来源于stack exchange,提问作者Mariam
相关产品推荐
相关产品推荐

