neural-network - Caffe 中的空间反射填充

标签 neural-network deep-learning caffe conv-neural-network torch

关于如何像在 Torch 中一样在 Caffe 中实现空间反射填充有什么想法吗?

  (x): nn.SpatialReflectionPadding(l=1, r=1, t=1, b=1)
  (x): nn.SpatialConvolution(64 -> 64, 3x3)
  (x): nn.ReLU

最佳答案

一种方法是使用 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% 确定它是否正常工作,但当我使用它时,它似乎确实如此。无论如何,它应该给出一个想法和一个关于如何进行的起点。另外,您可以引用this question and its answers .

关于neural-network - Caffe 中的空间反射填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44830512/

相关文章:

python - 无法在纯 CPU Caffe 中使用 GPU : check mode

python - 这两种保存keras机器学习模型权重的方式有什么区别?

machine-learning - 如何处理这个机器学习/NLP 上下文感知文本分类项目?请参阅下面的描述

tensorflow - Tensorflow中的Adam Optimizer会使损失突然增加

keras - LSTM 预测模型 : the loss value doesn't change

machine-learning - 如何在 Caffe 中使用与图像不同的数据?

machine-learning - 咖啡 |添加新层以使用训练模型后未知的底部 Blob (微调)

r - 如何使用 CARET 包评估多个模型?

python - 类型错误 : 'numpy.float64' object is not iterable Keras

keras - InceptionResnetV2 STEM block keras implementation 与原始论文中的不匹配?