这里说一下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