【问题标题】:how to define the derivative of a custom activation function in keras如何在keras中定义自定义激活函数的导数
【发布时间】:2019-01-16 04:31:07
【问题描述】:

我有一个自定义激活函数及其导数,虽然我可以使用自定义激活函数但我不知道如何告诉 keras 它的导数是什么。

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

我知道在 tensorflow 中有一种相对简单的方法可以做到这一点,但我不知道如何在 keras 中实现它here is how you do it in tensorflow

编辑:根据我得到的答案,我可能还不够清楚。我想要的是为我的激活函数实现一个自定义导数,以便它在反向传播期间使用我的导数。我知道如何实现自定义激活函数。

【问题讨论】:

  • Keras 使用 tensorflow,因此,将其定义为 tensorflow op。
  • 正如我所说,我不知道如何在 keras 中实现它
  • 在张量流中实现。 Keras 将使用您的 tensorflow 函数。在一个层中使用activation=yourTensorflowFunc。或者使用激活层Activation(yourTensorflowFunc)
  • 这不是我的问题,我知道如何实现我自己的激活函数,我想要的是实现它在反向传播期间使用的导数
  • 这就是我想说的:按照您的说明在“张量流”中实现您的自定义激活和自定义衍生。 Keras“确实使用了 tensorflow 函数”。

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


【解决方案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 注册您的渐变

【讨论】:

  • 我知道如何实现我自己的激活函数,我想要的是实现它在反向传播期间使用的自定义导数
猜你喜欢
  • 2020-05-29
  • 2018-08-30
  • 2017-10-10
  • 2019-12-19
  • 2018-04-15
  • 2018-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多