Caffe框架源码剖析(8)—激活函数层ReLULayer

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tianrolin/article/details/52592958

LeNet中使用修正线性单元(Rectified Linear Unit,ReLU)代替Sigmoid作为激活函数,目的是为了加速收敛。激活函数层ReLULayer原理很简单,就是实现了对输入数据的非负处理,将小于零的数据进行了截断。

ReLU

正向传导公式如下,其中negative_slope在程序赋值为0

top_data={bottom_databottom_datanegative_slopebottom_data>0bottom_data0

反向传导时,

lossbottom_data=losstop_datatop_databottom_data={top_difftop_diffnegative_slopebottom_data>0bottom_data0

如果

negative_slope0

则ReLU演变成Leaky-ReLU,可以参考这篇文章:RELU 激活函数及其他相关的函数

下面看一下源代码,relu_layer.hpp文件定义如下,

template <typename Dtype>
class ReLULayer : public NeuronLayer<Dtype> {
 public:
  explicit ReLULayer(const LayerParameter& param)
      : NeuronLayer<Dtype>(param) {}

  virtual inline const char* type() const { return "ReLU"; }

 protected:
  // 重载CPU和GPU正反向传导虚函数
  virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);
  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);

  virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
  virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
};

relu_layer.cpp文件中具体实现一目了然,对照公式很简单,

// CPU正向传导  
template <typename Dtype>  
void ReLULayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,  
    const vector<Blob<Dtype>*>& top) {  
  const Dtype* bottom_data = bottom[0]->cpu_data();  
  Dtype* top_data = top[0]->mutable_cpu_data();  
  const int count = bottom[0]->count();  
  // negative_slope一般取0  
  Dtype negative_slope = this->layer_param_.relu_param().negative_slope();  
  for (int i = 0; i < count; ++i) { 
    top_data[i] = std::max(bottom_data[i], Dtype(0))    // 截断小于0的数据  
        + negative_slope * std::min(bottom_data[i], Dtype(0));  
  }  
}  

// CPU反向传导  
template <typename Dtype>  
void ReLULayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,  
    const vector<bool>& propagate_down,  
    const vector<Blob<Dtype>*>& bottom) {  
  if (propagate_down[0]) {  
    const Dtype* bottom_data = bottom[0]->cpu_data();  
    const Dtype* top_diff = top[0]->cpu_diff();  
    Dtype* bottom_diff = bottom[0]->mutable_cpu_diff();  
    const int count = bottom[0]->count();  
    Dtype negative_slope = this->layer_param_.relu_param().negative_slope();  
    for (int i = 0; i < count; ++i) {  
      // bottom_diff = top_diff * bottom_data
      bottom_diff[i] = top_diff[i] * ((bottom_data[i] > 0)  
          + negative_slope * (bottom_data[i] <= 0));  
    }  
  }  
}  

// 如果CPU_ONLY模式则禁止Forward_gpu和Backward_gpu函数  
#ifdef CPU_ONLY  
STUB_GPU(ReLULayer);  
#endif  

猜你喜欢

转载自blog.csdn.net/tianrolin/article/details/52592958