如何在keras中定义自定义激活函数的导数

时间:2018-08-08 19:54:14

标签: machine-learning keras deep-learning activation-function

我有一个自定义激活函数及其派生类,尽管我可以使用该自定义激活函数,但我不知道如何告诉keras它的派生类是什么。

似乎它找到了自己,但是我有一个必须在函数及其派生函数之间共享的参数,所以我该怎么做?

我知道在张量流中有一个相对简便的方法,但是我不知道如何在keras here is how you do it in tensorflow

中实现它。

编辑:基于我得到的答案,可能我不够清楚。我想要的是为我的激活函数实现自定义派生类,以便它在反向传播期间使用我的派生类。我知道如何实现自定义激活功能。

1 个答案:

答案 0 :(得分:1)

看看定义Keras激活功能的源代码:

keras/activations.py

例如:

def relu(x, alpha=0., max_value=None):
    """Rectified Linear Unit.

    # Arguments
        x: Input tensor.
        alpha: Slope of the negative part. Defaults to zero.
        max_value: Maximum value for the output.

    # Returns
        The (leaky) rectified linear unit activation: `x` if `x > 0`,
        `alpha * x` if `x < 0`. If `max_value` is defined, the result
        is truncated to this value.
    """
    return K.relu(x, alpha=alpha, max_value=max_value)

Keras层还如何调用激活函数:self.activation = activations.get(activation) activation可以是字符串或可调用的。

因此,类似地,您可以定义自己的激活函数,例如:

def my_activ(x, p1, p2):
    ...
    return ...

假设您想在Dense层中使用此激活,只需将函数放置如下:

x = Dense(128, activation=my_activ(p1, p2))(input)

如果您要实现自己的派生:

如果您的激活函数是用Tensorflow / Keras函数编写的,这些函数的操作是可微分的(例如K.dot(), tf.matmul(), tf.concat() etc.),则导数将通过自动微分https://en.wikipedia.org/wiki/Automatic_differentiation获得。在那种情况下,您不需要编写自己的派生词。

如果您仍要重写导数,请查看此文档https://www.tensorflow.org/extend/adding_an_op,在此处需要使用tf.RegisterGradient注册渐变。