How to reduce the dimensions of a tensor with neural networks
I have a 3D tensor of size [100,70,42] (batch, seq_len, features) and I would like to get a tensor of size [100,1,1] by using a neural network based on linear transformations (nn.Linear in Pytorch).

I have implemented the following code

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


However, upon training this only gives me an output of the shape [100,70,1], which is not the desired one.

Thanks!

nn.Linear acts only on last axis. If you want to apply linear over last two dimensions, you must reshape your input tensor:

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

