【问题标题】:Can symmetrically paddding be done in convolution layers in Keras?可以在 Keras 的卷积层中进行对称填充吗?
【发布时间】:2018-03-09 08:28:37
【问题描述】:

我读到padding 在 Keras 的卷积层中是 sameavlid,我认为填充了零。

有没有办法在 Keras 中进行对称填充?

看来这可以通过TensorFlow的tf.pad来完成。 tf.pad(t, paddings, "SYMMETRIC") 正是我想要做的。 Keras 可以用 TensorFlow 作为后端吗?

【问题讨论】:

  • 你所说的对称填充是什么意思?
  • 请参考tf.padtf.pad(t, paddings, "SYMMETRIC") 正是我想要的 symmetrically padding
  • @MarcinMożejko 请参考我之前的评论

标签: python tensorflow keras


【解决方案1】:

我在 keras 中编写了一个示例层,它调用了 tensorflow 填充后端。

import keras.backend as K
from keras.layers import Layer

class SymmetricPadding2D(Layer):

    def __init__(self, output_dim, padding=[1,1], 
                 data_format="channels_last", **kwargs):
        self.output_dim = output_dim
        self.data_format = data_format
        self.padding = padding
        super(SymmetricPadding2D, self).__init__(**kwargs)

    def build(self, input_shape):
        super(SymmetricPadding2D, self).build(input_shape)

    def call(self, inputs):
        if self.data_format is "channels_last":
            #(batch, depth, rows, cols, channels)
            pad = [[0,0]] + [[i,i] for i in self.padding] + [[0,0]]
        elif self.data_format is "channels_first":
            #(batch, channels, depth, rows, cols)
            pad = [[0, 0], [0, 0]] + [[i,i] for i in self.padding]

        if K.backend() == "tensorflow":
            import tensorflow as tf
            paddings = tf.constant(pad)
            out = tf.pad(inputs, paddings, "REFLECT")
        else:
            raise Exception("Backend " + K.backend() + "not implemented")
        return out 

    def compute_output_shape(self, input_shape):
        return (input_shape[0], self.output_dim)

if __name__ == "__main__":

    from keras.models import Sequential
    import numpy as np

    #Set Image
    image = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]

    # Pad to "channels_last format 
    # which is [batch, width, height, channels]=[1,4,4,1]
    image = np.expand_dims(np.expand_dims(np.array(image),2),0)


    #Build Keras model
    model = Sequential()
    model.add(SymmetricPadding2D(1, input_shape=(4,4,1)))
    model.build()

    # To simply apply existing filter, we use predict with no training
    out = model.predict(image)
    print(out[0,:,:,0])

【讨论】:

    【解决方案2】:

    应用对称填充的一种方法是创建您自己的图层。 Keras documentation 展示了如何创建一个示例。

    然后,您可以拨打tf.pad(t, paddings, "SYMMETRIC")

    【讨论】:

      【解决方案3】:

      如果你想在 keras 中填充 1 个像素:

      padded_out = Lambda( lambda xi: tf.pad(xi, [[0,0],[1, 1], [1, 1],[0,0]], "SYMMETRIC"))(input_tensor)
      

      批处理似乎需要第一个 [0,0],通道需要最后一个 [0,0]。

      【讨论】:

      • 简洁的解决方案,但我认为@Ed Smiths 的答案在使用 REFLECT 而不是 SYMMETRIC 时是正确的
      猜你喜欢
      • 2017-10-15
      • 2019-05-17
      • 2018-08-04
      • 1970-01-01
      • 1970-01-01
      • 2017-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多