【问题标题】:Tensorflow says Input 0 of layer conv2d is incompatible with the layer: expected ndim=4, found ndim=3Tensorflow 说层 conv2d 的 Input 0 与层不兼容:expected ndim=4, found ndim=3
【发布时间】:2020-02-24 18:51:36
【问题描述】:

这是我的代码:

(x_train, y_train), (x_test, y_test) = mnist.load_data()

def create_model():
    model = tf.keras.models.Sequential()

    model.add(Conv2D(64, (3, 3), input_shape=x_train.shape[1:], activation='relu'))
    model.add(MaxPooling2D(pool_size=2))

    model.add(Conv2D(64, (3, 3), activation='relu'))
    model.add(MaxPooling2D(pool_size=2))

    model.add(Flatten())
    model.add(Dense(1024, activation='relu'))
    model.add(Dense(10, activation='softmax'))

    model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
    return model

model = create_model()

输入数据形状为 (60000, 28, 28)。它是 keras mnist 数据集。 这是错误

ValueError: Input 0 of layer conv2d_1 is incompatible with the layer: expected ndim=4, found ndim=3. Full shape received: [None, 28, 28]

我不知道它有什么问题。

【问题讨论】:

    标签: python-3.x tensorflow deep-learning conv-neural-network


    【解决方案1】:
    Input shape
    4D tensor with shape: (batch, channels, rows, cols) if data_format is "channels_first" or 4D tensor with shape: (batch, rows, cols, channels) if data_format is "channels_last".
    

    输入形状应为 (batch,channels,rows,cols) 您给定的图像数量。

    创建一个变量,如image_size=(3,28,28) 和

    input_shape = image_size
    

    ...这可能对您有用。或者试试

    input_shape = (3,28,28)
    

    【讨论】:

      【解决方案2】:

      我意识到我的错误 mnist 数据有一个形状:(sample, width, height) 和 Conv2D 层需要一个形状 (samples, width, height, depth),所以解决方案是添加一个额外的维度。

      x_train = x_train[..., np.newaxis]
      x_test = x_test[..., np.newaxis]
      

      【讨论】:

        猜你喜欢
        • 2018-08-21
        • 1970-01-01
        • 2017-10-26
        • 2022-01-06
        • 2019-04-14
        • 2018-09-25
        • 2017-11-18
        • 2020-04-18
        • 1970-01-01
        相关资源
        最近更新 更多