繁体   English   中英

Caffe python层backword传递实现

[英]Caffe python layer backword pass implementation

我正在编写一个caffe python层,该层转售沿着特定轴[附加代码]的[0 255]与正向传递之间的输入正常。 该层是否需要向后传递? 如果是这样,我该如何实施?

caffe_root = 'caffe_root'           
import sys
sys.path.insert(0, caffe_root + 'python')
import caffe
import numpy as np

class scale_layer(caffe.Layer):

  def setup(self, bottom, top):
    assert len(bottom)==1 and len(top)==1, "scale_layer expects a single input and a single output"

  def reshape(self, bottom, top):
    top[0].reshape(*bottom[0].data.shape)

  def forward(self, bottom, top):
    in_ = np.array(bottom[0].data)
    x_min = in_.min(axis=(0, 1), keepdims=True) 
    x_max = in_.max(axis=(0, 1), keepdims=True)
    top[0].data[...] = np.around(255*((in_-x_min)/(x_max-x_min)))

  def backward(self, top, propagate_down, bottom):
    # backward pass is not implemented!
    ???????????????????????????
    pass

如果您愿意忽略np.around ,则您的函数非常简单:

在此处输入图片说明

对于x=x_min和对于x=x_max ,导数为零,对于所有其他x ,导数为255/(x_max-x_min)

这可以通过以下方式实现

def forward(self, bottom, top):
  in_ = bottom[0].data
  self.x_min = in_.min(axis=(0, 1), keepdims=True)  # cache min/max for backward
  self.x_max = in_.max(axis=(0, 1), keepdims=True)
  top[0].data[...] = 255*((in_-self.x_min)/(self.x_max-self.x_min)))

def backward(self, top, propagate_down, bottom):
  in_ = bottom[0].data
  b, c = in_.shape[:2]
  diff = np.tile( 255/(self.x_max-self.x_min), (b, c, 1, 1) )
  diff[ in_ == self.x_min ] = 0
  diff[ in_ == self.x_max ] = 0
  bottom[0].diff[...] = diff * top[0].diff

不要忘记进行数字测试。 例如,可以使用test_gradient_for_python_layer来完成。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM