user3734568
user3734568

Reputation: 1471

keras error in model fit ValueError: Shapes (32, 147) and (32, 2) are incompatible

I am trying to train Keras model, below code I am using

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),activation='relu',input_shape=(28,28,1)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(len(np.unique(y)), activation='softmax'))

model.compile(loss='categorical_crossentropy',optimizer='Adam',metrics=['accuracy'])

model.fit(X_train, y_train, epochs=10, validation_data=(X_test, y_test))

but I am getting error:

ValueError: Shapes (32, 147) and (32, 2) are incompatible

input and output variable shape are as below.

print(f"Input: {X_train.shape}, Output: {y_train.shape}")
Input: (3360, 28, 28, 1), Output: (3360, 147)

I tried to use loss='sparse_categorical_crossentrop' using 1D integer encoded target , but getting very poor accuracy. Can anyone please help me.

Upvotes: 1

Views: 223

Answers (1)

Kaveh
Kaveh

Reputation: 4960

Your model's output shape is not the same as y_train.

You have 3360 samples. Each sample in X has shape (28,28,1) and in Y has (147). But your last layer has 2 neurons as output of len(np.unique(y), and they are incompatible (147 vs. 2).
You should specify that you have 147 classes or 2 classes.

One possible solution:

model.add(Dense(147, activation='softmax'))

Upvotes: 3

Related Questions