ValueError: Error when checking target: expected dense_35 to have 4 dimensions, but got array with shape (1157, 1)

ValueError: Error when checking target: expected dense_35 to have 4 dimensions, but got array with shape (1157, 1)

我有下面给出形状的训练和测试图像数据。

X_test.shape , y_test.shape , X_train.shape , y_train.shape
    ((277, 128, 128, 3), (277, 1), (1157, 128, 128, 3), (1157, 1))

我正在训练一个模型

def baseline_model():
    filters = 100
    model = Sequential()
    model.add(Conv2D(filters, (3, 3), input_shape=(128, 128, 3), padding='same', activation='relu'))
    #model.add(Dropout(0.2))
    model.add(BatchNormalization())
    model.add(Conv2D(filters, (3, 3), activation='relu', padding='same'))
    model.add(BatchNormalization())

    model.add(MaxPooling2D(pool_size=(2, 2)))
    #model.add(Flatten())

    model.add(Conv2D(filters, (3, 3), activation='relu', padding='same'))
    model.add(BatchNormalization())
    model.add(Conv2D(filters, (3, 3), activation='relu', padding='same'))
    model.add(Activation('linear'))
    model.add(BatchNormalization())

    model.add(Dense(512, activation='relu'))
    model.add(Dense(num_classes, activation='softmax'))
    # Compile model
    lrate = 0.01
    epochs = 10
    decay = lrate/epochs
    sgd = SGD(lr=lrate, momentum=0.9, decay=decay, nesterov=False)
    model.compile(loss='sparse_categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])

    print(model.summary())
    return model

但我收到以下错误消息

Error when checking target: expected dense_35 to have 4 dimensions, but got array with shape (1157, 1)

请告诉我我犯了什么错误以及如何解决这个问题。我附上了模型摘要的快照

虽然dense_35需要输入4维数据,但根据错误,网络输入的是2维数据,即标签向量。

您可能忘记做的一件事是在第一个 Dense 层之前添加一个 Flatten 层:

model.add(BatchNormalization())

model.add(Flatten()) # flatten the output of previous layer before feeding it to Dense layer
model.add(Dense(512, activation='relu'))

你需要它,因为 Dense 图层不会展平它的输入;相反,.