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

加载Keras模型时遇ValueError:无法识别参数['batch_shape']

Keras模型加载报错:batch_shape参数不识别问题解决

问题重现

执行代码加载模型:

model = tf.keras.models.load_model('/kaggle/input/iyntmodel/vgg19.keras')

触发核心错误:

TypeError: Error when deserializing class 'InputLayer' using config={'batch_shape': [None, 299, 299, 3], 'dtype': 'float32', 'sparse': False, 'name': 'input_layer_1'}.
Exception encountered: Unrecognized keyword arguments: ['batch_shape']

问题原因

新旧Keras版本序列化格式不兼容:旧版本保存模型时会使用batch_shape参数定义输入层,但新版本Keras的InputLayer已移除该参数,改用input_shape + batch_size的组合方式。

解决方案

方案1:匹配模型保存时的TensorFlow版本

安装模型原始保存环境对应的TensorFlow版本,即可正常加载:

pip install tensorflow==x.x.x  # 将x.x.x替换为模型保存时的具体版本号

方案2:自定义InputLayer兼容旧格式

通过custom_objects传入自定义的输入层类,自动转换batch_shape参数:

from tensorflow.keras.layers import InputLayer
from tensorflow.keras.models import load_model

class CustomInputLayer(InputLayer):
    def __init__(self, batch_shape=None, **kwargs):
        if batch_shape:
            batch_size = batch_shape[0]
            input_shape = batch_shape[1:]
            kwargs.update({"batch_size": batch_size, "input_shape": input_shape})
        super().__init__(**kwargs)

# 加载模型时指定自定义类
model = load_model(
    '/kaggle/input/iyntmodel/vgg19.keras',
    custom_objects={'InputLayer': CustomInputLayer}
)

方案3:手动修改模型配置文件

  1. 将.keras模型文件视为压缩包解压,找到config.json文件
  2. 搜索所有"batch_shape"字段,替换为input_shape和batch_size:
    例如将:
    "batch_shape": [None, 299, 299, 3]
    
    修改为:
    "input_shape": [299, 299, 3],
    "batch_size": null
    
  3. 重新打包修改后的文件为.keras格式,再加载模型

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 10:36:00