python - 可以在 Keras 的卷积层中进行对称填充吗?

标签 python tensorflow keras

我读到 Keras 的卷积层中的 paddingsameavlid,我认为零被填充了。

有什么方法可以在 Keras 中进行对称填充?

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

最佳答案

我在 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])

关于python - 可以在 Keras 的卷积层中进行对称填充吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49189496/

相关文章:

Python MySQLdb/MySQL INSERT IGNORE 并检查是否被忽略

python - 将字符串拆分为单词和标点符号

python - Tensorflow 模型使用 Flask 抛出的不是该图的元素

tensorflow - ValueError : Error when checking input: expected dense_1_input to have shape (3, )但得到形状为(2,)的数组

python - 如何对连续峰宽进行聚类

python - 在 Ubuntu 14.10 上安装 anki 的问题

python - 拟合 Keras 模型会产生错误 "constant folding failed: Invalid argument: Unsupported type: 21"

python - 使用 Tensorflow 构建适用于可变批量大小的图形

tensorflow - LSTM 'recurrent_dropout' 和 'relu' 产生 NaN

python - 将 Keras 中 VGG19 的部分层与 TimeDistributed 层一起使用