Dense layer probably produces InvalidArgumentError: Incompatible shapes: [0,2] vs. [32,2]

Dense layer probably produces InvalidArgumentError: Incompatible shapes: [0,2] vs. [32,2]

设置

我正在使用 Python 3.6, TF 2.4.0 在 Azure DSVM STANDARD_NC6(6 核、56 GB RAM、380 GB 磁盘)上使用 1 个 GPU


parameters/model

我有训练数据:print(xtrain.shape) 形状 (4599, 124, 124, 3) 和火车 | yval 作为分类。

我使用经典生成器

datagen = ImageDataGenerator(
    zoom_range=0.1,
    rotation_range=25,
    width_shift_range=0.1,
    height_shift_range=0.1,
    shear_range=0.15,
    horizontal_flip=True,
    fill_mode="nearest"
    )

datagen.fit(xtrain)

我的模型是有自己头部的基础 mobilenetv2:

baseModel = MobileNetV2(weights="imagenet", 
                        include_top=False, 
                        input_tensor=Input(shape=(224, 224,3)), 
                        #input_shape=(224, 224, 3),
                        )

headModel = baseModel.output
headModel = AveragePooling2D(pool_size=(7, 7))(headModel)
headModel = Flatten(name="flatten")(headModel)
headModel = Dense(64, activation="relu")(headModel)
headModel = Dropout(0.5)(headModel)
headModel = Dense(2, activation="softmax")(headModel)

model = Model(inputs=baseModel.input, outputs=headModel)

for layer in baseModel.layers:
    layer.trainable = False

model.compile(loss="mse", optimizer='adam', metrics=["accuracy"])

当我现在拟合模型时

Batch_Size=1

h = model.fit(
datagen.flow(xtrain, ytrain, batch_size=Batch_Size),
steps_per_epoch=len(xtrain) // Batch_Size,
validation_data=(xval, yval),
validation_steps=len(xval) // Batch_Size,
epochs=EPOCHS,
callbacks=[model_checkpoint_callback, Board])

错误

我收到错误(都一样,但随批量大小和损失函数而变化)

当我将 batch_size=1loss=msecategorical_crossentropy 或其他人一起使用时,模型进行训练但在纪元结束时抛出以下错误

ValueError: Input 0 is incompatible with layer model_2: expected shape=(None, 224, 224, 3), found shape=(1, 124, 124, 3)

如果我使用 1 以上的 batch_size,例如 32 和 loss=categorical_crossentropy,则在训练之前会抛出错误:

InvalidArgumentError: Incompatible shapes: [32] vs. [0] [[node Equal (defined at :12) ]] [Op:__inference_train_function_65107]

loss=mse

InvalidArgumentError: Incompatible shapes: [0,2] vs. [32,2] [[node gradient_tape/mean_squared_error/BroadcastGradientArgs (defined at :12) ]] [Op:__inference_train_function_81958]

如果我更改最后一个 Dense Layer 的 Hidden units,错误会变成那个。例如

...
headModel = Dense(5, activation="softmax")(headModel)

结果

InvalidArgumentError: Incompatible shapes: [0,5] vs. [32,2]

显然,正确的输入形状在某处丢失了。特别是批量大小(第二维基于密集的隐藏单元)。有人有想法吗? 谢谢

我在 git 上检查了这个旧线程中的许多答案:https://github.com/kuza55/keras-extras/issues/7 但在那里找不到解决方案。

您输入网络的数据必须与网络的输入具有相同的形状。您正在尝试为接受尺寸为 224x224x3 的图像的网络提供尺寸为 124x124x3.

的数据

您可以:

  • 加载具有兼容输入维度的 mobilenet 网络

    baseModel = MobileNetV2(weights=None, 
                      include_top=False, 
                      input_tensor=Input(shape=(124, 124,3)), 
                      )
    

    这种方法的缺点是无法使用预训练权重。

  • 将输入数据重塑为模型输入的大小。在这种情况下,将 124xx124 图片大小调整为 224x224。方法有很多,但如果你愿意保留ImageDataGenerator,我建议你提前做。