【问题标题】:converting pytorch 2d padding to tensorflow keras将 pytorch 2d 填充转换为 tensorflow keras
【发布时间】:2020-05-24 23:35:46
【问题描述】:

这相当于什么:

nn.ReflectionPad2d(1)

在 TensorFlow 2 中?上面一行来自 PyTorch。

在 TensorFlow 2 Keras 中,我目前正在研究使用 tf.pad() 作为其 TF 版本,但 PyTorch 似乎能够使用单个整数 1 处理不同的维度。例如,如果它得到一个输入形状 [batch size, 1, 1, 100], nn.ReflectionPad2D 可以很好地处理这个问题,但是在 TensorFlow 中,如果我尝试使用会出现错误

tf.pad(t, tf.constant([0,0], [1,1], [1,1], [0,0]]), 'REFLECT')

关于如何在 TensorFlow 2 keras 中复制 nn.ReflectinPad2d 有什么建议吗?谢谢!

【问题讨论】:

    标签: python tensorflow keras pytorch


    【解决方案1】:

    当我在 TF2 上训练 CycleGan 时,我为自己创建了这个自定义层:

    class ReflectionPad2D(tf.keras.layers.Layer):
      def __init__(self, paddings=(1,1,1,1)):
        super(ReflectionPad2D, self).__init__()
        self.paddings = paddings
    
      def call(self, input):
        l, r, t, b = self.paddings
    
        return tf.pad(input, paddings=[[0,0], [t,b], [l,r], [0,0]], mode='REFLECT')
    

    您可以通过将其放入模型/序列中来按原样使用它,例如:

    model = Sequential([
        ReflectionPad2D((3, 3, 3, 3)),
        Conv2D(64, kernel_size=7, strides=1, padding='valid', use_bias=False),
        BatchNormalization()
    ])
    
    model.build(input_shape=(8, 128, 128, 3))
    model.summary()
    

    示例输出:

    Model: "sequential_13"
    _________________________________________________________________
    Layer (type)                 Output Shape              Param #   
    =================================================================
    reflection_pad2d_198 (Reflec (8, 134, 134, 3)          0         
    _________________________________________________________________
    conv2d_474 (Conv2D)          (8, 128, 128, 64)         9408      
    _________________________________________________________________
    batch_normalization_41 (Batc (8, 128, 128, 64)         256       
    =================================================================
    Total params: 9,664
    Trainable params: 9,536
    Non-trainable params: 128
    _________________________________________________________________
    

    【讨论】:

      猜你喜欢
      • 2021-03-19
      • 2021-07-10
      • 1970-01-01
      • 2019-05-21
      • 1970-01-01
      • 1970-01-01
      • 2022-10-24
      • 1970-01-01
      • 2021-04-27
      相关资源
      最近更新 更多