Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

python - Error: optimizer got an empty parameter list. How can i modify my code?

Here is code:

class MLP(nn.Module):  
    def __ini__(self):
         super (MLP, self). __init__()  
         self.model=nn.nn.Sequential(  
            nn.Linear(784, 200),
            nn.LeakyReLU(inplace=True),  
            nn.Linear(200, 200),
            nn.LeakyReLU(inplace=True),
            nn.Linear(200, 10),
            nn.LeakyReLU(inplace=True),
            )

    def forward(self,x):
                x=self.model(x)
                return 
device= torch.device('cuda:0')
net = MLP().to(device)

when running these codes

optimizer = optim.SGD(net.parameters(),lr=learning_rate)

I get

ValueError: optimizer got an empty parameter list"

I am trying to imitate this notebook.

question from:https://stackoverflow.com/questions/65903600/error-optimizer-got-an-empty-parameter-list-how-can-i-modify-my-code

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are several issues with your code. Currently your code is equivalent to:

class MLP(nn.Module):
    def forward(self, x):
        pass

Here are the issues:

  1. Your initializer is named __init__.

  2. forward should return a value, here x.

  3. Replace nn.nn.Sequential with nn.Sequential.


class MLP(nn.Module):
    def __init__(self):
        super (MLP, self).__init__()  
        self.model = nn.Sequential(  
            nn.Linear(784, 200),
            nn.LeakyReLU(inplace=True),  
            nn.Linear(200, 200),
            nn.LeakyReLU(inplace=True),
            nn.Linear(200, 10),
            nn.LeakyReLU(inplace=True))

    def forward(self,x):
        x = self.model(x)
        return x

device= torch.device('cuda:0')
net = MLP().to(device)

optimizer = torch.optim.SGD(net.parameters(), lr=learning_rate)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...