ValueError,检查目标时出错:预期density_1具有4维

时间:2018-11-04 19:32:38

标签: tensorflow keras deep-learning conv-neural-network transfer-learning

我正在尝试微调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)

1 个答案:

答案 0 :(得分:1)

由于Dense layer is applied on the last axis of its input并考虑到x是4D张量的事实,因此predictions张量也将是4D张量。这就是为什么模型需要4D输出(即expected dense_1 to have 4 dimensions)但您的标签是2D(即but got array with shape (10, 14))的原因。要解决此问题,您需要将x设为2D张量。一种实现方法是使用Flatten层:

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