使用 Keras 将 Dropout 层添加到 Segmentation_Models Resnet34

Adding Dropout Layers to Segmentation_Models Resnet34 with Keras

我想使用Segmentation_Models UNet(与ResNet34 Backbone)进行不确定性估计,所以我想在上采样部分添加一些Dropout层。该模型不是顺序的,所以我想我必须将一些输出重新连接到新的 Dropout 层,并将下一层输入重新连接到 Dropout 的输出。

我不确定,正确的方法是什么。我目前正在尝试这个:

# create model
model = sm.Unet('resnet34', classes=1, activation='sigmoid', encoder_weights='imagenet')

# define optimizer, loss and metrics
optim = tf.keras.optimizers.Adam(0.001)
total_loss = sm.losses.binary_focal_dice_loss # or sm.losses.categorical_focal_dice_loss
metrics = ['accuracy', sm.metrics.IOUScore(threshold=0.5), sm.metrics.FScore(threshold=0.5)]

# get input layer
updated_model_layers = model.layers[0]

# iterate over old model and add Dropout after given Convolutions
for layer in model.layers[1:]:
    # take old layer and add to new Model
    updated_model_layers = layer(updated_model_layers.output)

    # after some convolutions, add Dropout
    if layer.name in ['decoder_stage0b_conv', 'decoder_stage0a_conv', 'decoder_stage1a_conv', 'decoder_stage1b_conv', 'decoder_stage2a_conv',
                          'decoder_stage2b_conv', 'decoder_stage3a_conv', 'decoder_stage3b_conv', 'decoder_stage4a_conv']:
          
        if (uncertain):
            # activate dropout in predictions
            next_layer = Dropout(0.1) (updated_model_layers, training=True)
        else:
            # add dropout layer
            next_layer = Dropout(0.1) (updated_model_layers)

        # add reconnected Droput Layer
        updated_model_layers = next_layer
model = Model(model.layers[0], updated_model_layers)

这会引发以下错误:AttributeError: 'KerasTensor' object has no attribute 'output'

但我觉得我做错了什么。有人对此有解决方案吗?

您使用的 Resnet 模型有问题。它很复杂并且具有添加层和连接层(我猜是残差层),它们将来自几个“子网络”的张量列表作为输入。换句话说,网络不是线性的,所以你不能用一个简单的循环遍历模型。

关于你的错误,在你的代码循环中:层是一个层,updated_model_layers是一个张量(函数API)。因此,updated_model_layers.output 不存在。你把两者混淆了一点