Shahid Ahmad Khan
Shahid Ahmad Khan

Reputation: 23

Tensorflow says Input 0 of layer conv2d is incompatible with the layer: expected ndim=4, found ndim=3

Here's my code:

(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()

the input data shape is (60000, 28, 28). its the keras mnist dataset. and here's the error

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

An I have no idea whats wrong with it.

Upvotes: 1

Views: 770

Answers (2)

Shahid Ahmad Khan
Shahid Ahmad Khan

Reputation: 23

I realized my mistake mnist data has a shape: (sample, width, height) and Conv2D layers require a shape (samples, width, height, depth), so the solution would be to add an extra dimension.

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

Upvotes: 0

Gokulaselvan
Gokulaselvan

Reputation: 138

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".

The Input shape is expected as (batch,channels,rows,cols) you have given number of images.

create a variable like image_size=(3,28,28) and

input_shape = image_size

... This might work for you. or try

input_shape = (3,28,28)

Upvotes: 1

Related Questions