Keras 上采样 2d 与 PyTorch 上采样

Keras Upsampling2d vs PyTorch Upsampling

我正在尝试将 Keras 模型转换为 PyTorch。现在,它涉及 keras 中的 UpSampling2D。当我在 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])

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

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

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

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

size: Int, or tuple of 2 integers. The upsampling factors for rows and columns.

而且,PyTorch 提供了直接 输出大小 比例因子 SOURCE.

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

To specify the scale, it takes either the size or the scale_factor as its constructor argument.


所以,在你的情况下

# 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])