python - 如何在 PyTorch 中构建具有两个输入的网络

标签 python machine-learning neural-network computer-vision pytorch

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

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

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

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

最佳答案

通过“组合它们”,我假设您的意思是 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.convout_channels 作为以及 c 的输出空间维度。

关于python - 如何在 PyTorch 中构建具有两个输入的网络,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51700729/

相关文章:

python - Keras:微调 Inception 时精度下降

neural-network - 如何在 TensorFlow 中的图中构建一个带有循环的简单 RNN?

machine-learning - 什么是卷积神经网络的深度?

python - 无法构建opencv-python

python - Keras 自定义目标需要张量评估

再现 Fisher 线性判别图

neural-network - 预训练的 GloVe 矢量文件(例如 glove.6B.50d.txt)中的 "unk"是什么?

python - 将 cython 函数与 cython 方法传递给 scipy.integrate

python - Dataframe 上的 Pandas 条件返回 TypeError : '>' not supported between instances of 'str' and 'int'

python - 线性判别分析