我正在尝试使用Tensorflow和Keras的多类分类的人工神经网络。我正在构建一个具有以下形状的模型:
print(X_train.shape, X_test.shape, y_train.shape, y_test.shape`
(2000, 5, 5) (800, 5, 5) (2000, 4) (800, 4)
标签是独热编码的。
这是我的模型:
from tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Densefrom tensorflow.keras.layers import Dropoutmodel = 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)`
我得到了以下错误:
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.
问题出在哪里?
回答:
你可能需要在网络中降低维度。你需要从3D转换到2D以匹配你的目标。你可以通过使用全局合并或平滑层来实现这一点。尝试在输出层之前使用Flatten ()
,或者使用GlobalAveragePooling1D()
或GlobalMaxPooling1D()
。