Tensorflow中实现leakyRelu Tensorflow中实现leakyRelu操作(高效)


ReLU、LeakyReLU

ReLU作为激活函数被广泛应用于各种深度神经网络中。在这篇博客中,我主要记录一下它和它的变种在caffe中的实现。 
先看下来自wikipedia的一张示意图,图中蓝色的线表示的就是ReLU函数。 
ReLU 
ReLU激活函数极为f(x)=max(0,x)f(x)=max(0,x)。而LeakyReLU则是其变体f(x)=max(0,x)+negative_slope×min(0,x)f(x)=max(0,x)+negative_slope×min(0,x),其中,negative_slopenegative_slope是一个小的非零数。

综上,在caffe中,ReLU和LeakyReLU都包含在relu_layer中。 
在后向传播过程中,ReLU做如下运算: 

Ex={0Eyifx0ifx>0∂E∂x={0ifx≤0∂E∂yifx>0

而变体的LeakyReLU则做: 
Ex=νEyEyifx0ifx>0∂E∂x={ν∂E∂yifx≤0∂E∂yifx>0

接下来,我们来看看ReLU层的参数。

// Message that stores parameters used by ReLULayer
message ReLUParameter {
  // Allow non-zero slope for negative inputs to speed up optimization
  // Described in:
  // Maas, A. L., Hannun, A. Y., & Ng, A. Y. (2013). Rectifier nonlinearities
  // improve neural network acoustic models. In ICML Workshop on Deep Learning
  // for Audio, Speech, and Language Processing.
  optional float negative_slope = 1 [default = 0]; //如之前分析的,默认值0即为ReLU,非零则为LeakyReLU
  enum Engine {
    DEFAULT = 0;
    CAFFE = 1;
    CUDNN = 2;
  }
  optional Engine engine = 2 [default = DEFAULT]; //运算引擎选择,一般选择默认
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

PReLU

PReLU,即Parametric ReLU,是何凯明组提出的一种改进ReLU。它的数学表示为yi=max(0,xi)+ai×min(0,xi)yi=max(0,xi)+ai×min(0,xi) ,其中aa是可学习参数。当aa为固定的非零较小数时,它等价于LeakyReLU;当它为0时,PReLU等价于ReLU。它的后向传播进行如下计算: 

Exi=aiEyiEyiifxi0ifxi>0∂E∂xi={ai∂E∂yiifxi≤0∂E∂yiifxi>0

参数 aa 的更新公式如下: 
Eai={xixiEyi0ifxi0ifxi>0∂E∂ai={∑xixi∂E∂yiifxi≤00ifxi>0

PReLU的实现不包含在ReLU中,主要是有可学习参数 aa ,它的实现包含在prelu_layer中。

message PReLUParameter {
  // Parametric ReLU described in K. He et al, Delving Deep into Rectifiers:
  // Surpassing Human-Level Performance on ImageNet Classification, 2015.

  // Initial value of a_i. Default is a_i=0.25 for all i.
  optional FillerParameter filler = 1;  //默认填充,a_i的初始值为0.25
  // Whether or not slope parameters are shared across channels.
  optional bool channel_shared = 2 [default = false]; //是否通道共享参数,默认为不共享
}


Tensorflow中实现leakyRelu操作(高效)

从github上转来,实在是厉害的想法,什么时候自己也能写出这种精妙的代码就好了 
原地址: 
简易高效的LeakyReLu实现

代码如下: 我做了些改进,因为实在tensorflow中使用,就将原来的abs()函数替换成了tf.abs()

 
   

import tensorflow as tfdef LeakyRelu(x, leak=0.2, name="LeakyRelu"): with tf.variable_scope(name): f1 = 0.5 * (1 + leak) f2 = 0.5 * (1 - leak) return f1 * x + f2 * tf.abs(x) # 这里和原文有不一样的,我没试验过原文的代码,但tf.abs()肯定是对的

猜你喜欢

转载自blog.csdn.net/jacke121/article/details/80568520