using ModuleList, still getting ValueError: optimizer got an empty parameter list

using ModuleList, still getting ValueError: optimizer got an empty parameter list

对于 Pytorch,我正在尝试使用 ModuleList 来确保检测到模型参数,并且可以对其进行优化。调用 SGD 优化器时出现以下错误:

ValueError: optimizer got an empty parameter list

能否查看下面的代码并提出建议?

class LR(nn.Module):
    def ___init___(self):
        super(LR, self).___init___()
        self.linear = nn.ModuleList()
        self.linear.append(nn.Linear(in_features=28*28, out_features=128, bias=True))
    
    def forward(self, x):
        y_p = torch.sigmoid(self.linear(x))
        return y_p

LR_model = LR()
optimizer = torch.optim.SGD(params = LR_model.parameters(), lr=learn_rate)

这似乎是一个复制粘贴问题:您的 __init____init__(self)super(LR, self).__init__() 处有 3 个下划线而不是 2 个。因此 init 本身失败了。删除多余的下划线并重试或尝试以下代码:

class LR(nn.Module):
    def __init__(self):
        super(LR, self).__init__()
        self.linear = nn.ModuleList()
        self.linear.append(nn.Linear(in_features=28*28,
                                     out_features=128, 
                                     bias=True))

    def forward(self, x):
        y_p = torch.sigmoid(self.linear(x))
        return y_p

    LR_model = LR()
    optimizer = torch.optim.SGD(params = list(LR_model.parameters()), 
                                lr=learn_rate)