假设我希望拥有以下一般的神经网络架构:
Input1 --> CNNLayer \ ---> FCLayer ---> Output /Input2 --> FCLayer
Input1 是图像数据,Input2 是非图像数据。我已经在Tensorflow中实现了这个架构。
我找到的所有PyTorch示例都是一个输入通过每一层。我如何定义前向函数来分别处理两个输入,然后在中间层将它们结合起来?
回答:
我假设你所说的“结合它们”是指拼接这两个输入。
假设你沿着第二个维度进行拼接:
import torchfrom torch import nnclass TwoInputsNet(nn.Module): def __init__(self): super(TwoInputsNet, self).__init__() self.conv = nn.Conv2d( ... ) # 在这里设置你的层 self.fc1 = nn.Linear( ... ) # 设置第一个全连接层 self.fc2 = nn.Linear( ... ) # 设置另一个全连接层 def forward(self, input1, input2): c = self.conv(input1) f = self.fc1(input2) # 现在我们可以将 `c` 和 `f` 重塑为2D并拼接它们 combined = torch.cat((c.view(c.size(0), -1), f.view(f.size(0), -1)), dim=1) out = self.fc2(combined) return out
请注意,当你定义 self.fc2
的输入数量时,你需要考虑 self.conv
的 out_channels
以及 c
的输出空间维度。