层 "dense_1" 的输入 0 与层不兼容:预期 min_ndim=2,发现 ndim=1。已收到完整形状:(None,)

Input 0 of layer "dense_1" is incompatible with the layer: expected min_ndim=2, found ndim=1. Full shape received: (None,)

出于学习目的,我在 tensorflow 中创建了一个简单的回归模型,但我陷入了这个问题。不知道我在哪里犯了错误,请帮助我解决这个微不足道的问题。发布下面的代码。

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) 

执行上面的代码出现如下错误

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

请提供input_shape型号和运行相同的型号。

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)

输出:

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>