如何在PyTorch中使用两个输入构建网络

Leo*_*onG 5 python machine-learning computer-vision neural-network pytorch

假设我想拥有通用的神经网络架构:

Input1 --> CNNLayer 
                    \
                     ---> FCLayer ---> Output
                    /
Input2 --> FCLayer
Run Code Online (Sandbox Code Playgroud)

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

我发现的所有pytorch示例都是通过每一层的一个输入。如何定义前向功能来分别处理2个输入,然后将它们组合在中间层?

Sha*_*hai 5

通过“组合它们”,我假设您的意思是连接两个输入。
假设您沿着第二个维度进行合并:

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
Run Code Online (Sandbox Code Playgroud)

注意:在定义的输入数量是self.fc2需要兼顾out_channelsself.conv,以及输出空间尺寸c