如何使用神经网络减少张量的尺寸

Dan*_*iel 0 neural-network dimensionality-reduction deep-learning pytorch tensor

我有一个大小为[100,70,42]的3D张量(批处理,seq_len,要素),我想通过使用基于线性变换的神经网络来获取大小为[100,1,1]的张量。在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
Run Code Online (Sandbox Code Playgroud)

但是,在训练后,这只会给我输出[100,70,1]的形状,这不是期望的形状。

谢谢!

小智 5

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
Run Code Online (Sandbox Code Playgroud)