class MyModel(nn.Module):
def __init__(self, in_channels, base_channels, conv1_kernel, conv1_stride, pool1_stride, norm_cfg, conv_cfg, act_cfg):
super().__init__()
self.in_channels = in_channels
self.base_channels = base_channels
self.conv1_kernel = conv1_kernel
self.conv1_stride = conv1_stride
self.pool1_stride = pool1_stride
self.norm_cfg = norm_cfg
self.conv_cfg = conv_cfg
self.act_cfg = act_cfg
self.conv1 = ConvModule(
self.in_channels,
self.base_channels,
kernel_size=self.conv1_kernel,
stride=(self.conv1_stride[0], self.conv1_stride[1], self.conv1_stride[1]),
padding=tuple([(k - 1) // 2 for k in _triple(self.conv1_kernel)]),
bias=False,
conv_cfg=self.conv_cfg,
norm_cfg=self.norm_cfg,
act_cfg=self.act_cfg)
self.maxpool = nn.MaxPool3d(
kernel_size=(1, 3, 3),
stride=(self.pool1_stride[0], self.pool1_stride[1], self.pool1_stride[1]),
padding=(0, 1, 1))
def __init__(self, in_channels, base_channels, conv1_kernel, conv1_stride, pool1_stride, norm_cfg, conv_cfg, act_cfg):
super().__init__()
self.in_channels = in_channels
self.base_channels = base_channels
self.conv1_kernel = conv1_kernel
self.conv1_stride = conv1_stride
self.pool1_stride = pool1_stride
self.norm_cfg = norm_cfg
self.conv_cfg = conv_cfg
self.act_cfg = act_cfg
self._make_stem_layer()
def _make_stem_layer(self):
self.conv1 = ConvModule(
self.in_channels,
self.base_channels,
kernel_size=self.conv1_kernel,
stride=(self.conv1_stride[0], self.conv1_stride[1], self.conv1_stride[1]),
padding=tuple([(k - 1) // 2 for k in _triple(self.conv1_kernel)]),
bias=False,
conv_cfg=self.conv_cfg,
norm_cfg=self.norm_cfg,
act_cfg=self.act_cfg)
self.maxpool = nn.MaxPool3d(
kernel_size=(1, 3, 3),
stride=(self.pool1_stride[0], self.pool1_stride[1], self.pool1_stride[1]),
padding=(0, 1, 1))
在面向对象编程中,初始化通常包括两个方面:
- 设置实例属性
- 创建实例所需的子模块
在这个例子中:
- 前面提到的属性初始化,如
self.in_channels
、self.base_channels
等,属于第一种初始化。 - 而
self.conv1
和self.maxpool
的创建,属于第二种初始化,即创建实例所需的子模块。
这两种初始化操作都是在 __init__
方法中完成的,目的都是为了让这个模型实例能够正常工作。
在大型复杂的模型中,这种子模块的创建通常会被进一步拆分到单独的方法中,比如上面提到的 _make_stem_layer
方法。
pyskl/pyskl/models/cnns/resnet3d.py at main · kennymckormick/pyskl · GitHub