使用信息流中的分支对 Pytorch 神经网络进行编程

Programing a Pytorch neural network with a branch in the flow of information

我正在尝试在 PyTorch 中编写自定义层。我希望这一层完全连接到上一层,但同时我想从输入层提供一些信息,假设我也希望它也完全连接到第一层。例如,第 4 层将喂给第 3 层和第 1 层。 这将使信息流在第一层分裂,然后将一个分支插入网络。

我必须在这一层定义前向有两个输入

class MyLayer(nn.Module):

    def __init__(self, size_in, size_out):
        super().__init__()

        self.size_in, self.size_out = size_in, size_out

        weights = torch.Tensor(size_out, size_in)

        (... ...)

    def forward(self, first_layer, previous_layer):

            (... ...)

        return output

如果我将这一层放在之后,比方说,一个仅将前一层的输出作为输入的普通前馈,我该如何进行这项工作? 我可以在这个图层上使用 nn.Sequential 吗?

谢谢!

只需将输入信息与前一层的输出连接起来,并将其提供给下一层,例如:

class Net(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = nn.Linear(100, 120) #supose your input shape is 100
        self.fc2 = nn.Linear(120, 80)
        self.fc3 = nn.Linear(180, 10)

    def forward(self, input_layer):

        x = F.relu(self.fc1(input_layer))
        x = F.relu(self.fc2(x))
        x = torch.cat((input_layer, x), 0)
        x = self.fc3(x) #this layer is fed by the input info and the previous layer
        return x