How can I get all the User defined attributes of nn.Module

  class, instance, python, pytorch, torch

the __dict__ attribute of nn.Module does not include other module instances, dir only includes the names. Is there somehow a way I can get the attributes as a dict or something similar?

class SomeNetwork(nn.Module):
    def __init__(self):
        super(SomeNetwork, self).__init__()
        self.randomBool = True
        self.someList = [24, 24, 524, 52]
        self.layer1 = nn.Linear(23, 42)
        self.layer2 = nn.Linear(42, 100)

        ...

print(dict_with_modules_inluded(SomeNetwork())

And this gets printed.

{‘randomBool’: True, ‘someList’: [24, 24, 524, 52], ‘layer1’: Linear(in_features=23, out_features=42, bias=True), ‘layer2’: Linear(in_features=42, out_features=100, bias=True)}

It doesnt matter much if other internal attributes is included printed

Source: Python Questions

LEAVE A COMMENT