Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pytorch Network.parameters() missing 1 required positional argument: 'self'

There's a problem when I call Network.parameters() in pytorch in this line in my main function: optimizer = optim.SGD(Network.parameters(), lr=0.001, momentum=0.9)

I get the error code:

TypeError: parameters() missing 1 required positional argument: 'self'

My network is defined in this class

class Network(nn.Module):
def __init__(self):
    super(Network, self).__init__()
    self.conv1 = nn.Conv2d(1, 32, 5)
    self.pool = nn.MaxPool2d(2, 2)
    self.conv2 = nn.Conv2d(32, 64, 5)
    self.pool2 = nn.MaxPool2d(2, 2)
    self.conv3 = nn.Conv2d(64, 64, 5)
    self.pool2 = nn.MaxPool2d(2, 2)
    self.fc1 = nn.Linear(64 * 5 * 5, 512)
    self.fc2 = nn.Linear(512, 640)
    self.fc3 = nn.Linear(640, 3756)

def forward(self, x):
    x = self.pool(F.relu(self.conv(x)))
    x = self.pool(F.relu(self.conv2(x)))
    x = self.pool(F.relu(self.conv3(x)))
    x = x.view(-1, 64 * 5 * 5)
    x = F.relu(self.fc1(x))
    x = F.relu(self.fc2(x))
    x = self.fc3(x)
    return x

Pretty sure that I imported all torch modules correctly. Any ideas of what I'm doing wrong here?

Thank you!

like image 303
SumakuTension Avatar asked May 04 '17 09:05

SumakuTension


2 Answers

When doing Network.parameters() you are calling the static method parameters.

But, parameters is an instance method.

So you have to instansiate Network before calling parameters.

network = Network()
optimizer = optim.SGD(network.parameters(), lr=0.001, momentum=0.9)

Or, if you only needs Network first this particular line:

optimizer = optim.SGD(Network().parameters(), lr=0.001, momentum=0.9)
like image 169
Arount Avatar answered Sep 23 '22 14:09

Arount


You need a particular Network instance, not just the Network class.

optimizer = optim.SGD(Network().parameters(), lr=0.001, momentum=0.9)

Note the parentheses to create an instance of the Network.

like image 40
Arya McCarthy Avatar answered Sep 24 '22 14:09

Arya McCarthy