【问题标题】:Keras remove activation function of last layerKeras 去掉最后一层的激活函数
【发布时间】:2020-09-12 17:13:55
【问题描述】:

我想将 ResNet50 与 Imagenet 权重一起使用。

ResNet50的最后一层是(来自here

x = layers.Dense(1000, activation='softmax', name='fc1000')(x)

我需要保留这一层的权重,但删除 softmax 函数。

我想手动更改它,使我的最后一层看起来像这样

x = layers.Dense(1000, name='fc1000')(x)

但权重保持不变。

目前我这样称呼我的网

resnet = Sequential([
    Input(shape(224,224,3)),
    ResNet50(weights='imagenet', input_shape(224,224,3))
    ])

我需要输入层,否则 model.compile 会说占位符未填充。

【问题讨论】:

    标签: tensorflow keras


    【解决方案1】:

    一般有两种方法可以实现:

    快捷方式-支持的功能:

    要改变最后一层的激活函数,你可以传递一个参数classifier_activation
    因此,为了一起摆脱激活,您的模块可以这样调用:

    import tensorflow as tf
    
    resnet = tf.keras.Sequential([
        tf.keras.layers.Input(shape=(224,224,3)),
        tf.keras.applications.ResNet50(
            weights='imagenet', 
            input_shape=(224,224,3),
            pooling="avg",
            classifier_activation=None
            )
        ])
    

    但是,如果您想要不同的功能,这将不起作用,而 Keras classifer_activation 参数不支持(例如自定义激活功能)。

    要实现这一点,您可以使用变通解决方案:

    Long way - 复制模型的权重

    此解决方案建议将原始模型的权重复制到您的自定义模型上。这种方法之所以有效,是因为除了激活函数之外,您并没有改变模型的架构。

    您需要:
    1.下载原始模型。
    2. 保存它的权重。
    3. 声明模型的修改版本(在您的情况下,没有激活函数)。
    4. 设置新模型的权重。

    下面的 sn-p 更详细地解释了这个概念:

    import tensorflow as tf
    
    # 1. Download original resnet
    
    resnet = tf.keras.Sequential([
        tf.keras.layers.Input(shape=(224,224,3)),
        tf.keras.applications.ResNet50(
            weights='imagenet', 
            input_shape=(224,224,3),
            pooling="avg"
            )
        ])
    
    # 2. Hold weights in memory:
    imagenet_weights = resnet.get_weights()
    
    # 3. Declare the model, but without softmax
    resnet_no_softmax = tf.keras.Sequential([
        tf.keras.layers.Input(shape=(224,224,3)),
        tf.keras.applications.ResNet50(
            include_top=False,
            weights='imagenet', 
            input_shape=(224,224,3),
            pooling="avg"
            ),
        tf.keras.layers.Dense(1000, name='fc1000')
    ])
    
    # 4. Pass the imagenet weights onto the second resnet
    resnet_no_softmax.set_weights(imagenet_weights)
    
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-26
      • 1970-01-01
      • 2016-06-03
      • 1970-01-01
      • 2020-12-05
      • 2023-03-13
      • 2017-08-10
      相关资源
      最近更新 更多