在PyTorch中手动初始化模型参数

我正在创建一个单独的类来初始化模型,并将层添加到一个列表中,但这些层并未被添加到模型的参数中,请告诉我如何将它们添加到模型的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])

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注