Keras中Conv2D padding='same'的填充值设置及维度计算咨询
padding='same' in Keras Conv2D Hey there! Let's break down exactly how Keras calculates padding when you set padding='same'—it's totally clear once you walk through the rules and your specific example.
First, the core idea of padding='same': Keras automatically calculates how many pixels to add around your input feature map so that the output's spatial dimensions match your input's spatial dimensions when strides=(1,1). If your strides are larger than 1, it adjusts padding to make the output dimensions equal to ceil(input_size / strides) instead.
Step-by-step calculation rules
For each spatial dimension (height and width separately):
- Calculate output size:
output_size = ceil(input_size / strides) - Calculate total padding needed:
total_pad = max((output_size - 1) * strides + kernel_size - input_size, 0) - Split padding evenly (or as evenly as possible):
- Padding on the top/left side:
pad_before = total_pad // 2 - Padding on the bottom/right side:
pad_after = total_pad - pad_before
Note: If total padding is odd, the extra pixel goes to the bottom/right side.
- Padding on the top/left side:
Applying this to your code example
Your input X has shape (3, 2, 2, 2)—let's focus on the spatial dimensions: height=2, width=2. You're using kernel_size=(2,2) and strides=(1,1).
- Output size calculation:
output_height = ceil(2 / 1) = 2, same for width. - Total padding needed:
For height:(2-1)*1 + 2 - 2 = 1 + 2 - 2 = 1
Same for width: total padding = 1. - Split padding:
- Height:
pad_top = 1//2 = 0,pad_bottom = 1-0 =1 - Width:
pad_left=0,pad_right=1
- Height:
So Keras adds 0 pixels to the top/left, 1 pixel to the bottom/right of your input (with 0-value padding, the default for Conv2D). After padding, your input becomes 3x3 in spatial dimensions, and applying the 2x2 kernel with stride 1 gives an output of 2x2—matching your original input's spatial size.
After running your code, the output X shape will be (3, 2, 2, 4)—the 4 comes from your filters=4 parameter, and the spatial dimensions stay 2x2 thanks to padding='same'.
Quick note for larger strides
If you ever use strides=(2,2) with, say, an input height of 5 and kernel size 3:
output_height = ceil(5/2) =3total_pad = (3-1)*2 +3 -5 =4+3-5=2pad_top=1,pad_bottom=1(even padding here)
内容的提问来源于stack exchange,提问作者edn

