向caffe中添加自己定义的层(快速教程)

向caffe中添加自己定义的新层需要:

1. 在caffe-master/src/caffe/proto/caffe.proto文件中添加新层的定义和声明;

2. 书写新层的定义头文件(.hpp),c++文件(.cpp),cuda文件(.cu);

 

一 、 基本caffe知识

    在定义你的新层之前,你必须搞清楚一些关于caffe的文件结构:

1. caffe所有用到的层,solver方法,他们的头文件都在caffe-master/include/caffe中;

2. caffe所有的层,solver方法,lr设置方法等,他们的源文件都存储在caffe-master/src/caffe中;

3. caffe-master/src/caffe/proto/caffe.proto文件定义了所有层的参数,message,这个文件很重要,主要是由于他相当于caffe源码与prototxt文件(网络结构申明文件)的连接接口。

    了解了以上的结构,那我们肯定可以推出:在定义新层的时候,头文件和源文件中定义的新层的名称,新层参数的名称必然与caffe.proto中的对应。

 

二、修改caffe.proto文件

    为了方便起见,假设我添加的新层名为“BatchNormLayer”,则我需要在caffe.proto中修改两处:


1. 在message LayerParameter中声明BN层的message类型(BatchNormParameter),和参数message名称(batch_norm_param)

optional BatchNormParameter batch_norm_param = 139;

其中的139是要根据你自己的文件中的标号来定,只有一个要求:不能使用已使用过的标号。

batch_norm_param就是到时候你在prototxt中定义这个层时参数集合的名称。

2.  新建message BatchNormParameter,其中声明了这个层需要的参数(也就是可以通过网络定义文件prototxt传入的参数)

message BatchNormParameter {
  // If false, normalization is performed over the current mini-batch
  // and global statistics are accumulated (but not yet used) by a moving
  // average.
  // If true, those accumulated mean and variance values are used for the
  // normalization.
  // By default, it is set to false when the network is in the training
  // phase and true when the network is in the testing phase.
  optional bool use_global_stats = 1;
  // What fraction of the moving average remains each iteration?
  // Smaller values make the moving average decay faster, giving more
  // weight to the recent values.
  // Each iteration updates the moving average @f$S_{t-1}@f$ with the
  // current mean @f$ Y_t @f$ by
  // @f$ S_t = (1-\beta)Y_t + \beta \cdot S_{t-1} @f$, where @f$ \beta @f$
  // is the moving_average_fraction parameter.
  optional float moving_average_fraction = 2 [default = .999];
  // Small value to add to the variance estimate so that we don't divide by
  // zero.
  optional float eps = 3 [default = 1e-5];
}

为了方便理解,这里将网络定义文件prototxt中BN层的定义列出来,对比一下你就会发现其中的规律:

layer {
    bottom: "res2a_branch1"
    top: "res2a_branch1"
    name: "bn2a_branch1"
    type: "BatchNorm"
    batch_norm_param {
        use_global_stats: true
    }
}

三、 编写batch_norm_layer.cu,batch_norm_layer.cpp, batch_norm_layer.hpp

具体的程序大家可以在较新版本的caffe中找到,这里不再贴代码,具体需要注意一下几点:

1.  .cpp,.hpp,.cu这三个文件对应的文件名一定要相同;

2. batch_norm_layer.cpp中需要注册层:
 

INSTANTIATE_CLASS(BatchNormLayer);
REGISTER_LAYER_CLASS(BatchNorm);

注意是否需要加“Layer”。

完成以上步骤之后就可以在caffe-master目录下重新编译:

make clean

make -j8

make pycaffe

这样就添加成功了。

 

 




NBJ原创 不得转载!!


 

你可能感兴趣的:(caffe,caffe)