如何加载部分预训练的 pytorch 模型?

hap*_*bit 5 python machine-learning pre-trained-model pytorch spacy-transformers

我正在尝试让 pytorch 模型在句子分类任务上运行。在处理医疗笔记时,我正在使用 ClinicalBert ( https://github.com/kexinhuang12345/clinicalBERT ) 并希望使用其预先训练的权重。不幸的是,ClinicalBert 模型只将文本分类为 1 个二进制标签,而我有 281 个二进制标签。因此,我试图实现此代码https://github.com/kaushaltrivedi/bert-toxic-comments-multilabel/blob/master/toxic-bert-multilabel-classification.ipynb,其中 bert 之后的最终分类器长度为 281。

如何在不加载分类权重的情况下从 ClinicalBert 模型加载预训练的 Bert 权重?

天真地尝试从预训练的 ClinicalBert 权重中加载权重,我收到以下错误:

size mismatch for classifier.weight: copying a param with shape torch.Size([2, 768]) from checkpoint, the shape in current model is torch.Size([281, 768]).
size mismatch for classifier.bias: copying a param with shape torch.Size([2]) from checkpoint, the shape in current model is torch.Size([281]).
Run Code Online (Sandbox Code Playgroud)

我目前尝试从 pytorch_pretrained_bert 包中替换 from_pretrained 函数,并像这样弹出分类器权重和偏差:

def from_pretrained(cls, pretrained_model_name, state_dict=None, cache_dir=None, *inputs, **kwargs):
    ...
    if state_dict is None:
        weights_path = os.path.join(serialization_dir, WEIGHTS_NAME)
        state_dict = torch.load(weights_path, map_location='cpu')
    state_dict.pop('classifier.weight')
    state_dict.pop('classifier.bias')
    old_keys = []
    new_keys = []
    ...
Run Code Online (Sandbox Code Playgroud)

我收到以下错误消息:INFO-modeling_diagnosis-BertForMultiLabelSequenceClassification 的权重未从预训练模型初始化:['classifier.weight', 'classifier.bias']

最后,我想从临床伯特预训练权重中加载 bert 嵌入,并随机初始化顶级分类器权重。

jod*_*dag 8

在加载之前删除状态字典中的键是一个好的开始。假设您用于nn.Module.load_state_dict加载预训练的权重,那么您还需要设置参数strict=False以避免意外或丢失键造成的错误。这将忽略 state_dict 中模型中不存在的条目(意外的键),并且对您来说更重要的是,将保留丢失的条目及其默认初始化(丢失的键)。为了安全起见,您可以检查该方法的返回值,以验证有问题的权重是丢失键的一部分,并且不存在任何意外的键。