I created a simple regression model in tensorflow for learning purpose and i am stuck in this problem. Not sure where i have made the mistake, please help me in solving this trivial problem. posting the code below.
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
X = np.array([2,4,6,8,1,3,5,7,9])
y = np.array([i**2 for i in X])
# we are creating a dataset for y = x^2
#converting the numpy array into tensors
X_tensor = tf.cast(tf.constant(X), dtype = tf.float32)
y_tensor = tf.cast(tf.constant(y), dtype = tf.float32)
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_tensor],y_tensor, epochs=5)
executing the above code gives the following error
WARNING:tensorflow:Layers in a Sequential model should only have a single input tensor. Received: inputs=(<tf.Tensor 'IteratorGetNext:0' shape=(None,) dtype=float32>,). Consider rewriting this model with the Functional API.
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-10-3af7f7bccd4f> in <module>()
----> 1 model.fit([X_tensor],y_tensor, 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_1" (type Sequential).
Input 0 of layer "dense_1" 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
CodePudding user response:
Please provide input_shape
to the model and run the same model again.
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=[1])])
model.compile(loss=tf.keras.losses.mae, optimizer=tf.keras.optimizers.SGD(), metrics = ["mae"])
model.fit(X_tensor,y_tensor, epochs=500)
Output:
Epoch 197/200
1/1 [==============================] - 0s 14ms/step - loss: 9.5596 - mae: 9.5596
Epoch 198/200
1/1 [==============================] - 0s 38ms/step - loss: 9.5573 - mae: 9.5573
Epoch 199/200
1/1 [==============================] - 0s 10ms/step - loss: 9.5551 - mae: 9.5551
Epoch 200/200
1/1 [==============================] - 0s 14ms/step - loss: 9.5529 - mae: 9.5529
<keras.callbacks.History at 0x7febf856bf50>