10

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!

SumakuTension
  • 542
  • 1
  • 9
  • 26
  • Possible duplicate of [TypeError: Missing 1 required positional argument: 'self'](http://stackoverflow.com/questions/17534345/typeerror-missing-1-required-positional-argument-self) – Arya McCarthy May 04 '17 at 09:53

2 Answers2

14

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)
Arount
  • 9,853
  • 1
  • 30
  • 43
  • `parameters()` is a library function in Torch. Can't change it. And semantically, you wouldn't want to—the function returns the parameters of a *particular* nn.Module. – Arya McCarthy May 04 '17 at 09:57
  • @aryamccarthy ho, yes. I updated my anwser, thx. Your one is surely the one, but I prefere to not remove my answer to explicit static / instance methods. – Arount May 04 '17 at 10:02
2

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.

Arya McCarthy
  • 8,554
  • 4
  • 34
  • 56