【问题标题】:Mismatched size on BertForSequenceClassification from Transformers and multiclass problem来自 Transformers 和多类问题的 BertForSequenceClassification 大小不匹配
【发布时间】:2021-11-10 15:11:12
【问题描述】:

我刚刚在一个由电子商务网站的产品和标签(部门)组成的数据集上训练了一个 BERT 模型。这是一个多类问题。我使用 BertForSequenceClassification 来预测每个产品的部门。我将它分为训练和评估,我使用了 pytorch 的数据加载器,我得到了很好的分数,没有过拟合。

现在我想在一个新的数据集上尝试它,以检查它如何处理看不见的数据。但是我无法加载模型并应用于新的数据集。我收到以下错误:

RuntimeError: Error(s) in loading state_dict for BertForSequenceClassification:
    size mismatch for classifier.weight: copying a param with shape torch.Size([59, 1024]) from checkpoint, the shape in current model is torch.Size([105, 1024]).
    size mismatch for classifier.bias: copying a param with shape torch.Size([59]) from checkpoint, the shape in current model is torch.Size([105]).

我发现问题可能是两个数据集之间的标签大小不匹配。我进行了一些搜索,发现了使用ignore_mismatched_sizes=True 作为pretrained 的参数的建议。但我一直收到同样的错误。

这是我尝试预测看不见的数据时的部分代码:

from transformers import BertForSequenceClassification

# Just right before the actual usage select your hardware
device = torch.device('cuda') # or cpu
model = model.to(device)      # send your model to your hardware



model = BertForSequenceClassification.from_pretrained("neuralmind/bert-large-portuguese-cased",
                                                      num_labels=len(label_dict),
                                                      output_attentions=False,
                                                      output_hidden_states=False,
                                                      ignore_mismatched_sizes=True)

model.to(device)

model.load_state_dict(torch.load('finetuned_BERT_epoch_2_full-Copy1.model', map_location=torch.device('cuda')))

_, predictions, true_vals = evaluate(dataloader_validation)
accuracy_per_class(predictions, true_vals)

有人可以帮助我如何处理它吗?我不知道我还能做什么!

任何帮助我都非常感谢!

【问题讨论】:

    标签: python deep-learning pytorch huggingface-transformers bert-language-model


    【解决方案1】:

    您的新数据集包含 105 个类别,而您的模型针对 59 个类别进行了训练。正如您已经提到的,您可以使用ignore_mismatched_sizes 来加载您的模型。此参数将加载模型的嵌入和编码层,但会随机初始化分类头:

    model = BertForSequenceClassification.from_pretrained("finetuned_BERT_epoch_2_full-Copy1.model",
                                                          num_labels=105,
                                                          output_attentions=False,
                                                          output_hidden_states=False,
                                                          ignore_mismatched_sizes=True)
    

    如果你想保留59个标签的分类层并添加46个标签,你可以参考这个answer。另请注意此答案的 cmets,因为由于新标签的随机初始化,此方法无法提供任何有意义的结果。

    【讨论】:

    • 谢谢。我只需要像您一样指定确切的num_labels。并感谢您对另一个答案的参考,稍后会对我有所帮助。
    猜你喜欢
    • 2021-03-22
    • 2022-01-23
    • 1970-01-01
    • 2020-07-14
    • 2016-07-03
    • 2013-03-15
    • 2023-03-23
    • 2021-05-06
    • 1970-01-01
    相关资源
    最近更新 更多