为什么 Keras 中的 plot_model 没有正确绘制模型?

Why plot_model in Keras does not plot the model correctly?

我想可视化我的神经网络。因此,我使用 from tensorflow.keras.utils import plot_model 并像这样使用它:

    model = Sequential()
    model.add(Dense(8, activation="relu"))
    model.add(Dense(1))
    plot_model(model, to_file="model.png", show_shapes=True)

但是,当我打开图形时,它看起来像这样:

我的代码有什么问题?我没有看到任何错误。

原因是模型还没有建立,因为它不知道它的输入形状。使用 input_shape(或 input_dim)参数指定第一层模型的输入形状,或者通过调用 fit 方法开始在某些数据上拟合模型(因此输入形状可以自动推断)。此外,正如@xdurch0 在评论部分提到的,另一种选择是调用模型的 build 方法并将输入形状作为参数传递给它。