TensorFlow加载MobileNetV2.h5模型时遇DepthwiseConv2D参数错误
解决TensorFlow加载MobileNetV2模型时的DepthwiseConv2D 'groups'参数错误
问题场景
从GitHub获取人脸反欺诈MobileNetV2模型(.h5格式),上传至Colab后尝试加载并转换为CoreML格式,执行代码时触发错误:ValueError: Unrecognized keyword arguments passed to DepthwiseConv2D: {'groups': 1}。将TensorFlow从2.17降级至2.16后问题仍未解决。
执行代码
import tensorflow as tf import coremltools as ct model = tf.keras.models.load_model('/content/MobileNetV2.h5') print(model.summary())
完整报错信息
ValueError Traceback (most recent call last) /usr/local/lib/python3.10/dist-packages/keras/src/ops/operation.py in from_config(cls, config) 233 try: --> 234 return cls(**config) 235 except Exception as e: 16 frames ValueError: Unrecognized keyword arguments passed to DepthwiseConv2D: {'groups': 1} During handling of the above exception, another exception occurred: TypeError Traceback (most recent call last) /usr/local/lib/python3.10/dist-packages/keras/src/ops/operation.py in from_config(cls, config) 234 return cls(**config) 235 except Exception as e: --> 236 raise TypeError( 237 f"Error when deserializing class '{cls.__name__}' using " 238 f"config={config}.\n\nException encountered: {e}" TypeError: Error when deserializing class 'DepthwiseConv2D' using config={'name': 'expanded_conv_depthwise', 'trainable': True, 'dtype': 'float32', 'kernel_size': [3, 3], 'strides': [1, 1], 'padding': 'same', 'data_format': 'channels_last', 'dilation_rate': [1, 1], 'groups': 1, 'activation': 'linear', 'use_bias': False, 'bias_initializer': {'class_name': 'Zeros', 'config': {}}, 'bias_regularizer': None, 'activity_regularizer': None, 'bias_constraint': None, 'depth_multiplier': 1, 'depthwise_initializer': {'class_name': 'GlorotUniform', 'config': {'seed': None}}, 'depthwise_regularizer': None, 'depthwise_constraint': None}.
原因分析
模型保存时使用的TensorFlow/Keras版本,在DepthwiseConv2D层中写入了groups参数,但当前环境的Keras版本不支持该参数——DepthwiseConv2D本质是逐通道卷积,groups默认等于输入通道数,无需额外指定。
解决方法
方法1:自定义加载逻辑过滤无效参数
在加载模型时传入自定义对象处理函数,移除不支持的groups参数:
import tensorflow as tf from tensorflow.keras.layers import DepthwiseConv2D def custom_depthwise_conv2d(config): # 移除groups参数(如果存在) config.pop('groups', None) return DepthwiseConv2D.from_config(config) # 加载模型时指定自定义解析逻辑 model = tf.keras.models.load_model( '/content/MobileNetV2.h5', custom_objects={'DepthwiseConv2D': custom_depthwise_conv2d} ) print(model.summary())
方法2:匹配模型保存时的TensorFlow版本
查找模型原始保存时使用的TensorFlow版本,在Colab中安装对应版本:
!pip install tensorflow==x.x.x
将x.x.x替换为模型保存时的具体版本号,安装完成后重新加载模型即可。
方法3:重新导出模型(若有原始训练权限)
如果能获取模型的原始训练代码,在当前环境重新训练并保存模型,或用当前版本的Keras重新导出.h5文件,从根源避免参数兼容问题。
内容的提问来源于stack exchange,提问作者Sai Balaji K
相关产品推荐
相关产品推荐

