tensorflow keras.sequential 函数错误

tensorflow keras.sequential function error

嗨,我试图在 tensorflow 中建立最简单的回归模型,但出现了这个错误。张量流版本:2.7.0

import tensorflow as tf
X_train = tf.cast(tf.constant([1,2,3]), dtype=tf.float32)
y_train = tf.cast(tf.constant([2,3,4]), dtype=tf.float32)

model = tf.keras.Sequential([tf.keras.layers.Dense(1)])
model.compile()
model.fit(X_train, y_train, epochs=10) 

ValueError:调用层“sequential_7”(类型 Sequential)时遇到异常。 层“dense_5”的输入 0 与层不兼容:预期 min_ndim=2,发现 ndim=1。已收到完整形状:(None,)

您没有指定输入形状、损失函数和优化器。

import tensorflow as tf

X_train = tf.cast(tf.constant([1, 2, 3]), dtype=tf.float32)
y_train = tf.cast(tf.constant([2, 3, 4]), dtype=tf.float32)

model = tf.keras.Sequential([
    tf.keras.Input(shape=(1, )),
    tf.keras.layers.Dense(1)
    ])
model.compile(optimizer="Adam", loss="binary_crossentropy")
model.fit(X_train, y_train, epochs=10)