Value Error -> Shapes (None, 5) and (None, 2) are incompatible

Hello all,

I’m trying to build a model to classify diseases according to a series of information.

My code follows bellow:

from tensorflow.keras.utils import to_categorical
import numpy as np

data = pd.read_csv(‘/content/sample_data/Blood_samples_dataset_balanced_2(f).csv’)

y = data.iloc[:,-1]
x = data.iloc[:, :-1]

x = pd.get_dummies(x)

X_train, X_test, Y_train, Y_test = train_test_split(x, y, test_size = 0.3, random_state = 0)

le = LabelEncoder()

Y_train = le.fit_transform(Y_train.astype(str))

Y_test = le.transform(Y_test.astype(str))

Y_train = to_categorical(Y_train)

Y_test = to_categorical(Y_test)

model = Sequential()
model.add(Dense(12, activation=‘relu’))
model.add(Dense(2, activation=‘softmax’))
model.compile(loss=‘categorical_crossentropy’, optimizer=‘adam’, metrics=[‘accuracy’]), Y_train, epochs = 50, batch_size = 2, verbose=1)

loss, acc = model.evaluate(X_test, Y_test, verbose=0)
print(“Loss”, loss, “Accuracy:”, acc)

y_estimate = model.predict(X_test, verbose=0)
y_estimate = np.argmax(y_estimate, axis=1)

y_true = np.argmax(Y_test, axis=1)

print(classification_report(y_true, y_estimate))

Whenever I try to run the code the following error shows up:

ValueError: Shapes (None, 5) and (None, 2) are incompatible

What can I do to solve this error?

Thank you very much,


Hi @Gustavo_Ferreira, This error is due to the shape mismatch between labels and model output shape. Could you please make sure that no,of labels and the number of units in the last dense layer are same.

Also if you are trying to perform a binary classification change the loss from categorical_crossentropy to binary_cross entropy and also change the activation from softmax to sigmoid since sigmoid is the proper activation function for binary data. Thank You.