PyTorch报错ValueError: optimizer got an empty parameter list求助
解决PyTorch中
ValueError: optimizer got an empty parameter list错误 错误场景
运行PyTorch代码时触发以下错误:
ValueError: optimizer got an empty parameter list
问题代码
class MultilayerpercePtron(nn.Module): def __init_(self,in_sz=784,out_sz=10,layers=[120,84]): super().__init__() self.fc1 = nn.linear(in_sz,layers[0]) self.fc2= nn.linear(layers[0],layers[1]) self.fc3 = nn.linear(layers[1],out_sz) def forward(self,x): x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return F.log_softmax(x,dim = 1) torch.manual_seed(101) model = MultilayerpercePtron() criterion = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(),lr=0.001)
错误原因及修正
1. 构造函数名称错误
原代码中构造函数写为__init_(仅一个下划线结尾),正确的Python类构造函数必须是__init__(前后各两个下划线)。名称错误会导致PyTorch无法正确初始化模型并注册可训练参数,最终model.parameters()返回空列表。
2. 线性层类名错误
PyTorch中的线性层类是nn.Linear(首字母大写),原代码中写成了小写的nn.linear,这会导致无法创建有效的线性层实例,同样造成参数未被注册。
修正后的代码
import torch import torch.nn as nn import torch.nn.functional as F class MultilayerpercePtron(nn.Module): def __init__(self, in_sz=784, out_sz=10, layers=[120,84]): super().__init__() self.fc1 = nn.Linear(in_sz, layers[0]) self.fc2 = nn.Linear(layers[0], layers[1]) self.fc3 = nn.Linear(layers[1], out_sz) def forward(self, x): x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return F.log_softmax(x, dim=1) torch.manual_seed(101) model = MultilayerpercePtron() criterion = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
内容的提问来源于stack exchange,提问作者mahdi norouzi
相关产品推荐
相关产品推荐

