Home > OS >  WARNING:tensorflow:Model was constructed with shape (4, 112, 112, 3) for input ..., but it was calle
WARNING:tensorflow:Model was constructed with shape (4, 112, 112, 3) for input ..., but it was calle

Time:03-14

I trained a model and saved it as a h5 file. When I reuse the model and try to make a prediction using an image, it throws an error saying that it is incompatible.

How can I eliminate the warning?

Here is the code:

CATEGORIES = ["Tuberculosis", "Normal"]

def prepare(filepath):
  IMG_SIZE = 112
  img_array = cv2.imread(filepath, cv2.IMREAD_GRAYSCALE)
  new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
  return new_array.reshape(-1, IMG_SIZE, IMG_SIZE, 1)

model = tf.keras.models.load_model("tuberculosis.h5")

prediction = model.predict([prepare("test.jpg")])
print(CATEGORIES[int(prediction[0][0])])

Here is the error it throws:

WARNING:tensorflow:Model was constructed with shape (4, 112, 112, 3) for input KerasTensor(type_spec=TensorSpec(shape=(4, 112, 112, 3), dtype=tf.float32, name='conv2d_input'), name='conv2d_input', description="created by layer 'conv2d_input'"), but it was called on an input with incompatible shape (None, 112).


ValueError                                
Traceback (most 
recent call last)
<ipython-input-79-6d3f8245e17a> in <module>()
----> 1 prediction = model.predict([prepare("test.jpg")])
      2 print(CATEGORIES[int(prediction[0][0])])

1 frames
/usr/local/lib/python3.7/dist- 
packages/tensorflow/python/framework/func_graph.py in 
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 "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1801, in predict_function  *
    return step_function(self, iterator)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1790, in step_function  **
    outputs = model.distribute_strategy.run(run_step, args=(data,))
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1783, in run_step  **
    outputs = model.predict_step(data)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1751, in predict_step
    return self(x, training=False)
File "/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py", line 67, in error_handler
    raise e.with_traceback(filtered_tb) from None
File "/usr/local/lib/python3.7/dist-packages/keras/engine/input_spec.py", line 228, in assert_input_compatibility
    raise ValueError(f'Input {input_index} of layer "{layer_name}" '

ValueError: Exception encountered when calling layer "sequential" (type Sequential).

Input 0 of layer "conv2d" is incompatible with the layer: expected min_ndim=4, found ndim=2. Full shape received: (None, 112)

Call arguments received:
  • inputs=('tf.Tensor(shape=(None, 112), dtype=uint8)',)
  • training=False
  • mask=None

CodePudding user response:

the error is saying you are passing a wronly shapped image, input with 3 channels. This might work if your input image has 3 channels:

def prepare(filepath):
  IMG_SIZE = 112
  img_array = cv2.imread(filepath)
  img_array = cv2.cvtColor(img_array ,cv2.COLOR_BGR2RGB)
  new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
  return new_array.reshape(-1, IMG_SIZE, IMG_SIZE, 3)

CodePudding user response:

This error came from shape of input, You can try this:

import tensorflow as tf
import cv2

IMAGE_CHANNEL = 1 # or 3

def prepare(filepath):
    IMG_SIZE = 112
    img_array = cv2.imread(filepath, cv2.IMREAD_GRAYSCALE)
    new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
    return new_array.reshape(-1, IMG_SIZE, IMG_SIZE, IMAGE_CHANNEL)

x = tf.keras.Input(shape=(112,112,IMAGE_CHANNEL))
y = tf.keras.layers.Dense(16, activation='softmax')(x)
model = tf.keras.Model(x, y)
model.summary()


prediction = model.predict([prepare("test.jpg")])
print(prediction)

Output:

Model: "model_11"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 input_17 (InputLayer)       [(None, 112, 112, 1)]     0         
                                                                 
 dense_13 (Dense)            (None, 112, 112, 16)      32        
                                                                 
=================================================================
Total params: 32
Trainable params: 32
Non-trainable params: 0
_________________________________________________________________
[[[[2.40530210e-15 1.25257872e-18 2.81339079e-01 ... 1.10927344e-20
    1.28210900e-22 3.45369773e-24]
   [1.21484684e-15 5.40451430e-19 2.79041141e-01 ... 4.33733043e-21
    4.56826763e-23 1.14132918e-24]
   [3.09763760e-16 1.00567346e-19 2.74375856e-01 ... 6.62814917e-22
    5.79706900e-24 1.24585123e-25]
   ...
  • Related