Use loop to define network

Hi,

I encounter a problem when writing forward function.

def forward(self, x):
    x = self.l1(x)
    x = self.l2(x)
    .......
    return x

To avoid hard coding, I prefer a loop like

 for i in range(10):
     x = self.locals()[ 'l' + str(i) ]

But this doesn’t work since l1, l2 appear as the name of attribute. Any suggestion will be much appreciated.

what about this?

x = getattr(self,  'l' + str(i))

Alternatively, you can use nn.ModuleList

That works. Thanks a lot! But I still have some problems with following parts:

for i in range(10):
locals()[ ‘l’ + str(i) ] = nn.Linear(32, 32)
getattr(self, ‘l’ + str(i)) = locals() [ ‘l’ + str(i) ]

It seems that getattr can’t be used to define the attribute (only get), but I still need to define them in loop. locals() also failed for defining the layer.

You could use the corresponding setattr for this

1 Like