Is it possible to instantiating modules as dictionary

Hi, I wonder if it is possible to instantiating modules in “init” as entries in a dictionary.

For example, is the following allowed?

class MyNet(nn.Module):
  def __init__(self):
      self.myModules = {}
      self.myModule['dog'] = nn.Linear(4096, 300)
      self.myModule['cat'] = nn.Linear(4096, 300)
      self.myModule['flower'] = nn.Linear(4096, 300)
  def forward(self, img):
      ...

This example is simple that it does not have to use dictionary, but what I actually need to do is something like following:

class MyNet(nn.Module):
  def __init__(self, number_of_modules):
      self.myModules = {}
      for i in range(0, number_of_modules):
          self.myModule[ 'dog' + str(i) ] = nn.Linear(4096, 300)
  def forward(self, img):
      ...

The modules are of same shape, but I don’t want them to share weights.

def __init__():
    .....
    for i in range(0, number_of_modules):
             setattr(self,'dog' + str(i) ,nn.Linear(4096, 300))
def forward(self,input):
  	dog1 = self.dog1(input)
  	dog2 = self.dog2(input)
  	dog3 = getattr(self,'dog3')(input)

or

def __init__():
    .....
    modules = []
    for i in range(0, number_of_modules):
             modules .append( nn.Linear(4096, 300))
    self.modules = nn.ModuleList(modules)
def forward(self,input):
  	outputs = []
    for model in self.modules:
      outputs.append(model(input))

also,try to format your code like:

```Python
your code here
```

4 Likes