Expected dense_3 had shape (None, 1) but got an array with shape (17268, 2)
I am new to Keras and I am trying to make a model for classification, this is my model:
model = Sequential()
model.add(Dense(86, activation='sigmoid', input_dim=21))
model.add(Dense(50, activation='sigmoid'))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='categorical_crossentropy', optimizer='nadam', metrics=['accuracy'])
but it keeps giving me this error:
ValueError: Error when checking target: expected dense_3 to have shape (None, 1) but got array with shape (17268, 2)
Now I know that I need to encode my labels using one hot encoding and flatten them, so I did that too.
oht_y_train = np_utils.to_categorical(y_train, num_classes=3)
oht_y_train = np.ndarray.flatten(oht_y_train)
But I still get the same error.
NOTE. Before I flattened the labels, I got the same error, only the shape was (5765, 3)
I also printed the form of an array of labels, it gives me (17268,)
source to share
Your labels don't have to be hot if your last level has an output size of 1 (for binary classification). If you have multiple classes, you should use one-line encoding and a loss function categorical_crossentropy
, but your final output layer should be of size 3, i.e. Dense(3)
, where 3 is the number of classes. You shouldn't have to flatten labels after encoding them.
model = Sequential()
model.add(Dense(86, activation='sigmoid', input_dim=21))
model.add(Dense(50, activation='sigmoid'))
model.add(Dense(3, activation='sigmoid'))
model.compile(loss='categorical_crossentropy', optimizer='nadam', metrics=['accuracy'])
model.fit(X_data, Y-one-hot-encoded) # here your labels have shape (data_size, 3).
If you need to do binary categorization, it is better to use loss binary_crossentropy
and have an output size of 1, using Dense(1)
both a sigmoid
or softmax
activation to normalize the outputs between 0 and 1.
model = Sequential()
model.add(Dense(86, activation='sigmoid', input_dim=21))
model.add(Dense(50, activation='sigmoid'))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='nadam', metrics=['accuracy'])
model.fit(X_data, Y_labels) # here your labels have shape (data_size,).
source to share