如何在PyTorch中构造双输入网络

2024-04-25 18:00:34 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我想要一个通用的神经网络架构:

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

Input1是图像数据,input2是非图像数据。我已经在Tensorflow中实现了这个架构。在

我发现的所有pytorch示例都是一个输入遍历每一层。如何定义forward func分别处理2个输入,然后将它们组合到中间层?在


Tags: 数据图像示例output定义架构tensorflow神经网络
1条回答
网友
1楼 · 发布于 2024-04-25 18:00:34

我认为“组合它们”是指concatenate这两个输入。
假设你沿着第二个维度集中:

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.conv的{},以及{}的输出空间维度。在

相关问题 更多 >