Using NN module List in C++ API


I am aware of this wonderful functionality in the Python API to declare a simple feedforward network in a loop using ModuleList. I am now trying to port my code into C++ and having trouble replicating the code there. I am not sure how the ModuleList works in C++. Any help would be great!

def __init__(self, numLayers, numNeuronsPerLyr):
        self.layers = nn.ModuleList();
        current_dim = 2;

        for lyr in range(numLayers): # define the layers in loop
            l = nn.Linear(current_dim, numNeuronsPerLyr);
            current_dim = numNeuronsPerLyr;
        self.layers.append(nn.Linear(current_dim, 3));
def forward(self, x):
        m = nn.LeakyReLU();
        ctr = 0;
        for layer in self.layers[:-1]: # forward prop
            x = m(self.bnLayer[ctr](layer(x))); # ReLU in all hidden layers
            ctr += 1;
        out = torch.softmax(self.layers[-1](x), dim = 1); # output layer softmax
        return out 

We have a simple instruction in the comment here:

We have tests here, it contains more examples.

1 Like