我正在使用keras构建用于图像分割的卷积神经网络,我想使用“反射填充”而不是“相同”的填充,但是我找不到在keras中做到这一点的方法。
inputs = Input((num_channels, img_rows, img_cols)) conv1=Conv2D(32,3,padding='same',kernel_initializer='he_uniform',data_format='channels_first')(inputs)
有没有办法实现反射层并将其插入keras模型中?
找到了解决方案!我们只需要创建一个将图层作为输入的新类,并使用tensorflow预定义函数即可。
import tensorflow as tf from keras.engine.topology import Layer from keras.engine import InputSpec class ReflectionPadding2D(Layer): def __init__(self, padding=(1, 1), **kwargs): self.padding = tuple(padding) self.input_spec = [InputSpec(ndim=4)] super(ReflectionPadding2D, self).__init__(**kwargs) def get_output_shape_for(self, s): """ If you are using "channels_last" configuration""" return (s[0], s[1] + 2 * self.padding[0], s[2] + 2 * self.padding[1], s[3]) def call(self, x, mask=None): w_pad,h_pad = self.padding return tf.pad(x, [[0,0], [h_pad,h_pad], [w_pad,w_pad], [0,0] ], 'REFLECT') # a little Demo inputs = Input((img_rows, img_cols, num_channels)) padded_inputs= ReflectionPadding2D(padding=(1,1))(inputs) conv1 = Conv2D(32, 3, padding='valid', kernel_initializer='he_uniform', data_format='channels_last')(padded_inputs)