我正在嘗試將 Keras 模型轉換為 PyTorch。現在,它涉及UpSampling2Dfrom keras。當我torch.nn.UpsamplingNearest2d在 pytorch 中使用時,由于UpSampling2Dkeras 中的默認值為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)與(32,512,16,16)來自 keras 的比較。
那么如何在 PyTorch 中獲得 Keras 的等效結果。謝謝
uj5u.com熱心網友回復:
在 keras 中,它使用縮放因子進行上采樣。來源。
tf.keras.layers.UpSampling2D(size, interpolation='nearest')
size:Int,或 2 個整數的元組。行和列的上采樣因子。
而且,PyTorch 提供了直接輸出大小和縮放因子。來源。
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])
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/450130.html
