number of input channels does not match corresponding dimension of filter in Keras

谁说胖子不能爱 提交于 2020-01-07 05:40:15

问题


I am using keras to build a model based on the Resnet50, the following code is shown below

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)  

However, I got an error

'ValueError: number of input channels does not match corresponding dimension of filter, 224 != 3'

how can I fix it?


回答1:


Such errors are routinely produced due to the different image format used by the Theano & TensorFlow backends for Keras. In your case, the images are obviously in channels_first format (Theano), while most probably you use a TensorFlow backend which needs them in channels_last format.

The MNIST CNN example in Keras provides a nice way to make your code immune to such issues, i.e. working for both Theano & TensorFlow backends - here is an adaptation for your data:

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)


来源:https://stackoverflow.com/questions/45909569/number-of-input-channels-does-not-match-corresponding-dimension-of-filter-in-ker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!