简体   繁体   中英

Keras - expected dense to have shape

I'm making a dense ML model with Keras but I get this error

ValueError: Error when checking target: expected dense_3 to have shape (1,) but got array with shape (9,)

This is how my model is set up

get_custom_objects().update({'swish': Swish(swish)})

model = Sequential()
model.add(Dense(33, activation='swish', input_shape=(trainX.shape[1],)))
model.add(Dense(33, activation='swish'))
model.add(Dense(9, activation='softmax'))

#Train Network
model.compile(optimizer="adam", loss=keras.losses.sparse_categorical_crossentropy, metrics=["accuracy"])
model.fit(trainX, trainY, validation_split=0.2, epochs=3)

trainX and trainY are pandas DataFrames trainX has 2 columns and trainY has 9.

I'm not sure why it says it should be (1,) since I specified the output layer to have 9 neurons.

Any help is greatly appreciated.

From Keras docs:

When using the sparse_categorical_crossentropy loss, your targets should be integer targets. If you have categorical targets, you should use categorical_crossentropy.

So you should replace

model.compile(optimizer="adam", loss=keras.losses.sparse_categorical_crossentropy, metrics=["accuracy"])

With

model.compile(optimizer="adam", loss=keras.losses.categorical_crossentropy, metrics=["accuracy"])

That is needed because trainY is a categorical target, since it has 9 columns instead of just one integer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM