Python 使用ModuleList,仍然获取ValueError:优化器获取的参数列表为空
有了Pytorch,我试图使用ModuleList来确保检测到模型参数,并且可以进行优化。调用SGD优化器时,我得到以下错误: ValueError:优化器获取的参数列表为空 你能检查一下下面的代码并提出建议吗Python 使用ModuleList,仍然获取ValueError:优化器获取的参数列表为空,python,optimization,pytorch,valueerror,sgd,Python,Optimization,Pytorch,Valueerror,Sgd,有了Pytorch,我试图使用ModuleList来确保检测到模型参数,并且可以进行优化。调用SGD优化器时,我得到以下错误: ValueError:优化器获取的参数列表为空 你能检查一下下面的代码并提出建议吗 class LR(nn.Module): def ___init___(self): super(LR, self).___init___() self.linear = nn.ModuleList() self.linear.ap
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)
这似乎是一个复制粘贴问题:您的
\uuuuu init\uuuuuuuuuuuuuuuuuuuuuuu(self)
和super(LR,self)。\uuuuu init\uuuuuuuuuuuuuuuuuuuuuu()都有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)
检查这个