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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章