How to loop over all the variable in a nn.module

Is there any way that I can iterate through all the layers in an arbitrary model with still knowing what type of layer they are, i.e. Conv2d, Linear, etc.? Right now I could only think of doing a breath first search on the _module.items(). Thank you.

2 Likes

yes, you can use .named_children or .apply.

http://pytorch.org/docs/master/nn.html?highlight=named_children#torch.nn.Module.named_children
http://pytorch.org/docs/master/nn.html?highlight=named_children#torch.nn.Module.apply

2 Likes