我试图在PyTorch中编程一个自定义层。我希望这一层完全连接到前一层,但同时我想从输入层提供一些信息,假设我希望它完全连接到第一层。例如,第四层将喂养第三层和第一层。这将使信息流在第一层分裂,然后将一个分支插入到网络中。
我必须在这一层定义有两个输入的前向。
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吗?
谢谢!
发布于 2022-01-13 21:15:07
只需将输入信息与前一层的输出连接起来,并将其提供给下一层,如下所示:
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 xhttps://stackoverflow.com/questions/70703071
复制相似问题