本文主要是介绍如何在caffe中增加layer以及caffe中triplet loss layer的实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
关于triplet loss的原理,目标函数和梯度推导在上一篇博客中已经讲过了,具体见:triplet loss原理以及梯度推导,这篇博文主要是讲caffe下实现triplet loss,编程菜鸟,如果有写的不优化的地方,欢迎指出。
1.如何在caffe中增加新的layer
2.caffe中实现triplet loss layer
1.caffe.proto中增加triplet loss layer的定义
//LayerParameter next available layer-specific ID: 134 (last added: reshape_param)
然后增加Message:
message TripletLossParameter {// margin for dissimilar pairoptional float margin = 1 [default = 1.0];
}
其中 margin就是定义triplet loss原理以及梯度推导所讲的alpha。
2.在./include/caffe/loss_layers.hpp中增加triplet loss layer的类的声明
/*** @brief Computes the triplet loss*/
template <typename Dtype>
class TripletLossLayer : public LossLayer<Dtype> {public:explicit TripletLossLayer(const LayerParameter& param): LossLayer<Dtype>(param){}virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,const vector<Blob<Dtype>*>& top);virtual inline int ExactNumBottomBlobs() const { return 4; }virtual inline const char* type() const { return "TripletLoss"; }/*** Unlike most loss layers, in the TripletLossLayer we can backpropagate* to the first three inputs.*/virtual inline bool AllowForceBackward(const int bottom_index) const {return bottom_index != 3;}protected:virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,const vector<Blob<Dtype>*>& top);virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,const vector<Blob<Dtype>*>& top);virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);Blob<Dtype> diff_ap_; // cached for backward passBlob<Dtype> diff_an_; // cached for backward passBlob<Dtype> diff_pn_; // cached for backward passBlob<Dtype> diff_sq_ap_; // cached for backward passBlob<Dtype> diff_sq_an_; // tmp storage for gpu forward passBlob<Dtype> dist_sq_ap_; // cached for backward passBlob<Dtype> dist_sq_an_; // cach
这篇关于如何在caffe中增加layer以及caffe中triplet loss layer的实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!