问题描述
我正在尝试将以下Keras模型代码转换为pytorch,但是在处理padding ='same'时遇到问题.
I'm trying to convert the following Keras model code to pytorch, but am having problems dealing with padding='same'.
model = Sequential()
model.add(Conv2D(64, (3, 3), input_shape=img_size))
model.add(BatchNormalization(axis=1))
model.add(Activation('relu'))
model.add(Dropout(0.3))
model.add(Conv2D(64, (3, 3), padding='same'))
model.add(BatchNormalization(axis=1))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
产生以下摘要:
Layer (type) Output Shape Param #
=================================================================
conv2d_1 (Conv2D) (None, 30, 30, 64) 1792
_________________________________________________________________
batch_normalization_1 (Batch (None, 30, 30, 64) 120
_________________________________________________________________
activation_1 (Activation) (None, 30, 30, 64) 0
_________________________________________________________________
dropout_1 (Dropout) (None, 30, 30, 64) 0
_________________________________________________________________
conv2d_2 (Conv2D) (None, 30, 30, 64) 36928
_________________________________________________________________
batch_normalization_2 (Batch (None, 30, 30, 64) 120
_________________________________________________________________
activation_2 (Activation) (None, 30, 30, 64) 0
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 15, 15, 64) 0
=================================================================
Total params: 38,960
Trainable params: 38,840
Non-trainable params: 120
现在,我会写:
self.features = nn.Sequential(
nn.Conv2d(3, 64, kernel_size=3,
bias=False),
nn.BatchNorm2d(64),
nn.ReLU(inplace=True),
nn.Dropout(0.3),
nn.Conv2d(64, 64, kernel_size=3, padding = ?
bias=False),
nn.BatchNorm2d(64),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2, padding = ?),
)
其中填充应具有数值的地方.我想知道是否有更简单的方法来计算此值,因为我们使用的是padding ='same'.
Where padding should have numerical value. I was wondering if there is an easier way to calculate this since we're using padding='same'.
此外,Keras模型的下一行如下所示:
Also, the next line of the Keras model looks like:
model.add(Conv2D(128, (3, 3), padding='same'))
所以我真的需要重新学习如何计算填充,特别是在大步之后. 从粗略的角度看,填充2是吗?
So I really need to brush up on how to calculate padding, especially after stride too. From a rough eye only, is the padding 2?
推荐答案
W:输入卷大小
F:内核大小
S:stride
P:填充量
输出量的大小=(W-F + 2P)/S + 1
size of output volume = (W-F+2P)/S+1
例如
输入:7x7,内核:3x3,步幅:1,pad:0:
input:7x7, kernel:3x3, stride:1, pad:0
输出大小=(7-3 + 2 * 0)/1 + 1 = 5 => 5x5
output size = (7-3+2*0)/1+1 = 5 =>5x5
这篇关于padding ='same'转换为PyTorch padding =#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!