Alexander Andersen
Alexander Andersen

Reputation: 33

How can I get Keras CNN to work with the right number of dimensions?

I get the error:
"Error when checking input: expected conv1d_41_input to have 3 dimensions, but got array with shape (1920, 5000)"
when trying to compile a CNN model in Keras.

My input data is 1920 samples with 5000 features.

I have tried adding a Flatten layer before the first Dense layer.

# Parameters 
BATCH_SIZE = 16
DROP_OUT = 0.25
N_EPOCHS = 100
N_FILTERS = 128
TRAINABLE = False
LEARNING_RATE = 0.001
N_DIM = 32
KERNEL_SIZE = 7

# Create model
model = Sequential()
model.add(Conv1D(N_FILTERS, KERNEL_SIZE, activation='relu', padding='same',input_shape=(5000,1)))
model.add(MaxPooling1D(2))
model.add(Conv1D(N_FILTERS, KERNEL_SIZE, activation='relu', padding='same'))
model.add(GlobalMaxPooling1D())
model.add(Dropout(DROP_OUT))
model.add(Dense(N_DIM, activation='relu', kernel_regularizer=regularizers.l2(1e-4)))
model.add(Dense(N_LABELS, activation='sigmoid'))  
adam = optimizers.Adam(lr=LEARNING_RATE, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)
model.compile(loss='binary_crossentropy', optimizer=adam, metrics=['accuracy'])
model.summary()

Upvotes: 0

Views: 126

Answers (1)

Dr. Snoopy
Dr. Snoopy

Reputation: 56367

If you declare your input shape as input_shape=(5000,1), then your data should have shape (None, 5000,1), where the first dimension corresponds to samples, so in this case you just need to add the channels dimension with a value of one by reshaping:

X_train = X_train.reshape((-1, 5000, 1))

And do the same for any test or validation data.

Upvotes: 1

Related Questions