Conv2d¶
- class Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, conv_mode='cross_correlation', compute_mode='default', padding_mode='zeros', **kwargs)[源代码]¶
对输入张量进行二维卷积
例如, 给定一个大小为 \((N, C_{\text{in}}, H, W)\) 的输入, 该层通过下述过程产生一个大小为 \((N, C_{\text{out}}, H_{\text{out}}, W_{\text{out}})\) 的输出。
\[\text{out}(N_i, C_{\text{out}_j}) = \text{bias}(C_{\text{out}_j}) + \sum_{k = 0}^{C_{\text{in}} - 1} \text{weight}(C_{\text{out}_j}, k) \star \text{input}(N_i, k)\]其中 \(\star\) 是有效的2D互相关运算; \(N\) 是批大小; \(C\) 表示通道数; \(H\) 是以像素为单位输入平面的高度; \(W\) 是以像素为单位的平面宽度。
通常,输出的特征图的形状可以被下面的方式推导出来:
input: \((N, C_{\text{in}}, H_{\text{in}}, W_{\text{in}})\)
output: \((N, C_{\text{out}}, H_{\text{out}}, W_{\text{out}})\) 在此式中
\[\text{H}_{out} = \lfloor \frac{\text{H}_{in} + 2 * \text{padding[0]} - \text{dilation[0]} * (\text{kernel_size[0]} - 1) - 1}{\text{stride[0]}} + 1 \rfloor\]\[\text{W}_{out} = \lfloor \frac{\text{W}_{in} + 2 * \text{padding[1]} - \text{dilation[1]} * (\text{kernel_size[1]} - 1) - 1}{\text{stride[1]}} + 1 \rfloor\]当 groups == in_channels 且 out_channels == K * in_channels ,其中 K 是正整数,该操作也被称为深度方向卷积(depthwise convolution)。
换言之, 对于大小为 \((N, C_{in}, H_{in}, W_{in})\) 的 depthwise 卷积, 可以通过参数构造:math:(in_channels=C_{in}, out_channels=C_{in} times K, …, groups=C_{in}).
- 参数
in_channels (
int
) – 输入数据中的通道数。out_channels (
int
) – 输出数据中的通道数。kernel_size (
Union
[int
,Tuple
[int
,int
]]) – 空间维度上的权重大小。如果kernel_size 是一个int
, 实际的kernel大小为(kernel_size, kernel_size)
.padding (
Union
[int
,Tuple
[int
,int
]]) – 在空间维度两侧进行填充的宽度。默认值:0dilation (
Union
[int
,Tuple
[int
,int
]]) – 二维卷积运算的空洞(dilation)。默认:1groups (
int
) – 在进行“分组卷积”时,对输入输出通道的分组数量。当groups
不是 1 时,in_channels
和out_channels
必须可被groups
整除,卷积核权重的形状将会是(groups, out_channel // groups, in_channels // groups, kernel_size)
。默认值:1bias (
bool
) – 是否将偏置(bias)加入卷积的结果中。默认:Trueconv_mode (
str
) – 支持 cross_correlation. 默认: cross_correlationcompute_mode (
str
) – 当设置 “default” 时, 不会对中间结果的精度有特殊要求。当设置 “float32” 时, “float32” 将被用作中间结果的累加器, 但是只有当输入和输出的dtype是float16时有效。padding_mode (
str
) – “zeros”, “reflect” 或者 “replicate”。默认值:”zeros”。更多信息参考Pad
。
注解
weight
的shape通常为(out_channels, in_channels, height, width)
,如果 groups 不为 1, shape 应该是
(groups, out_channels // groups, in_channels // groups, height, width)
bias
的shape通常为(1, out_channels, *1)
实际案例
>>> import numpy as np >>> m = M.Conv2d(in_channels=3, out_channels=1, kernel_size=3) >>> inp = mge.tensor(np.arange(0, 96).astype("float32").reshape(2, 3, 4, 4)) >>> oup = m(inp) >>> oup.numpy().shape (2, 1, 2, 2)