caffe源码——Euclidean Loss是怎么实现的

引用:

http://blog.csdn.net/fangjin_kl/article/details/54131144

损失函数:


的偏导:

的偏导:-

forward_cpu:

template <typename Dtype>
void EuclideanLossLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
    const vector<Blob<Dtype>*>& top) {
  int count = bottom[0]->count();
  caffe_sub(
      count,
      bottom[0]->cpu_data(),
      bottom[1]->cpu_data(),
      diff_.mutable_cpu_data());//diff_ = bottom[0] - bottom[1]
  Dtype dot = caffe_cpu_dot(count, diff_.cpu_data(), diff_.cpu_data());  // dot = ||diff_||^2
  Dtype loss = dot / bottom[0]->num() / Dtype(2);//输出的loss
  top[0]->mutable_cpu_data()[0] = loss;
}

backward_cpu:

template <typename Dtype>
void EuclideanLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
    const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {
  for (int i = 0; i < 2; ++i) {
    if (propagate_down[i]) {//对于输入的label bottom propagate_dowm 为0
      const Dtype sign = (i == 0) ? 1 : -1;//由于diff_ = bottom[0] - bottom[1]
      const Dtype alpha = sign * top[0]->cpu_diff()[0] / bottom[i]->num();
      caffe_cpu_axpby(
          bottom[i]->count(),              // count
          alpha,                              // alpha
          diff_.cpu_data(),                   // a
          Dtype(0),                           // beta
          bottom[i]->mutable_cpu_diff());  // b
    }//bottom[i]->mutable_cpu_diff()) = alpha*diff_.cpu_data()
  }
}
forward_cpu里就是按照损失函数的样式计算损失,并且将损失保存到top[0]->cpu_data()[0]中。其中有用的是计算得到的diff_->cpu_data()。

backward_cpu里的两个for循环就是就是分别计算对的偏导和对对的偏导,其中sign是正负号,用于控制是对还是对求偏导,而top[0]->cpu_diff()[0]是在网络的定义中(即prototxt文件中),loss层的定义中设置的loss_weight:1.0,即top[0]->cpu_diff()[0]=1.0,则alpha就是1/n或者-1/n,而diff_.cpu_data()=-,caffe_cpu_axpby()得到了1*(-)/n即对的偏导,和-1*(-)/n即对的偏导,并把结果存到bottom[i]->cpu_diff()中,用以传向前面的层。


更多参考:

http://blog.csdn.net/seashell_9/article/details/68064294

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值