【caffe解读】 caffe从数学公式到代码实现4-认识caffe自带的7大loss
文章首發(fā)于微信公眾號(hào)《與有三學(xué)AI》
[caffe解讀] caffe從數(shù)學(xué)公式到代碼實(shí)現(xiàn)4-認(rèn)識(shí)caffe自帶的7大lossz
本節(jié)說(shuō)caffe中常見(jiàn)loss的推導(dǎo),具體包含下面的cpp。
multinomial_logistic_loss_layer.cpp
softmax_loss_layer.cpp
euclidean_loss_layer.cpp
sigmoid_cross_entropy_loss_layer.cpp
contrastive_loss_layer.cpp
hinge_loss_layer.cpp
infogain_loss_layer.cpp
?
01 multinomial_logistic_loss_layer.cpp
數(shù)學(xué)定義
x是輸入,y是label,l是loss
上述式只有當(dāng)樣本i屬于第k類時(shí),y?k=1,其他情況?y?k=0,我們計(jì)不為0的?y?k=y。
forward?&?backward
forward對(duì)所有求和,注意此處沒(méi)有對(duì)圖像維度的像素進(jìn)行歸一化,只對(duì)batch?size維度進(jìn)行歸一化,num就是batchsize,這與下面的softmaxlosslayer是不一樣的。
voidMultinomialLogisticLossLayer<Dtype>::Forward_cpu(
const?vector<Blob<Dtype>*>&?bottom,?constvector<Blob<Dtype>*>&?top)?{
const?Dtype*?bottom_data?=?bottom[0]->cpu_data();
const?Dtype*?bottom_label?=?bottom[1]->cpu_data();
int?num?=?bottom[0]->num();
int?dim?=?bottom[0]->count()?/?bottom[0]->num();
Dtype?loss?=?0;
for?(int?i?=?0;?i?<?num;?++i)?{
int?label?=?static_cast<int>(bottom_label[i]);
Dtype?prob?=?std::max(?bottom_data[i?*?dim?+?label],Dtype(kLOG_THRESHOLD));
loss?-=?log(prob);
}
top[0]->mutable_cpu_data()[0]?=?loss?/?num;
}
backward可以自己去看,很簡(jiǎn)單就不說(shuō)了
?
02 softmax_layer.cpp
數(shù)學(xué)定義
softmax是我們最熟悉的了,分類任務(wù)中使用它,分割任務(wù)中依然使用它。Softmax?loss實(shí)際上是由softmax和cross-entropy?loss組合而成,兩者放一起數(shù)值計(jì)算更加穩(wěn)定。
令z是softmax_with_loss層的輸入,f(z)是softmax的輸出,則
單個(gè)像素i的softmax?loss等于cross-entropy?error如下
展開(kāi)上式:
在網(wǎng)絡(luò)中,z是即bottom?blob,l(y,z)是top?blob,反向傳播時(shí)就是要根據(jù)top?blob?diff得到bottom?blob?diff,所以要得到?
下面求loss對(duì)z的第k個(gè)節(jié)點(diǎn)的梯度
可見(jiàn),傳給groundtruth?label節(jié)點(diǎn)和非groundtruth?label是的梯度是不一樣的。
forward就不看了,看看backward吧。
Dtype*?bottom_diff?=?bottom[0]->mutable_cpu_diff();
const?Dtype*?prob_data?=?prob_.cpu_data();
caffe_copy(prob_.count(),?prob_data,?bottom_diff);
const?Dtype*?label?=?bottom[1]->cpu_data();
int?dim?=?prob_.count()?/?outer_num_;
int?count?=?0;
for?(int?i?=?0;?i?<?outer_num_;?++i)?{
for?(int?j?=?0;?j?<?inner_num_;?++j)?{
const?int?label_value?=?static_cast<int>(label[i?*inner_num_?+
j]);
if?(has_ignore_label_?&&?label_value?==ignore_label_)?{
for?(int?c?=?0;?c?<?bottom[0]->shape(softmax_axis_);++c)?{
bottom_diff[i?*?dim?+?c?*?inner_num_?+?j]?=?0;
}
}?else?{
bottom_diff[i?*?dim?+?label_value?*?inner_num_?+?j]?-=?1;
++count;
}
}
}
Test_softmax_with_loss_layer.cpp
作為loss層,很有必要測(cè)試一下,測(cè)試也分兩塊,forward和backward。
Forward測(cè)試是這樣的,定義了個(gè)bottom?blob?data和bottom?blob?label,給data塞入高斯分布數(shù)據(jù),給label塞入0~4。
blob_bottom_data_(new
Blob<Dtype>(10,?5,?2,?3)),
blob_bottom_label_(new
Blob<Dtype>(10,?1,?2,?3)),
然后分別ingore其中的一個(gè)label做5次,最后比較,代碼如下。
Dtype?accum_loss?=?0;
for?(int?label?=?0;?label?<?5;?++label)?{
layer_param.mutable_loss_param()->set_ignore_label(label);
layer.reset(new?SoftmaxWithLossLayer<Dtype>(layer_param));
layer->SetUp(this->blob_bottom_vec_,
this->blob_top_vec_);
layer->Forward(this->blob_bottom_vec_,?this->blob_top_vec_);
accum_loss?+=?this->blob_top_loss_->cpu_data()[0];
}
//?Check?that?each?label?was?included?all?but
once.
EXPECT_NEAR(4?*?full_loss,?accum_loss,?1e-4);
至于backwards,直接套用checker.CheckGradientExhaustive就行,它自己會(huì)利用數(shù)值微分的方法和你寫的backwards來(lái)比較精度。
TYPED_TEST(SoftmaxWithLossLayerTest,
TestGradientIgnoreLabel)?{
typedef?typename?TypeParam::Dtype?Dtype;
LayerParameter?layer_param;
//
labels?are?in?{0,?...,?4},?so?we'll?ignore?about?a?fifth?ofthem
layer_param.mutable_loss_param()->set_ignore_label(0);
SoftmaxWithLossLayer<Dtype>?layer(layer_param);
GradientChecker<Dtype>?checker(1e-2,?1e-2,?1701);
checker.CheckGradientExhaustive(&layer,?this->blob_bottom_vec_,
this->blob_top_vec_,?0);
}
?
03 eulidean_loss_layer.cpp
euclidean?loss就是定位檢測(cè)任務(wù)中常用的loss。
數(shù)學(xué)定義:
forward?&?backward
voidEuclideanLossLayer<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();
caffe_cpu_axpby(?bottom[i]->count(),??//?count
alpha,?//?alpha
diff_.cpu_data(),?//?a
Dtype(0),?//?beta
bottom[i]->mutable_cpu_diff());?//?b
}
}
}
testcpp就不說(shuō)了。
?
04 sigmoid_cross_entropy_loss_layer.cpp
與softmax?loss的應(yīng)用場(chǎng)景不同,這個(gè)loss不是用來(lái)分類的,而是用于預(yù)測(cè)概率,所以在loss中,沒(méi)有類別的累加項(xiàng)。
令第i個(gè)節(jié)點(diǎn)輸入Xi?,輸出總loss為l,label為?yi?,則loss定義如下
其中
上式子有個(gè)等價(jià)轉(zhuǎn)換,這是為了更好的理解caffe?中forward的計(jì)算,公式太多我就直接借用了,如果遇到了原作者請(qǐng)通知我添加轉(zhuǎn)載申明。
http://blog.csdn.net/u012235274/article/details/51361290
反向求導(dǎo)公式如下:
在經(jīng)過(guò)上面的轉(zhuǎn)換后,避開(kāi)了數(shù)值計(jì)算不穩(wěn)定的情況,caffe中的源碼是對(duì)整個(gè)的bottom[0]->count進(jìn)行計(jì)算累加的,沒(méi)有區(qū)分label項(xiàng)。
for?(int?i?=?0;?i?<?bottom[0]->count();?++i)?{
const?int?target_value?=?static_cast<int>(target[i]);
if?(has_ignore_label_?&&?target_value?==ignore_label_)?{
continue;
}
loss?-=?input_data[i]?*?(target[i]?-?(input_data[i]?>=0))?-?log(1?+?exp(input_data[i]?-?2?*?input_data[i]?*(input_data[i]?>=?0)));
++valid_count;
}
反向傳播很簡(jiǎn)單就不看了
?
05 contrastive_loss_layer.cpp
有一類網(wǎng)絡(luò)叫siamese?network,它的輸入是成對(duì)的。比如輸入兩張大小相同的圖,網(wǎng)絡(luò)輸出計(jì)算其是否匹配。所采用的損失函數(shù)就是contrastive?loss
數(shù)學(xué)定義:
d就是歐氏距離,y是標(biāo)簽,如果兩個(gè)樣本匹配,則為1,否則為0.?當(dāng)y=1,loss就是歐氏距離,說(shuō)明匹配的樣本距離越大,loss越大。當(dāng)y=0,就是與閾值margin的歐式距離,說(shuō)明不匹配的樣本,歐氏距離應(yīng)該越大越好,超過(guò)閾值最好,loss就等于0.
反向傳播其實(shí)就是分y=1和y=0兩種情況下的euclidean?loss的反向傳導(dǎo),由于與euclidean
loss非常相似,不再贅述。
?
06 hinge_loss_layer.cpp
這是一個(gè)多分類的loss,?也是SVM的目標(biāo)函數(shù),沒(méi)有學(xué)習(xí)參數(shù)的全連接層InnerProductLayer+HingeLossLayer就等價(jià)于SVM。
數(shù)學(xué)定義:
這個(gè)層的輸入bottom[0]是一個(gè)N*C*H*W的blob,其中取值任意值,label就是N*1*1*1,其中存儲(chǔ)的就是整型的label{0,1,2,…,k}。tnk??相當(dāng)于SVM中的 XTW
參考博客http://blog.leanote.com/post/braveapple/Hinge-Loss-%E7%9A%84%E7%90%86%E8%A7%A3
假如預(yù)測(cè)類別數(shù)是K個(gè),正確的label是M,預(yù)測(cè)值為tnk,即是第n個(gè)樣本對(duì)第k類的預(yù)測(cè)值,那么當(dāng)k=M時(shí)。
當(dāng)k!=M時(shí)
其中p=1,p=2分別對(duì)應(yīng)L1范數(shù)和L2范數(shù),以L1為例
Forward
caffe_copy(count,?bottom_data,?bottom_diff);
for?(int?i?=?0;?i?<?num;?++i)?{?bottom_diff[i?*?dim?+static_cast<int>(label[i])]?*=?-1;
}
for?(int?i?=?0;?i?<?num;?++i)?{
for?(int?j?=?0;?j?<?dim;?++j)?{
bottom_diff[i?*?dim?+?j]?=?std::max(?Dtype(0),?1?+bottom_diff[i?*?dim?+?j]);
}
}
Dtype*?loss?=?top[0]->mutable_cpu_data();
switch?(this->layer_param_.hinge_loss_param().norm())?{
case?HingeLossParameter_Norm_L1:
loss[0]?=?caffe_cpu_asum(count,?bottom_diff)?/?num;break;
case?HingeLossParameter_Norm_L2:
loss[0]?=?caffe_cpu_dot(count,?bottom_diff,bottom_diff)?/?num;?break;
default:?LOG(FATAL)?<<?"Unknown?Norm";
}
只需要根據(jù)上面的轉(zhuǎn)化后的式子,在正確label處乘以-1,然后累加即可。
再看反向梯度求導(dǎo):
當(dāng)進(jìn)行一次forward之后,
bottom_diff=[max(0,1+t0),max(0,1+t1),...,max(0,1?tk),...,max(0,1?tK-1)]
我們現(xiàn)在要求梯度,期望是1+tk>0時(shí)為1,1-tk>0時(shí)為-1,其他情況為0,
當(dāng)任意一項(xiàng)1+tk或者1-tk<0時(shí),會(huì)有梯度=0。實(shí)際上就是求上面向量各自元素的符號(hào),當(dāng)1+tk>0,sign(1+tk),只是max(0,1?tk)這個(gè)應(yīng)該反過(guò)來(lái),當(dāng)1-tk>0時(shí),sign(tk-1)=-1。
代碼如下:
Dtype*?bottom_diff?=?bottom[0]->mutable_cpu_diff();
const?Dtype*?label?=?bottom[1]->cpu_data();
int?num?=?bottom[0]->num();
int?count?=?bottom[0]->count();
int?dim?=?count?/?num;
for?(int?i?=?0;?i?<?num;?++i)?{
bottom_diff[i?*?dim?+?static_cast<int>(label[i])]?*=?-1;
}
const?Dtype?loss_weight?=?top[0]->cpu_diff()[0];
switch?(this->layer_param_.hinge_loss_param().norm())?{
case?HingeLossParameter_Norm_L1:
caffe_cpu_sign(count,?bottom_diff,?bottom_diff);
caffe_scal(count,?loss_weight?/?num,?bottom_diff);?
break;
case?HingeLossParameter_Norm_L2:
caffe_scal(count,?loss_weight?*?2?/?num,?bottom_diff);
break;
default:?LOG(FATAL)?<<?"Unknown?Norm";
}
}
?
07 infogain_loss_layer.cpp
數(shù)學(xué)定義:
輸入bottom_data是N*C*H*W維向量,bottom_label是N*1*1*1維向量,存儲(chǔ)的就是類別數(shù)。它還有個(gè)可選的bottom[2],是一個(gè)infogain?matrix矩陣,它的維度等于num_of_label?*?num_of_label。每個(gè)通道c預(yù)測(cè)的是第c類的概率,取值0~1,所有c個(gè)通道的概率相加=1。是不是像softMax?
實(shí)際上它內(nèi)部就定義了shared_ptr<Layer<Dtype>?>softmax_layer_,用于映射輸入。
Loss定義如下:
其中Hln代表H的第ln行,K是所有類別數(shù),如果H是一個(gè)單位矩陣,那么只有對(duì)角線有值,回到文章開(kāi)頭,這就是multinomial_logistic_loss_layer。當(dāng)H是一個(gè)普通矩陣時(shí),當(dāng)groundtruth?label為k,?
?時(shí),值也可以非零。這樣各個(gè)類別之間就不存在競(jìng)爭(zhēng)關(guān)系了,后來(lái)的mask-rcnn中實(shí)際上loss也就是去除了這重競(jìng)爭(zhēng)關(guān)系。
Forward:
void?InfogainLossLayer<Dtype>::Forward_cpu(constvector<Blob<Dtype>*>&?bottom,
const?vector<Blob<Dtype>*>&?top)?{
softmax_layer_->Forward(softmax_bottom_vec_,softmax_top_vec_);
const?Dtype*?prob_data?=?prob_.cpu_data();
const?Dtype*?bottom_label?=?bottom[1]->cpu_data();
const?Dtype*?infogain_mat?=?NULL;
if?(bottom.size()?<?3)?{?infogain_mat?=infogain_.cpu_data();
}?else?{?infogain_mat?=?bottom[2]->cpu_data();}
int?count?=?0;
Dtype?loss?=?0;
for?(int?i?=?0;?i?<?outer_num_;?++i)?{
for?(int?j?=?0;?j?<?inner_num_;?j++)?{
const?int?label_value?=?static_cast<int>(bottom_label[i?*?inner_num_?+?j]);
if?(has_ignore_label_?&&?label_value?==ignore_label_)?{continue;}
DCHECK_GE(label_value,?0);
DCHECK_LT(label_value,?num_labels_);
for?(int?l?=?0;?l?<?num_labels_;?l++)
{??loss?-=?infogain_mat[label_value?*?num_labels_?+?l]*?log(std::max(?prob_data[i?*inner_num_*num_labels_?+?l?*?inner_num_?+?j],
Dtype(kLOG_THRESHOLD)));}
++count;?}?}
top[0]->mutable_cpu_data()[0]?=?loss?/get_normalizer(normalization_,?count);
if?(top.size()?==?2)?{?top[1]->ShareData(prob_);?}}
上面與multinomial_logistic_loss_layer的區(qū)別就在于每一項(xiàng)乘了infogain_mat[label_value?*??num_labels_?+?l]。
Backward:
for?(int?l?=?0;?l?<?num_labels_;?++l)?{
???bottom_diff[i?*?dim?+?l?*?inner_num_?+?j]?=prob_data[i*dim?+?l*inner_num_?+j]*sum_rows_H[label_value]?-infogain_mat[label_value?*?num_labels_?+?l];
??}
這個(gè),看了4篇了大家不妨自己推一推?不行咱再一起來(lái)
同時(shí),在我的知乎專欄也會(huì)開(kāi)始同步更新這個(gè)模塊,歡迎來(lái)交流
https://zhuanlan.zhihu.com/c_151876233
注:部分圖片來(lái)自網(wǎng)絡(luò)
—END—
打一個(gè)小廣告,我在gitchat開(kāi)設(shè)了一些課程和chat,歡迎交流。
感謝各位看官的耐心閱讀,不足之處希望多多指教。后續(xù)內(nèi)容將會(huì)不定期奉上,歡迎大家關(guān)注有三公眾號(hào) 有三AI!
?
總結(jié)
以上是生活随笔為你收集整理的【caffe解读】 caffe从数学公式到代码实现4-认识caffe自带的7大loss的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 【caffe解读】 caffe从数学公式
- 下一篇: 【caffe解读】 caffe从数学公式