Gui*_*lau 6 python deep-learning pytorch bert-language-model huggingface-transformers
我刚刚在由电子商务网站的产品和标签(部门)组成的数据集上训练了 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]).
Run Code Online (Sandbox Code Playgroud)
我发现问题可能是两个数据集之间的标签大小不匹配。我进行了一些搜索,找到了使用ignore_mismatched_sizes=True
as 和 argument for 的建议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)
Run Code Online (Sandbox Code Playgroud)
有人可以帮助我如何处理吗?我不知道我还能做什么!
任何帮助我都非常感激!
您的新数据集有 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)
Run Code Online (Sandbox Code Playgroud)
如果你想保留59个标签的分类层并添加46个标签,可以参考这个答案。另请注意此答案的评论,因为由于新标签的随机初始化,此方法不会提供任何有意义的结果。
归档时间: |
|
查看次数: |
7617 次 |
最近记录: |