Home > Mobile >  Tensorflow / Keras ValueError: Input 0 of layer "model" is incompatible with the layer: ex
Tensorflow / Keras ValueError: Input 0 of layer "model" is incompatible with the layer: ex

Time:09-30

I checked all the other similar errors but no one worked. I'm doing transfer learning from resnet50 model in keras. This is how I created the model:

    inputs = keras.Input(shape=input_shape, dtype=tf.float32)

    augmentation_layer = Sequential([
        layers.RandomFlip(**data_aug_layer["random_flip"]),
        layers.RandomRotation(**data_aug_layer["random_rotation"]),
        layers.RandomZoom(**data_aug_layer["random_zoom"]),
    ])

    x = augmentation_layer(inputs)
    x = preprocess_input(x)
    
    scale_layer = layers.Rescaling(scale=1./255)
    x = scale_layer(x)
   
    base_model=ResNet50(
        include_top=False,
        weights='imagenet',
        pooling='avg',
        input_shape=input_shape
        )
    x = base_model(x, training=False)
    x = layers.Dropout(dropout_rate)(x)
    outputs=layers.Dense(classes, activation='softmax')(x)
    model = Model(inputs, outputs)

After training, I saved the weights and loaded them and do the image preprocessing again:

def norma(arr):
    normalization_layer = layers.Rescaling(1./255)
    return normalization_layer(arr)

ims=keras.utils.load_img(test_files[0], target_size=(224, 224))
im_arr=keras.utils.img_to_array(ims)
im_arr_preproc=tf.keras.applications.resnet.preprocess_input(im_arr)
im_arr_scaled = norma(im_arr_preproc)

WEIGHTS="/home/app/src/experiments/exp_007/model.01-5.2777.h5"
wg_model = resnet_50.create_model(weights = WEIGHTS)

wg_model.predict(im_arr_scaled)

The predict always fail with "ValueError: Input 0 of layer "model_2" is incompatible with the layer: expected shape=(None, 224, 224, 3), found shape=(32, 224, 3)"

But I'm checking the shape and size in every step of the image and never turns to (32, 224, 3). Don't know where the error might be, any thoughts would be very much appreciated.

This is the error output:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In [61], line 1
----> 1 cnn_model.predict(im_arr_scaled)

File ~/.local/lib/python3.8/site-packages/keras/utils/traceback_utils.py:67, in filter_traceback.<locals>.error_handler(*args, **kwargs)
     65 except Exception as e:  # pylint: disable=broad-except
     66   filtered_tb = _process_traceback_frames(e.__traceback__)
---> 67   raise e.with_traceback(filtered_tb) from None
     68 finally:
     69   del filtered_tb

File ~/.local/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py:1147, in func_graph_from_py_func.<locals>.autograph_handler(*args, **kwargs)
   1145 except Exception as e:  # pylint:disable=broad-except
   1146   if hasattr(e, "ag_error_metadata"):
-> 1147     raise e.ag_error_metadata.to_exception(e)
   1148   else:
   1149     raise

ValueError: in user code:

    File "/home/app/.local/lib/python3.8/site-packages/keras/engine/training.py", line 1801, in predict_function  *
        return step_function(self, iterator)
    File "/home/app/.local/lib/python3.8/site-packages/keras/engine/training.py", line 1790, in step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
...
    File "/home/app/.local/lib/python3.8/site-packages/keras/engine/input_spec.py", line 264, in assert_input_compatibility
        raise ValueError(f'Input {input_index} of layer "{layer_name}" is '

    ValueError: Input 0 of layer "model_2" is incompatible with the layer: expected shape=(None, 224, 224, 3), found shape=(32, 224, 3)

CodePudding user response:

You might be missing the batch dimension. Try:

wg_model.predict(im_arr_scaled[None, ...])
  • Related