【问题标题】:Initializing model parameters in pytorch manually手动初始化pytorch中的模型参数
【发布时间】:2021-11-16 21:17:22
【问题描述】:

我正在创建一个单独的类来初始化模型并在列表中添加层,但是这些层没有被添加到参数中,请告诉如何将它们添加到模型的参数()中。

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)

它在参数中显示一层。请告诉我如何在 model.parameters() 中的 self.layers 中添加所有层

【问题讨论】:

    标签: python neural-network pytorch artificial-intelligence


    【解决方案1】:

    要在父模块中注册,您的子模块本身应该是nn.Modules。在您的情况下,您应该用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])
    

    【讨论】:

      猜你喜欢
      • 2020-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-30
      • 2020-08-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多