最近做项目需要修改Euclidean loss函数,所以就先分析了一下Euclidean loss layer的代码
以gpu版本的为例:
一. 前向函数
template <typename Dtype>
void EuclideanLossLayer<Dtype>::Forward_gpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
int count = bottom[0]->count(); //这里的count就是你的batchsize的大小
caffe_gpu_sub(
count,
bottom[0]->gpu_data(), //网络的输出值
bottom[1]->gpu_data(), //标签值
diff_.mutable_gpu_data());//存储bottom[0] - bottom[1]
Dtype dot;
caffe_gpu_dot(count, diff_.gpu_data(), diff_.gpu_data(), &dot);//做点乘运算
Dtype loss = dot / bottom[0]->num() / Dtype(2); //除以总数再除以2
top[0]->mutable_cpu_data()[0] = loss; //将loss值赋给输出
}
1.首先明确caffe中Euclidean loss函数:(多除了个2,方便后面求梯度时刚好约掉)
其次是代码里面一些变量的意义:
count: count其实等于num*channels*height*width,也就是整个Blob元素的数量,但是因为此层中channels height width都为1,所以这里的count()与num()实际上是相等的,都代表输入图片的数量,也就是batchsize的大小,也即公式里的N
bottom[0]->gpu_data(): 网络的输出值,注意这个变量并不只是单个的输出值,而是包含整个batchsize每张图片的输出值,也就是一个含有N个元素的向量
bottom[1]->gpu_data(): 真实标签值,也是个含有N个元素的向量