【问题标题】:ValueError: optimizer got an empty parameter listValueError:优化器得到一个空的参数列表
【发布时间】:2019-12-10 18:08:14
【问题描述】:

我创建了以下简单的线性类:

class Decoder(nn.Module):
    def __init__(self, K, h=()):
        super().__init__()
        h = (K,)+h+(K,)
        self.layers = [nn.Linear(h1,h2) for h1,h2 in zip(h, h[1:])]

    def forward(self, x):
        for layer in self.layers[:-1]:
            x = F.relu(layer(x))
        return self.layers[-1](x)

但是,当我尝试将参数放入优化器类时,我收到错误 ValueError: optimizer got an empty parameter list

decoder = Decoder(4)
LR = 1e-3
opt = optim.Adam(decoder.parameters(), lr=LR)

类定义有什么明显错误的地方吗?

【问题讨论】:

标签: pytorch


【解决方案1】:

由于您将层存储在 Decoder 内的常规 pythonic 列表中,Pytorch 无法告诉 self.list 的这些成员实际上是子模块。把这个列表转换成pytorch的nn.ModuleList,你的问题就解决了

class Decoder(nn.Module):
    def __init__(self, K, h=()):
        super().__init__()
        h = (K,)+h+(K,)
        self.layers = nn.ModuleList(nn.Linear(h1,h2) for h1,h2 in zip(h, h[1:]))

【讨论】:

  • @NEERAJSWARNKAR 如果您有任何问题:照原样发布,而不是神秘评论
猜你喜欢
  • 2019-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多