【问题标题】:How to iterate over layers in Pytorch如何在 Pytorch 中迭代图层
【发布时间】:2019-06-09 17:40:08
【问题描述】:

假设我有一个名为m 的网络模型对象。现在我没有关于这个网络有多少层的先验信息。如何创建一个 for 循环来迭代其层? 我正在寻找类似的东西:

Weight=[]
for layer in m._modules:
    Weight.append(layer.weight)

【问题讨论】:

标签: python machine-learning neural-network deep-learning pytorch


【解决方案1】:

假设您有以下神经网络。

import torch
import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):

    def __init__(self):
        super(Net, self).__init__()
        # 1 input image channel, 6 output channels, 5x5 square convolution
        # kernel
        self.conv1 = nn.Conv2d(1, 6, 5)
        self.conv2 = nn.Conv2d(6, 16, 5)
        # an affine operation: y = Wx + b
        self.fc1 = nn.Linear(16 * 5 * 5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)

    def forward(self, x):
        # define the forward function 
        return x

现在,让我们打印与每个 NN 层相关的权重参数的大小。

model = Net()
for name, param in model.named_parameters():
    print(name, param.size())

输出

conv1.weight torch.Size([6, 1, 5, 5])
conv1.bias torch.Size([6])
conv2.weight torch.Size([16, 6, 5, 5])
conv2.bias torch.Size([16])
fc1.weight torch.Size([120, 400])
fc1.bias torch.Size([120])
fc2.weight torch.Size([84, 120])
fc2.bias torch.Size([84])
fc3.weight torch.Size([10, 84])
fc3.bias torch.Size([10])

希望您可以扩展示例以满足您的需求。

【讨论】:

  • model.named_parameters()循环参数的通用方式吗?
【解决方案2】:

假设 m 是你的模块,那么你可以这样做:

for layer in m.children():
    weights = list(layer.parameters())

【讨论】:

    【解决方案3】:

    您可以使用children 方法:

    for module in model.children():
        # ...
    

    或者,如果你想flatten Sequential layers

    for module in model.modules():
        if not isinstance(module, nn.Sequential):
            # ...
    

    【讨论】:

      【解决方案4】:

      您可以使用model.named_parameters() 简单地获取它,这将返回一个生成器,您可以对其进行迭代并获取张量、其名称等。

      这是 resnet 预训练模型的代码:

      In [106]: resnet = torchvision.models.resnet101(pretrained=True)
      
      In [107]: for name, param in resnet.named_parameters(): 
           ...:     print(name, param.shape) 
      

      会输出

      conv1.weight torch.Size([64, 3, 7, 7])
      bn1.weight torch.Size([64])
      bn1.bias torch.Size([64])
      layer1.0.conv1.weight torch.Size([64, 64, 1, 1])
      layer1.0.bn1.weight torch.Size([64])
      layer1.0.bn1.bias torch.Size([64])
      ........
      ........ and so on
      

      你可以在how-to-manipulate-layer-parameters-by-its-names/找到一些关于这个话题的讨论

      【讨论】:

      • 还有没有办法获取每一层对应的操作(relu、pooling等)?例如,如果我只想提取 relu 层的张量。
      【解决方案5】:

      你也可以这样做:

      for name, m in mdl.named_children():
          print(name)
          print(m.parameters())
      

      参考:

      # https://discuss.pytorch.org/t/how-to-get-the-module-names-of-nn-sequential/39682
      # looping through modules but get the one with a specific name
      
      import torch
      import torch.nn as nn
      
      from collections import OrderedDict
      
      params = OrderedDict([
          ('fc0', nn.Linear(in_features=4,out_features=4)),
          ('ReLU0', nn.ReLU()),
          ('fc1L:final', nn.Linear(in_features=4,out_features=1))
      ])
      mdl = nn.Sequential(params)
      
      # throws error
      # mdl['fc0']
      
      for m in mdl.children():
          print(m)
      
      print()
      
      for m in mdl.modules():
          print(m)
      
      print()
      
      for name, m in mdl.named_modules():
          print(name)
          print(m)
      
      print()
      
      for name, m in mdl.named_children():
          print(name)
          print(m)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-01
        • 2023-02-20
        • 2019-11-23
        • 2021-03-27
        相关资源
        最近更新 更多