Search code examples
pythontensorflowkerastensorflow2.0keras-layer

create Tensorflow model which accepts tensor image as input to the model


I'm using below configuration for the image classification model:

model = keras.Sequential([
    keras.layers.Flatten(input_shape=(100, 100, 3)),
    keras.layers.Dense(128, activation='relu'),
    keras.layers.Dense(10)
])

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

If I if print model.inputs then it returns

[<tf.Tensor 'flatten_input:0' shape=(None, 100, 100, 3) dtype=float32>]

If I pass tensor image to this model then it does not work. So my question is What changes should I do to my model so that it will accept tensor image

I'm passing image using below code:

image = np.asarray(image)
# The input needs to be a tensor, convert it using `tf.convert_to_tensor`.
input_tensor = tf.convert_to_tensor(image)
# The model expects a batch of images, so add an axis with `tf.newaxis`.
input_tensor = input_tensor[tf.newaxis,...]
# Run inference
output_dict = model(input_tensor)

I get below error if I pass tensor image

WARNING:tensorflow:Model was constructed with shape (None, 100, 100, 3) for input Tensor("flatten_input:0", shape=(None, 100, 100, 3), dtype=float32), but it was called on an input with incompatible shape (1, 886, 685, 3).
---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)

I just wanted to know which Keras layers and input parameters should I update to the model so that it can accept tensor image as input. Any help would be appreciated. Thanks!


Solution

  • The message is a warning, not an error, just some semantics. The warning does point to a real problem.

    Your model takes images with shape (100, 100, 3), and you are giving it inputs with shape (886, 865, 3). The spatial dimensions do not match, you need to resize the image to size 100 x 100.