ValueError,检查目标时出错:预计 dense_1 有 4 个维度

ValueError, Error when checking target: expected dense_1 to have 4 dimensions

我正在尝试微调 MobileNet,但收到以下错误:

ValueError, Error when checking target: expected dense_1 to have 4 dimensions, but got array with shape (10, 14)

我设置目录迭代器的方式是否有任何冲突?

train_batches = ImageDataGenerator(preprocessing_function=keras.applications.mobilenet_v2.preprocess_input).flow_from_directory(
train_path, target_size=(224, 224), batch_size=10)
valid_batches = ImageDataGenerator(preprocessing_function=keras.applications.mobilenet_v2.preprocess_input).flow_from_directory(
valid_path, target_size=(224, 224), batch_size=10)

test_batches = ImageDataGenerator(preprocessing_function=keras.applications.mobilenet_v2.preprocess_input).flow_from_directory(
test_path, target_size=(224, 224), batch_size=10, shuffle=False)

我新的瓶颈层如下:

x=mobile.layers[-6].output
predictions = Dense(14, activation='softmax')(x)

model = Model(inputs=mobile.input, outputs=predictions)

由于 并且考虑到 x 是一个 4D 张量,predictions 张量也将是一个 4D 张量。这就是为什么模型需要 4D 输出(即 expected dense_1 to have 4 dimensions)但你的标签是 2D(即 but got array with shape (10, 14))。要解决这个问题,您需要将 x 作为二维张量。一种方法是使用 Flatten 层:

x = mobile.layers[-6].output
x = Flatten()(x)
predictions = Dense(14, activation='softmax')(x)