這里說一下euclidean_loss_layer.cpp關於該歐式loss層的解析,代碼如下:
#include <vector> #include "caffe/layers/euclidean_loss_layer.hpp" #include "caffe/util/math_functions.hpp" namespace caffe { template <typename Dtype> //reshape步驟:驗證以及將loss層的誤差項的形狀進行校正 void EuclideanLossLayer<Dtype>::Reshape( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { LossLayer<Dtype>::Reshape(bottom, top); CHECK_EQ(bottom[0]->count(1), bottom[1]->count(1)) << "Inputs must have the same dimension."; diff_.ReshapeLike(*bottom[0]); } 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_,它是loss層自定義的一個blob,用來存儲終極的誤差項,然后基於這個blob進行反向傳播,這兒的值即(f(x) - y); Dtype dot = caffe_cpu_dot(count, diff_.cpu_data(), diff_.cpu_data()); Dtype loss = dot / bottom[0]->num() / Dtype(2); top[0]->mutable_cpu_data()[0] = loss; //按照定義計算loss } 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]) { const Dtype sign = (i == 0) ? 1 : -1; const Dtype alpha = sign * top[0]->cpu_diff()[0] / bottom[i]->num(); //注意這里的top[0]->cpu_diff()[0]的值不是傳遞的,而是之前已經初始化好的,初始化過程在layer.hpp的SetLossWeights()函數中,值為(loss_weight * 1),即loss_weight; caffe_cpu_axpby( //功能: b = alpha * a + beta * b bottom[i]->count(), // count alpha, // alpha diff_.cpu_data(), // a, diff_即該loss層的誤差項,即(f(x) - y) Dtype(0), // beta bottom[i]->mutable_cpu_diff()); // b } } } #ifdef CPU_ONLY STUB_GPU(EuclideanLossLayer); #endif INSTANTIATE_CLASS(EuclideanLossLayer); REGISTER_LAYER_CLASS(EuclideanLoss); //在caffe的工廠中注冊這個函數,從而在對應的prototxt中就可以使用“ type:EuclideanLoss ”這個type了 } // namespace caffe
關於caffe_set , caffe_sub , caffe_cpu_axpby等等的解釋可以參考:https://blog.csdn.net/seven_first/article/details/47378697#9caffeadd-caffesub-caffemul-caffediv-%E5%87%BD%E6%95%B0