使用德语BERT模型时出现'BertModel'无'bert'属性错误求助
解决AttributeError: 'BertModel' object has no attribute 'bert'的问题
错误原因
- 框架不匹配:原仓库代码使用的是TensorFlow版本的
TFBertModel,而你通过AutoModel.from_pretrained加载的是PyTorch版本的BertModel,两者API结构完全不同——PyTorch版的BertModel没有bert这个子模块,直接调用模型本身即可获取输出。 - 调用方式错误:原代码中
model.bert(...)是TensorFlow版TFBertModel的专属写法,不适用于PyTorch版模型。
解决方案(推荐适配TensorFlow框架,与原代码兼容)
步骤1:加载TensorFlow版本的德语BERT模型
将模型加载代码替换为TensorFlow专用的TFAutoModel:
from transformers import TFAutoModel model = TFAutoModel.from_pretrained("dbmdz/bert-base-german-cased")
步骤2:修正模型调用代码
去掉.bert后缀,直接调用模型实例获取输出:
# defining 2 input layers for input_ids and attn_masks input_ids = tf.keras.layers.Input(shape=(256,), name='input_ids', dtype='int32') attn_masks = tf.keras.layers.Input(shape=(256,), name='attention_mask', dtype='int32') # 直接调用model,而非model.bert bert_embds = model(input_ids=input_ids, attention_mask=attn_masks)[1] # 1对应pooled输出 intermediate_layer = tf.keras.layers.Dense(512, activation='relu', name='intermediate_layer')(bert_embds) output_layer = tf.keras.layers.Dense(5, activation='softmax', name='output_layer')(intermediate_layer) sentiment_model = tf.keras.Model(inputs=[input_ids, attn_masks], outputs=output_layer) sentiment_model.summary()
关键说明
TFAutoModel会自动加载对应模型的TensorFlow实现,和原代码的Keras架构完全兼容。- 模型调用返回的元组中,索引
0是所有token的隐藏状态(3D张量),索引1是<[BOS_never_used_51bce0c785ca2f68081bfa7d91973934]>token的池化输出(2D张量),和原代码逻辑一致。
内容的提问来源于stack exchange,提问作者youta
相关产品推荐
相关产品推荐

