zoukankan      html  css  js  c++  java
  • keras中激活函数自定义(以mish函数为列)

     若使用keras框架直接编辑函数调用会导致编译错误。因此,有2种方法可以实现keras的调用,其一使用lamda函数调用,

    其二使用继承Layer层调用(如下代码)。如果使用继承layer层调用,那你可以将你想要实现的方式,通过call函数编辑,而

    call函数的参数一般为输入特征变量[batch,h,w,c],具体实现如下代码:

    class Mish(Layer):
    '''
    Mish Activation Function.
    .. math::
    mish(x) = x * tanh(softplus(x)) = x * tanh(ln(1 + e^{x}))
    tanh=(1 - e^{-2x})/(1 + e^{-2x})
    Shape:
    - Input: Arbitrary. Use the keyword argument `input_shape`
    (tuple of integers, does not include the samples axis)
    when using this layer as the first layer in a model.
    - Output: Same shape as the input.
    Examples:
    >>> X_input = Input(input_shape)
    >>> X = Mish()(X_input)
    '''

    def __init__(self, **kwargs):
    super(Mish, self).__init__(**kwargs)
    self.supports_masking = True

    def call(self, inputs):
    return inputs * K.tanh(K.softplus(inputs))

    def get_config(self):
    config = super(Mish, self).get_config()
    return config

    def compute_output_shape(self, input_shape):
    '''
    compute_output_shape(self, input_shape):为了能让Keras内部shape的匹配检查通过,
    这里需要重写compute_output_shape方法去覆盖父类中的同名方法,来保证输出shape是正确的。
    父类Layer中的compute_output_shape方法直接返回的是input_shape这明显是不对的,
    所以需要我们重写这个方法。所以这个方法也是4个要实现的基本方法之一。
    '''
    return input_shape





    有了mish激活函数,该如何调呢?以下代码简单演示其调用方式:

    cov1=conv2d(卷积参数)(input) # 将输入input进行卷积操作
    Mish()(cov1)  # 将卷积结果输入定义的激活类中,实现mish激活







  • 相关阅读:
    [多线程学习笔记]条件变量
    [多线程学习笔记]互斥量
    [多线程学习笔记]线程生命周期
    多定时器队列
    双向环形链表
    多目录,多可执行文件的Makfile的编写
    大工匠
    从零开始打造我的计算机系统【运行效果】
    从零开始打造我的计算机系统【交叉汇编器】
    C中的回调函数
  • 原文地址:https://www.cnblogs.com/tangjunjun/p/12839457.html
Copyright © 2011-2022 走看看