在 Keras 模型的第一层识别 input_shape 有什么好处吗?

Is there any benefits of identifying input_shape in the first layer of a Keras model?

我假设 input_shape 参数对于 Sequential Keras 模型的第一层是可选的,如以下简单代码片段所示:

model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28)), 
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(10, activation='softmax')
])

如果不识别,就从第一批数据推断出来。我能想象到的唯一区别是当我们定义 input_shape 时,模型可以更快地初始化。识别这个论点有什么真正的好处吗?

你是对的,唯一的区别是模型的构建时间。这种差异可能很重要,例如,打印模型摘要或在提供任何数据之前保存模型仅在指定 input_shape 时才有效。