简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM