Skip to content

Commit 99b18c0

Browse files
github-actions[bot]FAQ Bot
andauthored
NEW: How many feature maps are produced by a PyTorch Conv2D layer, and how do (#46)
Co-authored-by: FAQ Bot <faq-bot@datatalks.club>
1 parent d87886c commit 99b18c0

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
---
2+
id: ad7e934f1c
3+
question: How many feature maps are produced by a PyTorch Conv2D layer, and how do
4+
you compute the spatial output size?
5+
sort_order: 34
6+
---
7+
8+
In PyTorch, a `Conv2d` layer outputs a 4D tensor of shape `(N, C_out, H_out, W_out)` where:
9+
10+
- `N` is the batch size
11+
- `C_out` is the number of output channels (out_channels)
12+
- `H_out` and `W_out` are the spatial dimensions after the convolution
13+
14+
The spatial size is computed (for dilation = 1) as:
15+
16+
```
17+
H_out = floor((H_in - K_H + 2*P_H) / S_H) + 1
18+
W_out = floor((W_in - K_W + 2*P_W) / S_W) + 1
19+
```
20+
21+
For the general case (including dilation `D`):
22+
23+
```
24+
H_out = floor((H_in + 2*P_H - D*(K_H - 1) - 1) / S_H + 1)
25+
W_out = floor((W_in + 2*P_W - D*(K_W - 1) - 1) / S_W + 1)
26+
```
27+
28+
If you have dilation = 1 (the common case), this reduces to the simplified formula above.
29+
30+
Example for your parameters (assuming input has 3 channels and batch size 1):
31+
32+
```
33+
import torch
34+
import torch.nn as nn
35+
36+
conv = nn.Conv2d(in_channels=3, out_channels=16, kernel_size=(2,2), stride=(2,2), padding=(2,2))
37+
x = torch.randn(1, 3, 150, 150)
38+
y = conv(x)
39+
print(y.shape) # torch.Size([1, 16, 77, 77])
40+
```
41+
42+
Notes:
43+
- The number of feature maps equals `out_channels`.
44+
- If you only care about spatial size, apply the height/width formula above; you can also verify with a quick forward pass or by using a library like `torchsummary` to inspect the model.

0 commit comments

Comments
 (0)