[英]Conv2D padding in TensorFlow and PyTorch
I am trying to convert TensorFlow
model to PyTorch
but having trouble with padding
.我正在尝试将
TensorFlow
模型转换为PyTorch
但在padding
遇到问题。 My code for for relevant platforms are as follow:我的相关平台代码如下:
TensorFlow TensorFlow
conv1 = tf.layers.conv2d(
inputs=input_layer,
filters=32,
kernel_size=[5, 5],
padding="same",
activation=tf.nn.relu,
name = "conv1")
PyTorch火炬
conv1 = nn.Conv2d(1, 32, kernel_size=5, stride=1, padding=2)
I have few questions:我有几个问题:
padding
s are added on left/right/top/bottom if we use same
padding in tensorflow
?tensorflow
使用same
padding ,在 left/right/top/bottom 上添加了多少padding
?padding
s are added on left/right/top/bottom if we use padding=2
in pytorch
?pytorch
使用padding=2
,在 left/right/top/bottom 上添加了多少padding
?conv
layer?conv
层? Thanks in advance.提前致谢。
To answer your questions:回答您的问题:
The reason why Pytorch doesn't have padding = 'same' to quite simply put it is due to its dynamic computation graph in comparison to Tensorflow static graph. Pytorch 没有 padding = 'same' 的原因很简单,是因为它的动态计算图与 Tensorflow 静态图相比。
Both the codes are not equivalent as different padding is used.由于使用了不同的填充,这两个代码并不等效。
'Same' padding tries to pad evenly on the left and right, but if the amount of columns to be added is odd, it will then add an extra column to the right. “相同”填充尝试在左侧和右侧均匀填充,但如果要添加的列数为奇数,则会在右侧添加额外的列。
'Padding = 2' in Pytorch applies 2 implicit paddings on either side. Pytorch 中的 'Padding = 2' 在任一侧应用 2 个隐式填充。
Pytorch 1.9 has added padding = 'same' for un-strided or stride = 1 convolutions. Pytorch 1.9 为 un-strided 或 stride = 1 卷积添加了 padding = 'same'。 Which will work for your use case.
这将适用于您的用例。
But for stride > 2 padding needs to be added manually.但是对于 stride > 2 padding 需要手动添加。
Here is the good implementation to perform 'same' padding:-这是执行“相同”填充的良好实现:-
https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/layers/padding.py#L28 https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/layers/padding.py#L28
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.