【问题标题】:How to specify the input dimension of pytorch nn.Linear? [duplicate]如何指定pytorch nn.Linear的输入维度? [复制]
【发布时间】:2020-11-09 14:11:45
【问题描述】:

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

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)

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

【问题讨论】:

    标签: python deep-learning pytorch


    【解决方案1】:

    如果您不想明确计算输入大小,您可以使用LazyLinear 模块(而不是Linear)来推断:

    fc_out = nn.LazyLinear(out_dim)
    

    【讨论】:

      【解决方案2】:

      我这样做的方法是输入一些任意值并让模型抛出错误。您将能够在错误描述中看到输入特征的数量。

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

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

      【讨论】:

      猜你喜欢
      • 2019-06-23
      • 2021-09-09
      • 2019-10-23
      • 2020-07-16
      • 1970-01-01
      • 2019-07-21
      • 2019-04-27
      • 2018-11-01
      • 2023-02-06
      相关资源
      最近更新 更多