Using for loop to increase number of hidden layers

Hi Folks,
I am trying to increase the number of hidden layers in my existing code-

D = 32*32
n = 64 
C = 1
classes = 10

fc_model = nn.Sequential(

    nn.Flatten(),

    nn.Linear(D,  n), # I/P layer

    nn.Tanh(),
 # Hidden layers
    nn.Linear(n,  n),
    nn.Tanh(),
    nn.Linear(n,  n),
    nn.Tanh(),

    nn.Linear(n, classes),

)

How would be able to write say a for loop which will repeat the hidden layers multiple times ? If i try to write a for loop within sequential, it throws a syntax error.

Hi Ronish!

You can use a loop to insert your desired layers into a python
OrderedDict and then construct your Sequential by passing
in that OrderedDict as a single constructor argument (rather than
passing in all of the layers as individual constructor arguments).

Best.

K. Frank

1 Like