pytorch optimizer TypeError 'collections.OrderedDict' object is not callable

Viewed 132

I used python3.8, pytorch suddenly reported an error optimizer TypeError, but the program was still running two weeks ago.

net = Net(num_classes=7)
net.to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(net.parameters(), lr=1e-4)

It seems to be net.parameters() cannot return the correct result?

Traceback (most recent call last):
   File "C:/Users/usr/Desktop/jaffeAttention/jaffe.py", line 190, in <module>
       main()   
   File "C:/Users/usr/Desktop/jaffeAttention/jaffe.py", line 87, in main
      optimizer = optim.Adam(net.parameters(), lr=1e-4)
TypeError: 'collections.OrderedDict' object is not callable
 

enter image description here

1 Answers

You get the error because net.parameters is an OrderedDict, and you then try to call it with net.parameters(), but that is not possible. So you get an error.

To find this out, could try the commands

net = Net(num_classes=7)
net.to(device)
criterion = nn.CrossEntropyLoss()
params= net.parameters
print(type(params)) # verify this is indeed an OrderedDict
optimizer = optim.Adam(params, lr=1e-4) # notice there is no () when passing the params to Adam

You can read about OrderedDict in the python documentation. https://docs.python.org/3/library/collections.html#collections.OrderedDict

Related