Aaron
Aaron

Reputation: 117

Tensorflow Keras Conv2D error with 2D numpy array input

I would like to train a CNN using a 2D numpy array as input, but I am receiving this error: ValueError: Error when checking input: expected conv2d_input to have 4 dimensions, but got array with shape (21, 21).

My input is indeed a 21x21 numpy array of floats. The first layer of the network is defined as Conv2D(32, (3, 3), input_shape=(21, 21, 1)) to match the shape of the input array.

I have found some similar questions but none pertaining to a 2D input array, they mostly deal with images. According to the documentation, Conv2D is expecting an input of a 4D tensor containing (samples, channels, rows, cols), but I cannot find any documentation explaining the meaning of these values. Similar questions pertaining to image inputs suggest reshaping the input array using np.ndarray.reshape(), but when trying to do that I receive an input error.

How can I train a CNN on such an input array? Should input_shape be a different size tuple?

Upvotes: 2

Views: 1663

Answers (1)

Balraj Ashwath
Balraj Ashwath

Reputation: 1427

Your current numpy array has dimensions (21, 21). However, TensorFlow expects input tensors to have dimensions in the format (batch_size, height, width, channels) or BHWC implying that you need to convert your numpy input array to 4 dimensions (from the current 2 dimensions). One way to do so is as follows:

input = np.expand_dims(input, axis=0)
input = np.expand_dims(input, axis=-1)

Now, the numpy input array has dimensions: (1, 21, 21, 1) which can be passed to a TF Conv2D operation.

Hope this helps! :)

Upvotes: 4

Related Questions