Search code examples
pythonkeraskeras-layer

Incorrect input to Conv2D in Keras


I am trying to learn using deep learning in python to analyse EEG data. Unfortunately, I am also new to python, so have tried to find the simplest tools available. This has lead me to Keras.

More precisely, I am trying to implement the following pipe line:

EEG analysis net from https://arxiv.org/abs/1610.01683

So far, I seem to be stuck around "S1" or "C2". The idea so far is:

  • input sections of EEG data (1 x 6000 is what I will use for now)

  • run that through 20 1D filters (1x200)

  • do max-pooling on the output of each of these filterings with pool 20, stride 10 (resulting in 20 1x578 data points)
  • "stack" this into a 20 x 578 matrix
  • run this through a 2D convolution with kernel size 20 x 30

However, the below code gives me the following error:

model = Sequential()
model.add(Conv1D(input_shape=(1,6000), kernel_size=200,strides=1,
                 activation='sigmoid',filters=20))
model.add(MaxPooling1D(pool_size=20, strides=10,padding='same'))
model.add(Conv2D(filters=400,kernel_size=(20,30),strides=(1,1),activation='sigmoid'))

Output:

ValueError: Input 0 is incompatible with layer conv2d_4: expected ndim=4, found ndim=3

I am sure this is trivial mistake, but going through the keras documentation has not made me any wiser.

I realize the above skips the "stacking" procedure, but the closest thing I could find to that was Concatenate, and that just complains that I have not given it any inputs.

I am using theano 0.9.0.dev and keras 2.0.2


Solution

  • You need to reshape your data before going from 1D to 2D. There is dedicated layer in Keras. I guess, your model may start like this:

    model = Sequential()
    model.add(Conv1D(input_shape=(6000,1),kernel_size=200,strides=1,
                 activation='sigmoid',filters=20))
    model.add(MaxPooling1D(pool_size=20, strides=10,padding='same'))
    model.add(Reshape((-1, 581, 20)))
    model.add(Conv2D(filters=400,kernel_size=(20,30),strides=(1,1), 
                 activation='sigmoid'))
    

    I've also replaced input_shape to default dimension ordering.