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

我有一个大小为[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

但是,经过培训,这只会给我输出[100,1]形状,这不是期望的形状。

谢谢!

ugrgadd1 回答:如何使用神经网络减少张量的尺寸

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
本文链接:https://www.f2er.com/3164562.html

大家都在问