I faced something similar recently. I did not want to use nn.Sequential
. When I print the model it did not show the operations I defined using loop in forward function. This solution worked for me.
I did not use loop in __init__
function to define the layers when defining the model. Only stored the layer in a variable then in forward
function looped over it. This resulted in print(model)
not showing layers added using for loop defined in forward function. Solution was to use nn.ModuleList.
This code below shows wrong results,
Code
class MyModel(nn.Module):
def __init__(self, input_units, hidden_units, hidden_layer_count, output_units):
super(MyModel, self).__init__()
self.hidden_layer_count = hidden_layer_count
self.input_layer = nn.Linear(in_features=input_units, out_features=hidden_units)
self.hidden_layer = nn.Linear(in_features=hidden_units, out_features=hidden_units)
self.output_layer = nn.Linear(in_features=hidden_units, out_features=output_units)
def forward(self, item):
x = self.input_layer(item)
for i in range(self.hidden_layer_count):
x = self.hidden_layer(x)
output = self.output_layer(x)
return output
my_model = MyModel(input_units=2, hidden_units=128, hidden_layer_count=7, output_units=3)
print(my_model)
Output
MyModel(
(input_layer): Linear(in_features=2, out_features=128, bias=True)
(hidden_layer): Linear(in_features=128, out_features=128, bias=True)
(output_layer): Linear(in_features=128, out_features=3, bias=True)
)
This code below defines the layers in loop with nn.ModuleList
and the in forward function those layer are traversed. This gives expected result.
Code
class MyModel2(nn.Module):
def __init__(self, input_units, hidden_units, hidden_layer_count, output_units):
super(MyModel2, self).__init__()
self.hidden_layer_count = hidden_layer_count
self.input_layer = nn.Linear(in_features=input_units, out_features=hidden_units)
self.hidden_layers = nn.ModuleList([nn.Linear(
in_features=hidden_units, out_features=hidden_units
) for i in range(hidden_layer_count)])
self.output_layer = nn.Linear(in_features=hidden_units, out_features=output_units)
def forward(self, item):
x = self.input_layer(item)
for hidden_layer in self.hidden_layers:
x = hidden_layer(x)
output = self.output_layer(x)
return output
my_model2 = MyModel2(input_units=2, hidden_units=128, hidden_layer_count=7, output_units=3)
print(my_model2)
Output
MyModel2(
(input_layer): Linear(in_features=2, out_features=128, bias=True)
(hidden_layers): ModuleList(
(0): Linear(in_features=128, out_features=128, bias=True)
(1): Linear(in_features=128, out_features=128, bias=True)
(2): Linear(in_features=128, out_features=128, bias=True)
(3): Linear(in_features=128, out_features=128, bias=True)
(4): Linear(in_features=128, out_features=128, bias=True)
(5): Linear(in_features=128, out_features=128, bias=True)
(6): Linear(in_features=128, out_features=128, bias=True)
)
(output_layer): Linear(in_features=128, out_features=3, bias=True)
)