Keras函数式API模型预测输入尺寸不兼容问题的排查与解决
Keras模型预测输入形状不兼容问题解决
问题重现
使用Keras函数式API构建模型:
shape = (128,128,1) input = Input(shape=shape) x = Conv2D(8, kernel_size=(7,7), padding="valid", name='input_conv', activation='relu')(input)
模型训练、保存流程正常,模型摘要显示输入层形状为[(None, 128, 128, 1)],卷积层输出符合预期:
Layer (type) Output Shape Param # ================================================================= input_1 (InputLayer) [(None, 128, 128, 1)] 0 input_conv (Conv2D) (None, 122, 122, 8) 400
加载模型后,传入形状为(128,128,1)的numpy数组执行预测:
print(f'image shape {im.shape} {type(im)}') p = model.predict(im)
触发形状不兼容警告:
image shape (128, 128, 1) <class 'numpy.ndarray'> WARNING:tensorflow:Model was constructed with shape (None, 128, 128, 1) for input KerasTensor(...), but it was called on an input with incompatible shape (32, 128, 1, 1).
问题解析
Keras模型要求输入必须包含批量维度,即标准输入形状为(batch_size, height, width, channels)。直接传入单张图片的(128,128,1)缺少批量维度,model.predict()会自动尝试补全批量维度,但因维度顺序识别错误,导致推断出不符合预期的(32, 128, 1, 1)(32为默认批量大小)。
解决方法
手动为输入添加批量维度,将单张图片形状调整为(1,128,128,1):
p = model.predict(im.reshape(1,128,128,1))
内容的提问来源于stack exchange,提问作者João Silva
相关产品推荐
相关产品推荐

