如何在 PyTorch 中构建具有两个输入的网络 [英] How to construct a network with two inputs in PyTorch
问题描述
假设我想要通用的神经网络架构:
Suppose I want to have the general neural network architecture:
Input1 --> CNNLayer
---> FCLayer ---> Output
/
Input2 --> FCLayer
Input1 是图像数据,input2 是非图像数据.我已经在 Tensorflow 中实现了这个架构.
Input1 is image data, input2 is non-image data. I have implemented this architecture in Tensorflow.
我发现的所有 pytorch 示例都是通过每一层的一个输入.如何定义前向函数来分别处理 2 个输入,然后将它们组合在中间层?
All pytorch examples I have found are one input go through each layer. How can I define forward func to process 2 inputs separately then combine them in a middle layer?
推荐答案
组合它们"我认为您的意思是 连接两个输入.
假设您沿第二维连接:
By "combine them" I assume you mean to concatenate the two inputs.
Assuming you concat along the second dimension:
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
的 out_channels
作为以及c
的输出空间维度.
Note that when you define the number of inputs to self.fc2
you need to take into account both out_channels
of self.conv
as well as the output spatial dimensions of c
.
这篇关于如何在 PyTorch 中构建具有两个输入的网络的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!