导出Teachable Machine模型后本地加载报错:DepthwiseConv2D参数异常
Teachable Machine导出h5模型本地加载报错解决
报错信息
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': 'VarianceScaling', 'config': {'scale': 1, 'mode': 'fan_avg', 'distribution': 'uniform', 'seed': None}}, 'depthwise_regularizer': None, 'depthwise_constraint': None}. Exception encountered: Unrecognized keyword arguments passed to DepthwiseConv2D: {'groups': 1}
本地部署代码
from keras.models import load_model # TensorFlow is required for Keras to work from PIL import Image, ImageOps # Install pillow instead of PIL import numpy as np # Disable scientific notation for clarity np.set_printoptions(suppress=True) # Load the model model = load_model("keras_model.h5", compile=False) # Load the labels class_names = open("labels.txt", "r").readlines() # Create the array of the right shape to feed into the keras model # The 'length' or number of images you can put into the array is # determined by the first position in the shape tuple, in this case 1 data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32) # Replace this with the path to your image image = Image.open("jap span.jfif").convert("RGB") # resizing the image to be at least 224x224 and then cropping from the center size = (224, 224) image = ImageOps.fit(image, size, Image.Resampling.LANCZOS) # turn the image into a numpy array image_array = np.asarray(image) # Normalize the image normalized_image_array = (image_array.astype(np.float32) / 127.5) - 1 # Load the image into the array data[0] = normalized_image_array # Predicts the model prediction = model.predict(data) index = np.argmax(prediction) class_name = class_names[index] confidence_score = prediction[0][index] # Print prediction and confidence score print("Class:", class_name[2:], end="") print("Confidence Score:", confidence_score)
问题原因
Teachable Machine云端使用的是较新版本的TensorFlow,导出的模型配置中给DepthwiseConv2D层添加了groups参数,但本地环境安装的TensorFlow/Keras版本较低,该版本的DepthwiseConv2D不支持groups参数,导致反序列化模型时报错。
解决方案
方案1:升级TensorFlow版本
直接升级本地的TensorFlow到兼容版本(建议2.10及以上),执行以下命令:
pip install --upgrade tensorflow
升级完成后重新运行代码即可。
方案2:自定义兼容层(无需升级版本)
如果无法升级环境,可以自定义一个忽略groups参数的DepthwiseConv2D层,加载模型时替换原层:
修改模型加载部分的代码为以下内容:
from keras.models import load_model from keras.layers import DepthwiseConv2D from keras.utils import get_custom_objects import numpy as np from PIL import Image, ImageOps # 自定义兼容的DepthwiseConv2D层,移除不识别的groups参数 class CustomDepthwiseConv2D(DepthwiseConv2D): def __init__(self, *args, **kwargs): kwargs.pop('groups', None) super().__init__(*args, **kwargs) # 注册自定义层 get_custom_objects()['DepthwiseConv2D'] = CustomDepthwiseConv2D # Disable scientific notation for clarity np.set_printoptions(suppress=True) # Load the model model = load_model("keras_model.h5", compile=False) # 后续代码保持不变...
这样加载模型时会自动忽略groups参数,不影响模型的预测功能。
内容的提问来源于stack exchange,提问作者Akshay Prakash
相关产品推荐
相关产品推荐

