【问题标题】:How to implement PReLU activation in Tensorflow?如何在 Tensorflow 中实现 PReLU 激活?
【发布时间】:2017-02-19 21:39:15
【问题描述】:

Parametric Rectified Linear Unit (PReLU) 是一个有趣且广泛使用的激活函数。 Tensorflow (reference link) 似乎不提供 PReLU。我知道KerasTFLearn等更高级的库都有它的实现。

我想知道如何在Tensorflow中实现PReLU

【问题讨论】:

  • 这里是 PRelu 的 TFLearn implementation。您不想依赖 TFLearn 的任何具体原因?
  • 我已经是TFLearn的用户了。但是,在这里我问这个问题是为了了解更多关于 Tensorflow 的基本实现。

标签: tensorflow


【解决方案1】:

PReLU 的实现似乎直接基于高级库的 PreLU 实现(参见:KerasTFLearnTensorLayer) .我的代码如下:

def parametric_relu(_x):
  alphas = tf.get_variable('alpha', _x.get_shape()[-1],
                       initializer=tf.constant_initializer(0.0),
                        dtype=tf.float32)
  pos = tf.nn.relu(_x)
  neg = alphas * (_x - abs(_x)) * 0.5

  return pos + neg

【讨论】:

  • neg = alphas * (-x - abs(_x)) * 0.5 这个词是怎么出现的
【解决方案2】:

虽然tf.maximum的解法效率很高,但不能代表凹函数。这是一个解决方案,可以:

def prelu(_x, scope=None):
    """parametric ReLU activation"""
    with tf.variable_scope(name_or_scope=scope, default_name="prelu"):
        _alpha = tf.get_variable("prelu", shape=_x.get_shape()[-1],
                                 dtype=_x.dtype, initializer=tf.constant_initializer(0.1))
        return tf.maximum(0.0, _x) + _alpha * tf.minimum(0.0, _x)

【讨论】:

    【解决方案3】:

    我认为使用tf.maximum 实现起来要容易得多

    我的实现如下

    import tensorflow as tf
    
    def PReLU(_x, name=None):
      if name is None:
        name = "alpha"
      _alpha = tf.get_variable(name,
                               shape=_x.get_shape(),
                               initializer=tf.constant_initializer(0.0),
                               dtype=_x.dtype)
    
      return tf.maximum(_alpha*_x, _x)
    

    【讨论】:

      【解决方案4】:
      【解决方案5】:

      您在 Keras 中将其作为层实现(从 2.3.0 版本开始):tf.keras.layers.PReLU。这是文档页面的链接:https://www.tensorflow.org/api_docs/python/tf/keras/layers/PReLU

      如果您想使用 TFLite 部署模型并使用 NNAPI 等委托,这将非常有用,因为有专门针对 NNAPI的实现

      【讨论】:

        【解决方案6】:

        只是对 Hasnat 答案的补充:(我还不能发表评论..

        如果你想要多个不同的 prelu 层,你应该设置一个 'name' 参数:

        def prelu(_x, name):
        """
        Parametric ReLU
        """
        alphas = tf.get_variable(name, _x.get_shape()[-1],
                           initializer=tf.constant_initializer(0.1),
                            dtype=tf.float32, trainable=True)
        pos = tf.nn.relu(_x)
        neg = alphas * (_x - abs(_x)) * 0.5
        
        return pos + neg
        

        然后你可以给每个prelu一个不同的名字,例如:

        prelu(x, "alpha1")
        
        # convolution or other
        
        prelu(x, "alpha2")
        

        这将解决错误:

        变量 alpha 已经存在,不允许。你的意思是在 VarScope 中设置reuse=True 还是reuse=tf.AUTO_REUSE?

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-02-27
          • 1970-01-01
          • 2010-09-20
          • 2019-05-20
          • 2020-04-09
          • 1970-01-01
          相关资源
          最近更新 更多