Pytorch-tutorial:class 定义中的奇怪输入参数

Pytorch-tutorial: Strange input argument in class definition

我正在阅读一些 pytorch 教程。下面是残差块的定义。但是在 forward 方法中每个函数句柄只接受一个参数 out 而在 __init__ 函数中这些函数有不同数量的输入参数:

# Residual Block
class ResidualBlock(nn.Module):
    def __init__(self, in_channels, out_channels, stride=1, downsample=None):
        super(ResidualBlock, self).__init__()
        self.conv1 = conv3x3(in_channels, out_channels, stride)
        self.bn1 = nn.BatchNorm2d(out_channels)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = conv3x3(out_channels, out_channels)
        self.bn2 = nn.BatchNorm2d(out_channels)
        self.downsample = downsample

    def forward(self, x):
        residual = x
        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)
        out = self.conv2(out)
        out = self.bn2(out)
        if self.downsample:
            residual = self.downsample(x)
        out += residual
        out = self.relu(out)
        return out

有人知道这是怎么回事吗? 它是标准的 python class 继承特性还是特定于 pytorch?

你在init函数中定义层,也就是参数。在 forward 函数中,您只需输入需要使用 init 中的预定义设置处理的数据。 nn.whatever 使用您传递给它的设置构建一个函数。那么这个函数就可以在forward中使用,而且这个函数只有一个参数。

您在 class(__init__ 函数)的构造函数中定义网络架构的不同层。本质上,当您创建不同层的实例时,您使用您的设置参数初始化它们。

例如,当您声明第一个卷积层时,self.conv1,您给出了初始化该层所需的参数。在 forward 函数中,您只需简单地调用具有输入的层即可获得相应的输出。例如,在 out = self.conv2(out) 中,您将上一层的输出作为下一个 self.conv2 层的输入。

请注意,在初始化期间,您向层提供信息,即 kind/shape 的输入将提供给该层。例如,您告诉第一个卷积层您的输入中输入和输出通道的数量是多少。在forward方法中,你只需要传递输入即可。