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?
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)