输入通道的数量与 Keras 中过滤器的相应维度不匹配

use*_*624 1 machine-learning neural-network deep-learning conv-neural-network keras

我使用keras搭建基于Resnet50的模型,代码如下

input_crop = Input(shape=(3, 224, 224))

# extract feature from image crop
resnet = ResNet50(include_top=False, weights='imagenet')
for layer in resnet.layers:  # set resnet as non-trainable
    layer.trainable = False

crop_encoded = resnet(input_crop)  
Run Code Online (Sandbox Code Playgroud)

但是,我遇到了错误

'ValueError: 输入通道数与过滤器的对应维度不匹配,224 != 3'

我该如何解决?

des*_*aut 5

由于 Keras 的 Theano 和 TensorFlow后端使用不同的图像格式,经常会产生此类错误。在您的情况下,图像显然是channels_first格式 (Theano),而您很可能使用需要channels_last格式的 TensorFlow 后端。

MNIST CNN例如在Keras提供了一个很好的方法,使你的代码不受这样的问题,即工作都Theano&TensorFlow后端-这里是为您的数据适应:

from keras import backend as K

img_rows, img_cols = 224, 224

if K.image_data_format() == 'channels_first':
    input_crop = input_crop.reshape(input_crop.shape[0], 3, img_rows, img_cols)
    input_shape = (3, img_rows, img_cols)
else:
    input_crop = input_crop.reshape(input_crop.shape[0], img_rows, img_cols, 3)
    input_shape = (img_rows, img_cols, 3)

input_crop = Input(shape=input_shape)
Run Code Online (Sandbox Code Playgroud)