Keras Upsampling2d 与 PyTorch 上采样

社会演员多 pytorch 343

原文标题Keras Upsampling2d vs PyTorch Upsampling

我正在尝试将 Keras 模型转换为 PyTorch。现在,它涉及UpSampling2Dfromkeras。当我在pytorch中使用torch.nn.UpsamplingNearest2d时,由于keras中UpSampling2D的默认值为nearest,我得到了不同的不一致结果。示例如下:

Keras 行为

In [3]: t1 = tf.random_normal([32, 8, 8, 512]) # as we have channels last in keras                                  

In [4]: u_s = tf.keras.layers.UpSampling2D(2)(t1)                               

In [5]: u_s.shape                                                               
Out[5]: TensorShape([Dimension(32), Dimension(16), Dimension(16), Dimension(512)])

所以输出形状是(32,16,16,512)。现在让我们用 PyTorch 做同样的事情。

PyTorch 行为

In [2]: t1 = torch.randn([32,512,8,8]) # as channels first in pytorch

In [3]: u_s = torch.nn.UpsamplingNearest2d(2)(t1)

In [4]: u_s.shape
Out[4]: torch.Size([32, 512, 2, 2])

这里的输出形状是(32,512,2,2),与 keras 的(32,512,16,16)相比。

那么如何在 PyTorch 中获得 Keras 的等效结果。谢谢

原文链接:https://stackoverflow.com//questions/71585394/keras-upsampling2d-vs-pytorch-upsampling

回复

我来回复
  • M.Innat的头像
    M.Innat 评论

    在 keras 中,它使用缩放因子来上采样.SOURCE。

    tf.keras.layers.UpSampling2D(size, interpolation='nearest')
    

    size:Int,或 2 个整数的元组。行和列的上采样因子。

    而且,PyTorch 提供了直接输出大小和缩放因子。SOURCE。

    torch.nn.UpsamplingNearest2d(size=None, scale_factor=None)
    

    要指定比例,它将大小或 scale_factor 作为其构造函数参数。


    所以,在你的情况下

    # scaling factor in keras 
    t1 = tf.random.normal([32, 8, 8, 512])
    tf.keras.layers.UpSampling2D(2)(t1).shape
    TensorShape([32, 16, 16, 512])
    
    # direct output size in pytorch 
    t1 = torch.randn([32,512,8,8]) # as channels first in pytorch
    torch.nn.UpsamplingNearest2d(size=(16, 16))(t1).shape
    # or torch.nn.UpsamplingNearest2d(size=16)(t1).shape
    torch.Size([32, 512, 16, 16])
    
    # scaling factor in pytorch.
    torch.nn.UpsamplingNearest2d(scale_factor=2)(t1).shape
    torch.Size([32, 512, 16, 16])
    
    2年前 0条评论