Reputation: 553
I'm trying to understand how to write a Conv1D model on Keras but I keep running into a dimensionality mismatch error. Right now x_train = [1000,294] (1000 items and 294 features) and y_train = [1000,9] (1000 items and 9 labels). I keep getting the error message expected 3 dimensions but got 2 dimensions. But I try to fix it, it appears again. Some issues on github has suggested Flatten()
but it is already there and no luck. Any idea what I'm missing? Thank you
The error I got,
Code is included below
tb = [keras.callbacks.TensorBoard(log_dir='./dllogs')]
main_input = Input(shape=(294, ), dtype='float32')
x_train = np.array(x_train)
y_train = np.array(y_train)
x_dev = np.array(x_dev)
y_dev = np.array(y_dev)
x = Conv1D(128, 5, activation='relu')(main_input)
x = MaxPooling1D(5)(x)
x = Conv1D(128, 5, activation='relu')(x)
x = MaxPooling1D(5)(x)
x = Conv1D(128, 5, activation='relu')(x)
x = MaxPooling1D(35)(x)
x = Flatten()(x)
x = Dropout(0.25)(x)
x = Dense(128, activation='relu')(x)
preds = Dense(pred_dim, activation='softmax')(x)
model = Model(inputs=main_input, outputs=preds)
model.compile(optimizer='adam', loss='kullback_leibler_divergence', metrics=['accuracy'])
print(model.summary())
history_NN = model.fit(x_train, y_train, batch_size=BATCHSIZE, epochs=EPOCHS, callbacks=tb, validation_data=(x_dev, y_dev))
Answer
Resulting code,
tb = [keras.callbacks.TensorBoard(log_dir='./dllogs')]
main_input = Input(shape=(294, 1))#changed
x_train = np.array(x_train)
y_train = np.array(y_train)
x_dev = np.array(x_dev)
y_dev = np.array(y_dev)
x_train = np.expand_dims(x_train, axis=-1) #changed
x_dev = np.expand_dims(x_dev, axis=-1) #changed
x = Conv1D(128, 5, activation='relu')(main_input)
x = MaxPooling1D(5)(x)
x = Conv1D(128, 5, activation='relu')(x)
x = MaxPooling1D(5)(x)
x = Conv1D(128, 5, activation='relu')(x)
x = MaxPooling1D(11)(x)
x = Flatten()(x)
x = Dropout(0.25)(x)
x = Dense(128, activation='relu')(x)
preds = Dense(pred_dim, activation='softmax')(x)
model = Model(inputs=main_input, outputs=preds)
model.compile(optimizer='adam', loss='kullback_leibler_divergence', metrics=['accuracy'])
print(model.summary())
history_NN = model.fit(x_train, y_train, batch_size=BATCHSIZE, epochs=EPOCHS, callbacks=tb, validation_data=(x_dev, y_dev))
Upvotes: 1
Views: 673
Reputation: 33410
Conv1D
layer expects sequence inputs of shape (sequence_length, num_features)
. It seems you have sequences of length 294 with one feature; therefore, each input sample needs to have a shape of (294,1)
(and not (294,)
). To fix it, you can use np.expand_dims
to add a third dimension of size 1 to your input data:
x_train = np.expand_dims(x_train, axis=-1)
x_dev = np.expand_dims(x_dev, axis=-1)
main_input = Input(shape=(294, 1)) # fix the input shape here as well
Upvotes: 1