loss有一个细节问题就是Loss weights(损失权重),用来表征不同Layer产生的loss的重要性,Layer名称中以Loss结尾表示这是一个会产生loss的Layer,其他的Layer只是单纯的用于中间计算。任何一个Layer都可以被用于产生loss。反向迭代时,一个Layer可以赋予一个非零的loss weight,用于调整中间Layer产生的一些数据、参数。对于不止一个输出(top)的Layer(对应的有非零的loss weight),输出的loss是对所有输出blob的loss的和。Caffe最后输出的loss,是由Net中所有的loss加权得到的。对于loss Layer,loss_weight为非0,对于非loss Layer,loss_weight都是0,所以Layer对网络loss的贡献值也为0。
Pseudocode:
[cpp] view plain copy loss := 0 for layer in layers: for top, loss_weight in layer.tops, layer.loss_weights: loss += loss_weight * sum(top) 这个设置在layer.hpp文件中, 一个protected函数, SetLossWeight() :
[cpp] view plain copy /** * 初始化损失权重---<strong>为每个top blob设置loss weight multiplier blobs(损失权重乘子blobs)</strong>,非LossLayer的top blob的loss weight值为零 * =====!!!! Store non-zero loss weights in the diff blob !!!!=== */ inline void SetLossWeights(const vector<Blob<Dtype>*>& top) { const int num_loss_weights = layer_param_.loss_weight_size();//message Layerparameter中的repeated float loss_weight = 5;表示的是“The amount of weight to assign each top blob in the objective”</strong></em> if (num_loss_weights) { CHECK_EQ(top.size(), num_loss_weights) << "loss_weight must be " "unspecified or specified once per top blob."; for (int top_id = 0; top_id < top.size(); ++top_id) { const Dtype loss_weight = layer_param_.loss_weight(top_id); if (loss_weight == Dtype(0)) { continue; } this->set_loss(top_id, loss_weight);//修改Layer的数据成员loss_,其存储的是loss_weight const int count = top[top_id]->count(); Dtype* loss_multiplier = top[top_id]->mutable_cpu_diff();//返回指向某块Blob的diff所对应的内存空间的指针,并且由于mutable_cpu_diff返回的是void*指针,还有一个类型转换过程 caffe_set(count, loss_weight, loss_multiplier);//loss_multiplier是一个void指针,caffe_set函数表示用loss_weight初始化这块内存,使其能够存储count个loss_weight(when loss_weight!=0),if loss_weight=0,则用0值来初始化.-----这里为blob的每个元素都初始化了一个loss_weight, 那么在后面计算loss时,只要sum(top)就可以了. } } }