Search code examples
python-3.xkerasconv-neural-networkkeras-layer

1D Convolutional network with keras, error on input size


I'm trying to build a convolutional neural network for my dataset. My training dataset has 1209 examples of 800 features each.

Here's what part of the code looks like :

model = Sequential()
model.add(Conv1D(64, 3, activation='linear', input_shape=(1209, 800)))
model.add(GlobalMaxPooling1D())
model.add(Dense(1, activation='linear'))
model.compile(loss=loss_type, optimizer=optimizer_type, metrics=[metrics_type])
model.fit(X, Y, validation_data=(X2,Y2),epochs = nb_epochs, 
batch_size = batch_size,shuffle=True)

When I compile this code, I get the following error :

Error when checking input: expected conv1d_25_input to have 3 dimensions, 
but got array with shape (1209, 800)

So I add a dimension, here's what I do :

X = np.expand_dims(X, axis=0)
X2 = np.expand_dims(X2, axis=0)

And then I get this error :

ValueError: Input arrays should have the same number of samples as target arrays. 
Found 1 input samples and 1209 target samples.

My training data has now a shape like this (1, 1209, 800), should it be something else ?

Thanks a lot for reading this.


Solution

  • Instead of expanding the dimensions on X at axis 0, you should expand on axis 2. Thus, rather than X = np.expand_dims(X, axis=0), you need X = np.expand_dims(X, axis=2).

    Afterwards, the shape of X should be (1209, 800, 1), and you should then specify input_shape=(800, 1) in your first layer.