Home > Net >  How can I fix this problem related to Conv2D of Keras?
How can I fix this problem related to Conv2D of Keras?

Time:04-06

I have created the following neural networks:

model = keras.Sequential()
model.add(layers.Conv2D(3, (3,3), activation="relu", padding="same", input_shape=constants.GRID_SHAPE))
model.add(layers.MaxPooling2D((3,3)))
model.add(layers.Flatten())
model.add(layers.Dense(constants.NUM_ACTIONS), activation="softmax")

where constants.GRID_SHAPE is (4,12).

I get the following error:

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

How can I fix this problem?

CodePudding user response:

Make sure you have a 3D input shape excluding the batch size if you plan to use the Conv2D layer. Currently you have a 2D input shape. Also make sure the activation function softmax is part of the Dense layer:

import tensorflow as tf

model = tf.keras.Sequential()
model.add(tf.keras.layers.Conv2D(3, (3,3), activation="relu", padding="same", input_shape=(4, 12, 1)))
model.add(tf.keras.layers.MaxPooling2D((3,3)))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(5, activation="softmax"))

If your input data is of the shape (samples, 4, 12), you can use data = tf.expand_dims(data, axis=-1) to add an extra dimension to your data to make it compatible with the Conv2D layer.

If you do not want to add a new dimension, you could also simply use a Conv1D layer:

import tensorflow as tf

model = tf.keras.Sequential()
model.add(tf.keras.layers.Conv1D(3, 3, activation="relu", padding="same", input_shape=(4, 12)))
model.add(tf.keras.layers.MaxPooling1D(3))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(5, activation="softmax"))
  • Related