Caffe代码阅读8:absval_layer层的实现

这一层比较简单:主要就是求绝对值,反传部分的代码也很简单

里头用到了caffe_abs这个函数以及caffe_cpu_sign这两个函数

需要注意的是caffe_cpu_sign在math_functions.hpp里头定义得比较特别

在math_functions.hpp里只有caffe_sign,通过一个宏定义生成了caffe_cpu_sign这个函数

整体来说没啥特别的内容,直接上代码吧。

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #include <vector>  
  2.   
  3. #include "caffe/layers/absval_layer.hpp"  
  4. #include "caffe/util/math_functions.hpp"  
  5.   
  6. namespace caffe {  
  7.   
  8. template <typename Dtype>  
  9. void AbsValLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom,  
  10.       const vector<Blob<Dtype>*>& top) {  
  11.   NeuronLayer<Dtype>::LayerSetUp(bottom, top);  
  12.   CHECK_NE(top[0], bottom[0]) << this->type() << " Layer does not "  
  13.     "allow in-place computation.";  
  14. }  
  15.   
  16. template <typename Dtype>  
  17. void AbsValLayer<Dtype>::Forward_cpu(  
  18.     const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {  
  19.   const int count = top[0]->count();  
  20.   Dtype* top_data = top[0]->mutable_cpu_data();  
  21.   caffe_abs(count, bottom[0]->cpu_data(), top_data);  
  22. }  
  23.   
  24. template <typename Dtype>  
  25. void AbsValLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,  
  26.     const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {  
  27.   const int count = top[0]->count();  
  28.   // 前面一层关于本层top的偏导  
  29.   const Dtype* top_diff = top[0]->cpu_diff();  
  30.   if (propagate_down[0]) {  
  31.     const Dtype* bottom_data = bottom[0]->cpu_data();  
  32.     Dtype* bottom_diff = bottom[0]->mutable_cpu_diff();  
  33.     // 将bottom_data里头的每个元素的正负值复制到bottom_diff  
  34.     caffe_cpu_sign(count, bottom_data, bottom_diff);  
  35.     // 计算偏导数计算关于本层bottom的偏导  
  36.     // 将关于top的偏导乘以当前层bottom中每个数据的符号  
  37.     caffe_mul(count, bottom_diff, top_diff, bottom_diff);  
  38.   }  
  39. }  
  40.   
  41. #ifdef CPU_ONLY  
  42. STUB_GPU(AbsValLayer);  
  43. #endif  
  44.   
  45. INSTANTIATE_CLASS(AbsValLayer);  
  46. REGISTER_LAYER_CLASS(AbsVal);  
  47.   
  48. }  // namespace caffe  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值