自定义Bert模型出现self.init_weights()未解析引用警告如何解决
问题根本原因
你遇到的self.init_weights()未解析属性引用警告基本都是IDE的静态类型检测误报,你继承的BertPreTrainedModel父类在transformers 4.9.1版本中已经内置实现了init_weights()方法,代码实际运行时不会抛出属性不存在的错误。
可选解决方案
- 方案1:直接抑制IDE警告
仅需在警告行上方添加对应IDE的注释即可,不会影响代码运行逻辑:- PyCharm:添加
# noinspection PyUnresolvedReferences - VS Code/Pylance:添加
# type: ignore
示例代码:
# noinspection PyUnresolvedReferences self.init_weights() - PyCharm:添加
- 方案2:显式调用父类方法消除警告
将self.init_weights()改为调用父类实现,IDE可以直接识别到父类方法,不会触发警告:super().init_weights() - 方案3:重写初始化方法(更推荐,适配你新增的分类器)
你可以在MyBert类中重写_init_weights方法,自定义新增的三个分类器的初始化逻辑,和Bert官方初始化规则保持一致,同时消除警告:import torch.nn as nn class MyBert(BertPreTrainedModel): def __init__(self, config, num_labels1=None, num_labels2=None, num_labels3=None): # 原有__init__逻辑不变 super().__init__(config) self.num_labels1 = num_labels1 self.num_labels2 = num_labels2 self.num_labels3 = num_labels3 self.bert = BertModel(config) self.dropout = torch.nn.Dropout(config.hidden_dropout_prob) self.classifier1 = torch.nn.Linear(config.hidden_size, num_labels1) self.classifier2 = torch.nn.Linear(config.hidden_size, num_labels2) self.classifier3 = torch.nn.Linear(config.hidden_size, num_labels3) self.init_weights() def _init_weights(self, module): if isinstance(module, (nn.Linear, nn.Embedding)): module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) elif isinstance(module, nn.LayerNorm): module.bias.data.zero_() module.weight.data.fill_(1.0) if isinstance(module, nn.Linear) and module.bias is not None: module.bias.data.zero_()
验证方式
你可以直接运行模型实例化代码,只要没有抛出AttributeError: 'MyBert' object has no attribute 'init_weights'错误,就证明方法实际存在,仅为IDE误报。
内容的提问来源于stack exchange,提问作者Salvadora
相关产品推荐
相关产品推荐

