首页 > 解决方案 > 如何使用神经网络减少张量的维数

问题描述

我有一个大小为 [100,70,42](batch, seq_len, features)的 3D 张量,我想通过使用基于线性变换的神经网络(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-networkdeep-learningpytorchtensordimensionality-reduction

解决方案


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

推荐阅读