'tensorflow Keras fitting value_error

I am new to tensorflow. i've tried to fit X and y both shape=8 float64 tensors X as feature set and y as target set.

X = np.array([-7.0, -4.0, -1.0, 2.0, 5.0, 8.0, 11.0, 14.0])
y = np.array([3.0, 6.0, 9.0, 12.0, 15.0, 18.0, 21.0, 24.0])
X = tf.constant(X)
y = tf.constant(y)

my code to fit model as per below:

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=tf.keras.metrics.mae)
model.fit(X, y, epochs=5)

and finally error came up as per below:

    Epoch 1/5
    -------------------------------------------------------------                        
    --------------
    ValueError                                Traceback (most         
    recent call last)
    <ipython-input-62-f2b0f2566f13> in <module>()
         12 
         13 
    ---> 14 model.fit(X, y, epochs=5)

    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 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 "dense" 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

i already updated my Keras, tensorflow and numpy to the latest versions. i tried different epochs too.



Solution 1:[1]

Issue is with shape of the input data. Working sample code

import tensorflow as tf
import numpy as np

X = np.array([-7.0, -4.0, -1.0, 2.0, 5.0, 8.0, 11.0, 14.0])
y = np.array([3.0, 6.0, 9.0, 12.0, 15.0, 18.0, 21.0, 24.0])
X = tf.constant(X)
y = tf.constant(y)

dataset = tf.data.Dataset.from_tensor_slices((X, y))
train_data = dataset.shuffle(len(X_train)).batch(4)
train_data = train_data.prefetch(
        buffer_size=tf.data.experimental.AUTOTUNE)

model = tf.keras.Sequential([
                  tf.keras.layers.Dense(15, activation=tf.nn.relu, input_shape=(1,)),
                  tf.keras.layers.Flatten(),
                  tf.keras.layers.Dense(10, activation=tf.nn.relu),
                  tf.keras.layers.Dense(1, activation=tf.nn.softmax)
])

model.compile(loss=tf.keras.losses.mae,
          optimizer=tf.keras.optimizers.SGD(),
          metrics=tf.keras.metrics.mae)
model.fit(train_data, epochs=5)

Output

Epoch 1/5
2/2 [==============================] - 2s 13ms/step - loss: 12.5000 - mean_absolute_error: 12.5000
Epoch 2/5
2/2 [==============================] - 0s 10ms/step - loss: 12.5000 - mean_absolute_error: 12.5000
Epoch 3/5
2/2 [==============================] - 0s 10ms/step - loss: 12.5000 - mean_absolute_error: 12.5000
Epoch 4/5
2/2 [==============================] - 0s 10ms/step - loss: 12.5000 - mean_absolute_error: 12.5000
Epoch 5/5
2/2 [==============================] - 0s 10ms/step - loss: 12.5000 - mean_absolute_error: 12.5000

Solution 2:[2]

Kindly set your input data as:

import tensorflow as tf
import numpy as np

X = np.array([-7.0, -4.0, -1.0, 2.0, 5.0, 8.0, 11.0, 14.0]).reshape((-1, 1))
y = np.array([3.0, 6.0, 9.0, 12.0, 15.0, 18.0, 21.0, 24.0]).reshape((-1, 1))
X = tf.constant(X)
y = tf.constant(y)


#convert numpy array into tensors
X = tf.constant(X)
y = tf.constant(y)

#create the model

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

#compile the model

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

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

Output

Epoch 1/5
1/1 [==============================] - 0s 285ms/step - loss: 11.5048 - mean_absolute_error: 11.5048
Epoch 2/5
1/1 [==============================] - 0s 9ms/step - loss: 11.3723 - mean_absolute_error: 11.3723
Epoch 3/5
1/1 [==============================] - 0s 8ms/step - loss: 11.2398 - mean_absolute_error: 11.2398
Epoch 4/5
1/1 [==============================] - 0s 8ms/step - loss: 11.1073 - mean_absolute_error: 11.1073
Epoch 5/5
1/1 [==============================] - 0s 8ms/step - loss: 10.9748 - mean_absolute_error: 10.9748
<keras.callbacks.History at 0x7f828d936510>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TFer
Solution 2 Grace U. Nneji