alex martinez
alex martinez

Reputation: 1

Input 0 of layer sequential8 is incompatible with the layer: expected axis -1 of input shape to have value 1 but received input with shape (32, 1, 21)

I am building a CNN with Keras and it is showing an error. The code is the following:

input_shape = (21,)  # For your tabular data, add a channel dimension of 1

model = models.Sequential()

# Convolutional layers
model.add(layers.Conv1D(32, 3, activation='relu', input_shape=(21, 1)))
model.add(layers.MaxPooling1D(2))
model.add(layers.Conv1D(64, 3, activation='relu'))
model.add(layers.MaxPooling1D(2))
model.add(layers.Conv1D(64, 3, activation='relu'))

# Flatten the output and add dense layers
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10, activation='softmax'))  # 10 output units for 10 classes


model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# Train the model
model.fit(X_train_reshaped, Y_train, epochs=10, validation_data=(X_test, Y_test))

# Predict using the model
y_pred = model.predict(X_test_reshaped)
y_pred_classes = np.argmax(y_pred, axis=1)

The input has 5 million rows with 21 features. The code should make a multi-class classification with 10 different classes. What is wrong with the code?

Thanks for your help.

Upvotes: 0

Views: 26

Answers (1)

Chih-Hao Liu
Chih-Hao Liu

Reputation: 466

The shape of your X_train_reshaped is (32, 1, 21), but you've defined your model with input_shape=(21, 1). So you need to reshape X_train_reshaped to the shape (32, 21, 1) to match the input shape of your model.

Here's a simple example for your reference:

model = models.Sequential()

# Convolutional layers
model.add(layers.Conv1D(32, 3, activation='relu', input_shape=(21, 1)))
model.add(layers.MaxPooling1D(2))
model.add(layers.Conv1D(64, 3, activation='relu'))
model.add(layers.MaxPooling1D(2))
model.add(layers.Conv1D(64, 3, activation='relu'))

# Flatten the output and add dense layers
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10, activation='softmax'))  # 10 output units for 10 classes


model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
X_train_reshaped = tf.random.normal([32,21,1])
Y_train = tf.random.normal([32,10])
X_test = tf.random.normal([32,21,1])
Y_test = tf.random.normal([32,10])
# Train the model
model.fit(X_train_reshaped, Y_train, epochs=10, validation_data=(X_test, Y_test))

Upvotes: 0

Related Questions