首页 > 解决方案 > Tensorflow 说层 conv2d 的 Input 0 与层不兼容:expected ndim=4, found ndim=3

问题描述

这是我的代码:

(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.xtensorflowdeep-learningconv-neural-network

解决方案


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)

推荐阅读