Deep learning 如何指定pytorch nn.Linear的输入维度?

Deep learning 如何指定pytorch nn.Linear的输入维度?,deep-learning,pytorch,Deep Learning,Pytorch,例如,我定义了一个模型,如下所示: class Net(nn.module): def __init__(): self.conv11 = nn.Conv2d(in_channel,out1_channel,3) self.conv12 = nn.Conv2d(...) self.conv13 = nn.Conv2d(...) self.conv14 = nn.Conv2d(...) ... #Here is the

例如,我定义了一个模型,如下所示:

class Net(nn.module):
   def __init__():
      self.conv11 = nn.Conv2d(in_channel,out1_channel,3)
      self.conv12 = nn.Conv2d(...)
      self.conv13 = nn.Conv2d(...)
      self.conv14 = nn.Conv2d(...)
      ...
      #Here is the point
      flat = nn.Flatten()
      #I don't want to compute the size of data after flatten, but I need a linear layer.

      fc_out = nn.Linear(???,out_dim)

问题是线性层,我不想计算输入到线性层的大小,但是定义模型需要指定它。如何解决这个问题?

我的方法是输入一些任意值,然后让模型抛出一个错误。您将能够在错误描述中看到输入功能的数量

还有其他方法可以做到这一点。您可以手工计算大小,并在描述层输出的每个
nn.Conv2d
层旁边编写注释。在使用
nn.flatte()
之前,您将获得输出,只需将除bacthsize之外的所有维度相乘即可。结果值是
nn.Linear()
层的输入特征数


如果你不想做这些,你可以试试。一个方便的软件包,可以让您定义像Keras这样的pytorch模型。

我在这里找到了另一种方法:首先明确打印最后一层的大小: