Keras Valueerror: Input 0 Is Incompatible With Layer Conv2D_1: Expected Ndim=4, Found Ndim=5

Keras ValueError: Input 0 is incompatible with layer conv2d_1: expected ndim=4, found ndim=5

The problem is input_shape.

It should actually contain 3 dimensions only. And internally keras will add the batch dimension making it 4.

Since you probably used input_shape with 4 dimensions (batch included), keras is adding the 5th.

You should use input_shape=(32,32,1).

ValueError: Input 0 of layer "max_pooling2d" is incompatible with the layer: expected ndim=4, found ndim=5. Full shape received: (None, 3, 51, 39, 32)

Issue is with input_shape. input_shape=input_shape[1:]

Working sample code

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten, Convolution2D, MaxPooling2D, Activation
from tensorflow.keras.optimizers import Adam

input_shape = (3, 210, 160, 3)

model = Sequential()
model.add(Convolution2D(32, (8,8), strides=(4,4), activation="relu", input_shape=input_shape[1:], data_format="channels_last"))
model.add(MaxPooling2D(pool_size=(2,2), data_format="channels_last"))
model.add(Convolution2D(64, (4,4), strides=(1,1), activation="relu"))
model.add(MaxPooling2D(pool_size=(2, 2), data_format="channels_last"))
model.add(Convolution2D(64, (3,3), activation="relu"))
model.add(Flatten())
model.add(Dense(512, activation="relu"))
model.add(Dense(256, activation="relu"))
model.add(Dense(2, activation="linear"))

model.summary()

Output

Model: "sequential_7"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d_9 (Conv2D) (None, 51, 39, 32) 6176

max_pooling2d_5 (MaxPooling (None, 25, 19, 32) 0
2D)

conv2d_10 (Conv2D) (None, 22, 16, 64) 32832

max_pooling2d_6 (MaxPooling (None, 11, 8, 64) 0
2D)

conv2d_11 (Conv2D) (None, 9, 6, 64) 36928

flatten_1 (Flatten) (None, 3456) 0

dense_4 (Dense) (None, 512) 1769984

dense_5 (Dense) (None, 256) 131328

dense_6 (Dense) (None, 2) 514

=================================================================
Total params: 1,977,762
Trainable params: 1,977,762
Non-trainable params: 0

ValueError: Input 0 of layer "conv2d" is incompatible with the layer: expected min_ndim=4, found ndim=3. Full shape received: (28, 28, 1)

Take it easy, just a little mistake in input_fn() that cause your problem:

def input_fn(images, labels, epochs, batch_size):
dataset = tf.data.Dataset.from_tensor_slices((images, labels))

SHUFFLE_SIZE = 5000
# In-place changes do not work so add `dataset = `
dataset = dataset.shuffle(SHUFFLE_SIZE).repeat(epochs).batch(batch_size)
dataset = dataset.prefetch(None)

return dataset

P.S.: tf.data.Dataset's methods always return an Iterable obj instead of the original data pipeline. So any In-place like changes do not work.



Related Topics



Leave a reply



Submit