本文介绍了可以在Keras的卷积层中进行对称填充吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我读到在Keras的卷积层中padding
是same
或avlid
,我认为填充了零.
I read that the padding
is same
or avlid
in convolution layers in Keras, and I think zeros are padded.
有什么方法可以在Keras中进行对称填充吗?
Is there any way to do a symmetrically padding in Keras?
这似乎可以通过TensorFlow的 tf.pad 完成. tf.pad(t, paddings, "SYMMETRIC")
就是我想要做的. Keras可以使用TensorFlow作为后端吗?
It seems that this can be done with TensorFlow's tf.pad. tf.pad(t, paddings, "SYMMETRIC")
is just what I want do. Can Keras does that with TensorFlow as the backend?
推荐答案
我已经在keras中编写了一个示例层,将其称为tensorflow padding后端.
I've written an example layer in keras which calls the tensorflow padding backend.
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])
这篇关于可以在Keras的卷积层中进行对称填充吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!