【问题标题】:Adding Dropout Layers to Segmentation_Models Resnet34 with Keras使用 Keras 将 Dropout 层添加到 Segmentation_Models Resnet34
【发布时间】:2021-12-12 00:15:20
【问题描述】:

我想使用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'

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

【问题讨论】:

    标签: python tensorflow machine-learning keras tf.keras


    【解决方案1】:

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

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

    【讨论】:

    • 你是对的。我通过分叉 segment_models 并编辑 build_model() 函数本身来解决它。之后在非序列模型中添加层似乎有点复杂。
    猜你喜欢
    • 2021-12-12
    • 2021-03-27
    • 1970-01-01
    • 1970-01-01
    • 2019-08-09
    • 2019-05-22
    • 1970-01-01
    • 2019-06-16
    • 2019-12-22
    相关资源
    最近更新 更多