python - 如何在 PyTorch 中构建具有两个输入的网络
问题描述
假设我想拥有通用的神经网络架构:
Input1 --> CNNLayer
\
---> FCLayer ---> Output
/
Input2 --> FCLayer
Input1 是图像数据,input2 是非图像数据。我已经在 Tensorflow 中实现了这个架构。
我发现的所有 pytorch 示例都是通过每一层的一个输入。如何定义正向函数来分别处理 2 个输入,然后将它们组合在中间层中?
解决方案
通过“组合它们”,我假设您的意思是连接两个输入。
假设您沿着第二个维度连接:
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
您需要同时考虑out_channels
的self.conv
空间维度和输出空间维度c
。
推荐阅读
- c# - 使用 WebClient.UploadFile 将文件上传到 WebDAV 服务器返回 401
- c# - c# - 字段名称中的下划线
- python - 跳过没有属性的元组 Python NLTK
- flutter - google_sign_in signinSilently gets APIException PlatformException(sign_in_required, com.google.android.gms.common.api.ApiException: 4: 4: , null)
- matlab - 在 uiputfile 中设置文件夹 - Matlab
- java - 如何在java中分隔特定标签
- botframework - 如果 BotFramework 发送了两次 event 类型的活动,如何使用 activitymiddleware
- aws-cdk - AWS CDK: Unexpected token '?'
- python - Python 3: What should I do about this the Internal Python error in the inspect module
- android - how can i fix that android studio does not accept or detect my xml layouts when doing setContentView()?