Caffe中的空间反射填充

3
有没有想法如何在Caffe中实现类似Torch中的空间反射填充?
  (x): nn.SpatialReflectionPadding(l=1, r=1, t=1, b=1)
  (x): nn.SpatialConvolution(64 -> 64, 3x3)
  (x): nn.ReLU
1个回答

2
一种实现这个的方法是使用Caffe的Python Layer。然后您可以自己设置函数并根据需要进行定制。但是,这个层只能在CPU上运行,因此如果您在网络中间使用它,可能会减慢模型速度。
下面,我定义了一个使用Python层来进行零填充输入的层,您可以根据自己的需求进行修改:
import caffe
import numpy as np

class SpatialReflectionPadding(caffe.Layer):

def setup(self,bottom,top):
    if len(bottom) != 1: # check that a single bottom blob is given
        raise Exception("Expected a single blob")       
    if len(bottom[0].shape) != 4: # check that it is 4D
        raise Exception("Expected 4D blob")
    params = eval(self.param_str) # get the params given in the prototxt
    self.l = params["l"]
    self.r = params["r"]
    self.t = params["t"]
    self.b = params["b"]

def reshape(self,bottom,top):
    top[0].reshape(bottom[0].shape[0],bottom[0].shape[1],bottom[0].shape[2]+self.t+self.b,bottom[0].shape[3]+self.r+self.l) # set the shape of the top blob based on the shape of the existing bottom blob

def forward(self,bottom,top):
    for i in range(0,top[0].shape[2]):
        for j in range(0,top[0].shape[3]):
            if (i < self.t or i >= self.t+bottom[0].shape[2]) or (j < self.l or j >= self.l+bottom[0].shape[3]):
                top[0].data[:,:,i,j] = 0 # for the padded part, set the value to 0
            else:
                top[0].data[:,:,i,j] = bottom[0].data[:,:,i-self.t,j-self.l] # for the rest, copy the value from the bottom blob

def backward(self,top,propagate_down,bottom):
    bottom[0].diff[...] = np.full(bottom[0].shape,1) * top[0].diff[:,:,self.t:self.t+bottom[0].shape[2],self.l:self.l+bottom[0].shape[3]] # set the gradient for backward pass

然后,在您的prototxt文件中,您可以这样使用它:
layer {
    name: "srp" # some name
    type: "Python"
    bottom: "some_layer" # the layer which provides the input blob
    top: "srp"
    python_param {
        module: "caffe_srp" # whatever is your module name
        layer: "SpatialReflectionPadding"
        param_str: '{ "l": 1, "b": 1, "t": 1, "r": 1}'
    }
}

我并不100%确定它是否正确运行,但在我使用时,它似乎是这样的。无论如何,它应该提供了一个思路和开始的点,告诉你如何继续。此外,你可以参考这个问题及其答案

1
在GPU层中间使用CPU层会严重影响Caffe的性能。我曾经遇到过这种情况。如果你一定要使用这种填充方式,那就花时间去实现它吧。 - Shai

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接