You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TF2.6加载含BERT的tf.keras模型报错ValueError:嵌套结构不一致

错误根源

这个报错是HuggingFace Transformers库的TFBertModel和TensorFlow Keras序列化逻辑不兼容导致的:你调用bert层时直接按位置传入两个输入张量,Keras保存模型时记录的输入结构是两个独立张量,但BERT层的call方法默认也支持第一个参数为包含input_ids、attention_mask的字典,加载时结构校验不匹配就触发了该错误。

解决步骤
  1. 调整BERT层的调用方式,不要用位置参数传attention_mask,改为显式指定关键字参数,对应修改代码中的输出计算行:
# 原错误写法
# txt12_outputs = bert(txt12_input_ids, txt12_mask).pooler_output
# 修改后写法
txt12_outputs = bert(txt12_input_ids, attention_mask=txt12_mask).pooler_output

你也可以直接把输入打包为字典传入,效果一致:

bert_inputs = {
    "input_ids": txt12_input_ids,
    "attention_mask": txt12_mask
}
txt12_outputs = bert(bert_inputs).pooler_output
  1. 若调整调用方式后加载仍有报错,加载模型时显式传入自定义层声明即可:
from transformers import TFBertModel
model_2 = tf.keras.models.load_model(dir_path+'Prob', custom_objects={"TFBertModel": TFBertModel})

内容的提问来源于stack exchange,提问作者Nadja

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 10:03:04