user18919163
user18919163

Reputation: 1

How to fix google-colab tensorflow ValueError?

This is the code I wrote:

tf.random.set_seed(42)


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=2)

And this is the error I got:

    /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 228, in assert_input_compatibility
        raise ValueError(f'Input {input_index} of layer "{layer_name}" '

    ValueError: Exception encountered when calling layer "sequential_5" (type Sequential).
    
    Input 0 of layer "dense_4" 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=float32)
      • training=True
      • mask=None

Upvotes: 0

Views: 568

Answers (1)

Zaza
Zaza

Reputation: 11

I faced the same problem. If you are trying to follow Daniel Bourke deep learning codes, look at his github code for the same session.

Here is the fix in the code:

# Fit the model
# model.fit(X, y, epochs=5) # this will break with TensorFlow 2.7.0+
model.fit(tf.expand_dims(X, axis=-1), y, epochs=5)

It worked for me.

Upvotes: 1

Related Questions