You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 00:47:06