训练FinBERT模型报not enough values to unpack错误求解
报错根因
这个报错和attention_mask维度无关,本质是FinBERT模型的前向返回值结构与代码解包逻辑不匹配。
你的代码中写_, pooled_output = self.finbert(...),默认期待模型直接返回包含2个元素的元组:第一个是全token最后一层隐状态,第二个是<[BOS_never_used_51bce0c785ca2f68081bfa7d91973934]>位的池化输出。但当前你使用的HuggingFace Transformers版本中,BERT类模型前向传播返回的是结构化的ModelOutput对象,不是原生元组,直接按位置解包2个值就会触发“需要2个值但只拿到1个”的错误。
异常栈提示错误指向len(train)传参行,是Python异常逐层向上传递的显示问题,不是传参本身有问题,真正的触发点就是FinBERT调用的那行代码。
修复方法
修改SentimentClassifier的forward方法,不要用位置解包拿返回值,显式读取返回对象的pooler_output属性即可,修改后代码:
class SentimentClassifier(nn.Module): def __init__(self, n_classes): super(SentimentClassifier, self).__init__() self.finbert = finbert self.drop = nn.Dropout(p=0.3) self.out = nn.Linear(self.finbert.config.hidden_size, n_classes) def forward(self, input_ids, attention_mask): finbert_output = self.finbert( input_ids=input_ids, attention_mask=attention_mask ) pooled_output = finbert_output.pooler_output output = self.drop(pooled_output) return self.out(output)
其他说明
- 如果后续需要获取所有token的最后一层隐状态,直接读取
finbert_output.last_hidden_state属性即可,不需要按位置解包。 - 你之前排查的attention_mask维度问题是另一类常见报错,本次问题中你确认attention_mask是2维张量,这部分逻辑不需要调整。
内容的提问来源于stack exchange,提问作者Jasmine N
相关产品推荐
相关产品推荐

