如何在PyTorch中构建一个带有两个输入的神经网络

34

假设我想要有通用的神经网络结构:

Input1 --> CNNLayer 
                    \
                     ---> FCLayer ---> Output
                    /
Input2 --> FCLayer

输入1是图像数据,输入2是非图像数据。我已经在Tensorflow中实现了这个架构。

我找到的所有PyTorch示例都是一个输入通过每一层。如何定义forward函数以分别处理2个输入,然后将它们组合在中间层中?

1个回答

34

我假设你所说的“combine them”意味着要连接这两个输入。
假设你沿第二个维度进行连接:

import torch
from torch import nn

class TwoInputsNet(nn.Module):
  def __init__(self):
    super(TwoInputsNet, self).__init__()
    self.conv = nn.Conv2d( ... )  # set up your layer here
    self.fc1 = nn.Linear( ... )  # set up first FC layer
    self.fc2 = nn.Linear( ... )  # set up the other FC layer

  def forward(self, input1, input2):
    c = self.conv(input1)
    f = self.fc1(input2)
    # now we can reshape `c` and `f` to 2D and concat them
    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.convout_channels 以及 c 的输出空间尺寸。

如果我的输入都是图像数据,比如两张大小为120X90的灰度图像,我该如何进行连接操作? - iCHAIT
@iCHAIT,如果它们的空间大小相同,您可以在“通道”维度上连接它们。 - Shai
有没有一些良好的策略可以将输入1和输入2一起归一化?这是否应该被考虑? - dermen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接