Home > Software design >  Tensorflow network layers error but received input with shape (None, 250, 250, 3)
Tensorflow network layers error but received input with shape (None, 250, 250, 3)

Time:10-13

I am writing a neural network in TensorFlow and keras. The goal is to understand the state of the 2 options from the picture. Pictures 250x250.

model = Sequential()
model.add(Dense(32, input_shape=(250,250,1)))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(1, activation='sigmoid'))

model.compile(loss='binary_crossentropy', 
              optimizer="adam",
              metrics=['accuracy'])

Model: "sequential_16"

Layer (type) Output Shape Param #

dense_33 (Dense) (None, 250, 250, 32) 64

flatten_5 (Flatten) (None, 2000000) 0

dense_34 (Dense) (None, 128) 256000128

dense_35 (Dense) (None, 1) 129

Total params: 256,000,321 Trainable params: 256,000,321 Non-trainable params: 0

history = model.fit(train_dataset,
                    validation_data=validation_dataset,
                    epochs=15)

But when I start the tutorial, I get an error:

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


ValueError                                Traceback (most recent call last)
<ipython-input-77-6be7592045fb> in <module>
      1 history = model.fit(train_dataset,
      2                     validation_data=validation_dataset,
----> 3                     epochs=15)

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 1021, in train_function  *
        return step_function(self, iterator)
    File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1010, 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 1000, in run_step  **
        outputs = model.train_step(data)
    File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 859, in train_step
        y_pred = self(x, training=True)
    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 249, in assert_input_compatibility
        f'Input {input_index} of layer "{layer_name}" is '

    ValueError: Exception encountered when calling layer "sequential_16" (type Sequential).
    
    Input 0 of layer "dense_33" is incompatible with the layer: expected axis -1 of input shape to have value 1, but received input with shape (None, 250, 250, 3)
    
    Call arguments received:
      • inputs=tf.Tensor(shape=(None, 250, 250, 3), dtype=float32)
      • training=True
      • mask=None

Tell me what should I do with this, please?

CodePudding user response:

Your input is (probably) a 3-channel RGB image, hence its last shape dimension is 3, but the first layer of the model expects a input_shape=(250,250,1). So, either modify your network to take as input a 3 channel image, or pre-process your images to grayscale for instance, to only have one channel.

  • Related