1. 程式人生 > >在caffe中新增自定義的layer

在caffe中新增自定義的layer

在處理某些問題時,可能會需要自己去定義特定的layer來實現某些特殊功能,現將新增新的caffe layer的具體步驟進行整理,便於以後複習。 (一)具體步驟如下: 1. 修改{caffe_dir}/src/caffe/proto/caffe.proto 檔案,在 V1LayerParameter的LayerType enum中新增新的layer的名稱及ID(如:MYLAYER 38),並在V1LayerParameter中新增MyLayer的引數說明;在message LayerParameter中新增MyLayer的引數說明,同時更新 LayerParameter的available ID(如:optional MyLayerParameter my_layer_param = 146);最後新增新Layer的引數說明。 message MyLayerParameter {
  optional uint32 para1 = 1; (1 is the ID of para1 in this layerparameter)
  optional bool para2 = 2 [default = true]; 
  optional FillerParameter para3 = 3; 
  optional float para4 = 4; 
}
2. 修改{caffe_dir}/
src/caffe/util下的upgrade_proto.cpp檔案
    2.1 在const char* UpgradeV1LayerType(const V1LayerParameter_LayerType type)函式中新增如下程式碼,使解析prototxt時可以找到新新增的  layer。        case V1LayerParameter_MYLAYER :  
   return "MyLayer"; 
    2.2 在bool UpgradeV1LayerParameter(const V1LayerParameter& v1_layer_param, LayerParameter* layer_param) 函式的相應位置新增對Mylayer層引數的處理函式,否則無法解析該層相應的引數。
if (v1_layer_param.has_my_layer_param()) {
   layer_param->mutable_my_layer_param()->CopyFrom(
       v1_layer_param.my_layer_param());
  }
3. 在{caffe_dir}/include/caffe/layers/ 資料夾中增加該layer的類的宣告my_layer_layer.h檔案。 4. 在{caffe_dir}/src/caffe/layers/目錄下新建.cpp和.cu檔案,進行類實現。 5. 在{caffe_dir}/src/caffe/test/中增加layer的測試程式碼,對所寫的layer前傳和反傳進行測試,測試還包括速度。 (二)編譯
make all -j8 Note:若報錯,則根據相應的錯誤位置檢查語法錯誤。 make test -j8 make runtest -j8 Note:若報錯,則根據相應的錯誤位置檢查邏輯錯誤。
(補充) 如果不寫test檔案,為了檢驗該 Layer 是否能正常建立和執行  forward, backward,也可以利用新建的layer編寫deploy.prototxt,然後執行 caffe time 命令並指定剛剛實現的deploy.prototxt: {caffe_dir}/build/tools/caffe.bin time -model deploy.prototxt