Caffe:如何获得Python层的阶段?

Sha*_*hai 10 python neural-network deep-learning caffe pycaffe

我在caffe中创建了一个"Python"图层"myLayer",并在网中使用它train_val.prototxt我像这样插入图层:

layer {
  name: "my_py_layer"
  type: "Python"
  bottom: "in"
  top: "out"
  python_param {
    module: "my_module_name"
    layer: "myLayer"
  }
  include { phase: TRAIN } # THIS IS THE TRICKY PART!
}
Run Code Online (Sandbox Code Playgroud)

现在,我的图层只参与网络的TRAINing阶段,
我怎么知道在我的图层的setup功能?

class myLayer(caffe.Layer):
  def setup(self, bottom, top):
     # I want to know here what is the phase?!!
  ...
Run Code Online (Sandbox Code Playgroud)

PS,
我在"Caffe Users"谷歌小组上发布了这个问题.如果有什么东西在那里,我会更新.

Sha*_*hai 7

正如galloguille所指出的,caffe现在暴露phase给python层类.这个新功能使这个答案有点多余.了解param_str用于将其他参数传递给图层的caffe python图层仍然很有用.

原始答案:

AFAIK没有琐碎的方式来获得阶段.但是,可以将任意参数从net prototxt传递给python.这可以使用的param_str参数来完成python_param.
以下是它的完成方式:

layer {
  type: "Python"
  ...
  python_param {
    ...
    param_str: '{"phase":"TRAIN","numeric_arg":5}' # passing params as a STRING
Run Code Online (Sandbox Code Playgroud)

在python中,你进入param_str了图层的setup功能:

import caffe, json
class myLayer(caffe.Layer):
  def setup(self, bottom, top):
    param = json.loads( self.param_str ) # use JSON to convert string to dict
    self.phase = param['phase']
    self.other_param = int( param['numeric_arg'] ) # I might want to use this as well...
Run Code Online (Sandbox Code Playgroud)


Gui*_*ull 6

这是一个非常好的解决方法,但如果您只想将phase参数作为参数传递,那么现在您可以将该阶段作为图层的属性进行访问.此功能仅在6天前合并https://github.com/BVLC/caffe/pull/3995.

具体提交:https://github.com/BVLC/caffe/commit/de8ac32a02f3e324b0495f1729bff2446d402c2c

使用此新功能,您只需使用该属性即可self.phase.例如,您可以执行以下操作:

class PhaseLayer(caffe.Layer):
"""A layer for checking attribute `phase`"""

def setup(self, bottom, top):
    pass

def reshape(self, bootom, top):
    top[0].reshape()

def forward(self, bottom, top):
    top[0].data[()] = self.phase
Run Code Online (Sandbox Code Playgroud)