【问题标题】:How to reduce the dimensions of a tensor with neural networks如何使用神经网络减少张量的维数
【发布时间】:2020-03-01 02:22:49
【问题描述】:

我有一个大小为 [100,70,42](batch、seq_len、特征)的 3D 张量,我想通过使用基于线性变换的神经网络来获得一个大小为 [100,1,1] 的张量(nn.Pytorch 中的线性)。

我已经实现了以下代码

class Network(nn.Module):
   def __init__(self):
      super(Network, self).__init__()
      self.fc1 = nn.Linear(42, 120)
      self.fc2 = nn.Linear(120,1)

   def forward(self, input):
      model = nn.Sequential(self.fc1,
                            nn.ReLU(),
                            self.fc2)
      output = model(input)
      return output

但是,在训练时,这只会给我一个形状 [100,70,1] 的输出,这不是我想要的。

谢谢!

【问题讨论】:

    标签: neural-network deep-learning pytorch tensor dimensionality-reduction


    【解决方案1】:

    nn.Linear 仅作用于最后一个轴。如果你想在最后两个维度上应用线性,你必须重塑你的输入张量:

    class Network(nn.Module):
       def __init__(self):
          super(Network, self).__init__()
          self.fc1 = nn.Linear(70 * 42, 120)  # notice input shape
          self.fc2 = nn.Linear(120,1)
    
       def forward(self, input):
          input = input.reshape((-1, 70 * 42))  # added reshape
          model = nn.Sequential(self.fc1,
                                nn.ReLU(),
                                self.fc2)
          output = model(input)
          output = output.reshape((-1, 1, 1))  # OP asked for 3-dim output
          return output
    

    【讨论】:

      猜你喜欢
      • 2021-01-10
      • 1970-01-01
      • 1970-01-01
      • 2019-04-23
      • 2020-07-28
      • 1970-01-01
      • 2017-11-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多