Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception encountered when calling layer "sequential_4" (type Sequential)

This is a simple code for creating,compile and fitting a model for a single layer

X = tf.cast(tf.constant(X),dtype=tf.float32)
y = tf.cast(tf.constant(y),dtype=tf.float32)

#Set Random seed

tf.random.set_seed(42)

#1.create a model using the Sequential API

model = tf.keras.Sequential([
                             tf.keras.layers.Dense(1)
                             ])

#2.Compile the model

model.compile(loss=tf.keras.losses.mae,
              optimizer=tf.keras.optimizers.SGD(),metrics=["mae"])

#Fit the model

model.fit(X,y,epochs = 5)

but I am getting this error at the end.

ValueError: in user code:

    File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 878, in train_function  *
        return step_function(self, iterator)
    File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 867, 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 860, in run_step  **
        outputs = model.train_step(data)
    File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 808, 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 227, in assert_input_compatibility
        raise ValueError(f'Input {input_index} of layer "{layer_name}" '

    ValueError: Exception encountered when calling layer "sequential_6" (type Sequential).
    
    Input 0 of layer "dense_7" is incompatible with the layer: expected min_ndim=2, found ndim=1. Full shape received: (None,)
    
    Call arguments received:
      • inputs=tf.Tensor(shape=(None,), dtype=float64)
      • training=True
      • mask=None

Why Sequential_6 and dense_7??? This is a single layer.

like image 835
Raulp Avatar asked Sep 01 '25 01:09

Raulp


1 Answers

You are forgetting the batch dimension. Your input to your model has to have the shape (batch_size, features). Try something like this:


X = tf.cast(tf.constant([0.5]),dtype=tf.float32)
y = tf.cast(tf.constant([0.6]),dtype=tf.float32)
X = tf.expand_dims(X, axis=0)
y = tf.expand_dims(y, axis=0)
model = tf.keras.Sequential([
                             tf.keras.layers.Dense(1)
                             ])
model.compile(loss=tf.keras.losses.mae,
              optimizer=tf.keras.optimizers.SGD(),metrics=["mae"])

model.fit(X,y,epochs = 5)

Sequential_6 is your model name, dense_7 is the name of the Dense layer. Every time you run your model again, the numbers in the names are incremented.

like image 151
AloneTogether Avatar answered Sep 02 '25 16:09

AloneTogether