【发布时间】:2021-05-05 15:10:02
【问题描述】:
我正在尝试在 python 中加载一个预训练的 FinBERT 模型,但只是尝试加载它时出现错误。我正在关注 GitHub 文档:https://github.com/ProsusAI/finBERT
按照教程,我创建了一个名为bert 的目录,下载了模型pytorch_model.bin 和config.json 文件并将它们放入文件夹中。
我尝试使用以下代码调用模型:
import os
os.chdir(r'bert')
from transformers import BertTokenizer, BertForSequenceClassification
import torch
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
model = BertForSequenceClassification.from_pretrained(r'bert\pytorch_model.bin',
config = r'bert\config.json')
尝试加载的错误如下:
RuntimeError: Error(s) in loading state_dict for BertForSequenceClassification:
size mismatch for classifier.weight: copying a param with shape torch.Size([3, 768]) from checkpoint, the shape in current model is torch.Size([2, 768]).
size mismatch for classifier.bias: copying a param with shape torch.Size([3]) from checkpoint, the shape in current model is torch.Size([2]).
我对此的了解非常基础,如果有人了解这里发生的事情,将不胜感激。
谢谢
【问题讨论】:
-
您的张量需要调整大小:形状不是模型所期望的。
-
@duffymo 谢谢。你有任何材料的链接来告诉我我将如何做到这一点?
-
PyTorch 有一些方法可以让你做到这一点。 “我对此的了解非常基础”——我建议您查看 fast.ai。它为编码人员提供了 8 个视频课程,介绍如何使用 fast.ai 和 PyTorch,非常棒。通过尝试 BERT 模型,您正在跳入深渊。
-
@duffymo 我已经对此进行了研究,但我仍然无法理解的一件事是为什么张量大小不同。我没有定义任何张量大小,所以为什么有一个带有 [2, 768] 的
current model但他们正在尝试加载 [3, 768] 的模型。当然,如果我没有定义任何张量,就不应该存在差异。 -
@duffymo 例如,我已经设法使用
num_labels=3加载模型,但我必须指定它而不是从检查点自动加载似乎很奇怪。