Adding Convolutional Layers using For-Loop

Hi there,
I wanted to build a neural network which accepts the number of convolutional blocks [ conv layer + relu + maxpool ] as input from the user and then build the model accordingly. I thought of using a for loop for this purpose and the following is the code i tried to implement :

self.model = nn.Module
        for i in range(conv_blocks):
            name = "conv_{}".format(i+1)
            n_feats = 64*(2**i)
            model.add_module(name,nn.Conv2d(3,n_feats,3,stride=1))
            name = "relu_{}".format(i+1)
            model.add_module(name,nn.ReLU())
            name = "maxpool_{}".format(i+1)
            self.model.add_module(name,nn.MaxPool2d(3,stride=2))

However I’m getting the following error :

TypeError: add_module() missing 1 required positional argument: 'module'

Please help me with this one.
Thanks

This

self.model = nn.Module

doesn’t really look like you’re supposed to do it. You could use nn.Module().
An even cleaner way might be to use a ModuleList or Sequential.

Best regards

Thomas

Thanks alot !
It works :slight_smile: