如何创建动态 python 层来计算 caffe 中的 class 权重?

How to create on-the-fly python layer for calculating class weights in caffe?

我想添加一个 python 层,用于即时计算 INfoGainLoss Layer 的概率矩阵 H。我已经编写了通过计算一张图像的每个 class 的概率并将其保存到 .binaryproto 文件中来创建此矩阵的程序。如果你给我一些提示,我真的很感激我如何编写一个 python 层来创建这个矩阵并将它作为第三个参数发送到 InfoGainLoss 层?我在这里画了一个原理图,对吗?如果是,如何为此编写 python 层?我已经在线阅读了一些代码,但仍然对 setupreshapeforward 函数感到困惑。

7a.png

您的 Python 层与输入层非常相似:它没有反向传播,因此很容易实现。有关详细信息,请参阅

你的图层需要 "label" 底部,并生成 "H" 矩阵作为顶部:

图层{ 姓名:"classWeightH" 底部:"label" 顶部:"H" 类型:"Python" python_param{ 模块:# python 代码所在的文件名 图层:"classWeightHLayer" } }

python 代码应如下所示:

import sys, os, numpy as np
sys.path.insert(0, os.environ['CAFFE_ROOT']+'/python')
import caffe
class classWeightHLayer(caffe.Layer):
  def setup(self,bottom,top):
    assert len(bottom)==1, "expecting exactly one input"
    assert len(top)==1, "producing exactly one output"
    # you might want to get L - the number of labels as a parameter...

  def reshape(self,bottom,top):
    top[0].reshape(1,1,L,L) # reshape the output to the size of H

  def forward(self,bottom,top):         
    labels = bottom[0].data
    H = np.zeros((1,1,L,L), dtype='f4') 
    # do your magic here...
    top[0].data[...] = H    

  def backward(self, top, propagate_down, bottom):
    # no back-prop for input layers
    pass