Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keras/Tensorflow Conv1D expected input shape

I want to apply 1-dimensional convolution on my 29 feature input data (as in 29x1 shape). I tell Keras that input_shape=(29,1) but I get an error that it was expecting the input "to have 3 dimensions, but got array with shape (4000, 29)". Why is Keras expecting 3 dimensions?

Keras docs give this weird example of how to use input_shape:

(None, 128) for variable-length sequences with 128 features per step.

I'm not sure what they mean by variable-length sequence, but since I have 29 features I also tried (None,29) and (1,29) and got similar errors with those.

Am I misunderstanding something about what a 1-dimensional convolution does?

Here is a visual depiction of what I expect a Conv1D to do with a kernel size of 3, given 7x1 input.

[x][x][x][ ][ ][ ][ ]
[ ][x][x][x][ ][ ][ ]
[ ][ ][x][x][x][ ][ ]
[ ][ ][ ][x][x][x][ ]
[ ][ ][ ][ ][x][x][x]
like image 856
Atte Juvonen Avatar asked Jul 29 '26 22:07

Atte Juvonen


1 Answers

Why is Keras expecting 3 dimensions?

The three dimensions are (batch_size, feature_size, channels).

Define a 1D Conv layer

Conv1D(32, (3), activation='relu' , input_shape=( 29, 1 ))

Feed (4000, 29, 1) samples to this layer.

Simple example:

from keras import models, layers
import numpy as np

x = np.ones((10, 29, 1))
y = np.zeros((10,))
model = models.Sequential()
model.add(layers.Conv1D(32, (3), activation='relu' , input_shape=( 29,1)))
model.add(layers.Flatten())
model.add(layers.Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer= "adam", metrics=['accuracy'])
print(model.summary())
model.fit(x,y)
like image 193
Manoj Mohan Avatar answered Aug 01 '26 00:08

Manoj Mohan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!