我正在创建一个单独的类来初始化模型,并将层添加到一个列表中,但这些层并未被添加到模型的参数中,请告诉我如何将它们添加到模型的parameters()中。
class Mnist_Net(nn.Module):def __init__(self,input_dim,output_dim,hidden_layers=2,neurons=128): super().__init__() layers = [] for i in range(hidden_layers): if len(layers) == 0: layers.append(nn.Linear(input_dim,neurons)) if i == hidden_layers-1: layers.append(nn.Linear(layers[-2].weight.shape[0],output_dim)) layers.append(nn.Linear(layers[i-1].weight.shape[0],neurons)) self.layers= layers
当我打印model.parameters()时
model = Mnist_Net(28*28,10,neurons=56) for t in model.parameters(): print(t)
它显示为空,但是当我在类中像这样添加层时
self.layer1 = nn.Linear(input_dim,neurons)
它显示了一个层在parameters中。请告诉我如何将self.layers中的所有层添加到model.parameters()中
回答:
为了在父模块中注册,你的子模块本身应该是一个nn.Module
。在你的情况下,你应该用nn.ModuleList
包装layers
:
self.layers = nn.ModuleList(layers)
这样,你的层就会被注册:
>>> model = Mnist_Net(28*28,10, neurons=56)>>> for t in model.parameters():... print(t.shape)torch.Size([56, 784])torch.Size([56])torch.Size([56, 56])torch.Size([56])torch.Size([10, 56])torch.Size([10])torch.Size([56, 56])torch.Size([56])