Kyv
Kyv

Reputation: 697

Error with targets shape while building a multi-class classification with tensorflow

I am trying to use an Artificial Neural Network for multi-class classification using Tensorflow with Keras. I am buildung a model with the following shape:

print(X_train.shape, X_test.shape, y_train.shape, y_test.shape`
(2000, 5, 5) (800, 5, 5) (2000, 4) (800, 4)

Labels are one-hot encoded.
Here is my model:

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import Dropout

model = Sequential()
model.add(Dense(64, input_shape=(X_train.shape[1], X_train.shape[2],), activation='relu'))
model.add(Dense(32, activation='relu'))
model.add(Dense(y_train.shape[1], activation='softmax'))

model.compile(optimizer = 'adam', loss='categorical_crossentropy', metrics=['accuracy'])
# model.summary()

model.fit(X_train, y_train, epochs=5, batch_size=32, verbose=1, validation_data=(X_test, y_test)`

I get this error:

ValueError: A target array with shape (2000, 4) was passed for an output of shape (None, 5, 4) while using as loss `categorical_crossentropy`. This loss expects targets to have the same shape as the output.

Where does the problem come from ?

Upvotes: 0

Views: 56

Answers (1)

Tehnorobot
Tehnorobot

Reputation: 369

You should probably reduce the dimension within your network. You have to go from 3d to 2d to match your goal. You can do this by using a global merge or smoothing layer. Try using Flatten () before the output level or (GlobalAveragePooling1D() or GlobalMaxPooling1D())

Upvotes: 1

Related Questions