IT/Pytorch

Pytorch Error: optimizer got an empty parameter list 해결(nn.ModuleList)

이녀기 2023. 5. 14. 21:22

문제상황

nn.Module을 상속한 신경망 클래스의 생성자에서 리스트에 레이어를 담으려니 에러가 났다.

 

Exception has occured: 

optimizer got an empty parameter list

class NN(nn.Module):
    def __init__(self, input_size=10):
    	self.network = []
        layer = nn.Linear(input_size, 16)
        self.network.append(layer)
    def forward(self, x):
    	for layer in self.network:
        	x = layer(x)
        return x

이런 상황이었다.

 

해결책

https://discuss.pytorch.org/t/valueerror-optimizer-got-an-empty-parameter-list-why-does-this-happen/127726/3

 

ValueError: optimizer got an empty parameter list why does this happen?

Thank you, it works. I fixed bottom and end to self.bottom and self.end. But I can’t understand how I use nn.ModuleList instead of a plain Python list.

discuss.pytorch.org

nn.ModuelList 를 Python plain list 대신 사용하면 된다고 한다.

torch module이 python plain list를 인식하지 못하기 때문에, Module으로 구성된 list를 만들려면 nn.ModuleList를 쓰라고 한다.

class NN(nn.Module):
    def __init__(self, input_size=10):
    	self.network = nn.ModuleList()
        layer = nn.Linear(input_size, 16)
        self.network.append(layer)
    def forward(self, x):
    	for layer in self.network:
        	x = layer(x)
        return x

 

배운점

이전에 같은 문제를 겪다가 torch에서 리스트를 인식하지 못하는 문제가 존재하나보다, 하고 넘어갔다. 검색하니 금방 해결할 수 있는 문제였는데, documentation이든 forum이든 빠르게 검색해보는 습관을 들여야할 것 같다. 사고력으로 고민할 문제와 내부 구현에 관한 문제를 구분하자!