【问题标题】:Get some layers in a pytorch model that is not defined by nn.Sequential在 nn.Sequential 未定义的 pytorch 模型中获取一些层
【发布时间】:2021-05-11 02:03:11
【问题描述】:

我在下面定义了一个网络。

class model_dnn_2(nn.Module):
    def __init__(self):
        super(model_dnn_2, self).__init__()
        self.flatten = Flatten()
        self.fc1 = nn.Linear(784, 200)
        self.fc2 = nn.Linear(200, 100)
        self.fc3 = nn.Linear(100, 100)
        self.fc4 = nn.Linear(100, 10)

    def forward(self, x):
        x = self.flatten(x)
        x = self.fc1(x)
        x = F.relu(x)
        x = self.fc2(x)
        x = F.relu(x)
        x = self.fc3(x)
        x = F.relu(x)
        x = self.fc4(x)

我想将最后两层与 relu 函数一起使用。使用children 方法我得到以下内容

>>> new_model = nn.Sequential(*list(model.children())[-2:])
>>> new_model
Sequential(
  (0): Linear(in_features=100, out_features=100, bias=True)
  (1): Linear(in_features=100, out_features=10, bias=True)
)

但我希望 Relu 函数出现在层之间 - 就像原始模型一样,即新模型应该是这样的:

>>> new_model
Sequential(
  (0): Linear(in_features=100, out_features=100, bias=True)
  (1): Relu()
  (2): Linear(in_features=100, out_features=10, bias=True)
)

我认为模型的children方法是使用类初始化来创建模型,因此出现了问题。

如何获取模型?

【问题讨论】:

    标签: pytorch


    【解决方案1】:

    按照您实现模型的方式,ReLU 激活不是层,而是函数。列出模块的子层(也称为“子层”)时,您看不到 ReLUs。

    你可以改变你的实现:

    class model_dnn_2(nn.Module):
        def __init__(self):
            super(model_dnn_2, self).__init__()
            self.layers = nn.Sequential(
              nn.Flatten(),
              nn.Linear(784, 200),
              nn.ReLU(),  # now you are using a ReLU _layer_
              nn.Linear(200, 100),
              nn.ReLU(),  # this is a different ReLU _layer_
              nn.Linear(100, 100),
              nn.ReLU(),
              nn.Linear(100, 10)
            )
    
        def forward(self, x):
          y = self.layers(x)
          return y
    

    更多关于层和函数的区别可以找到here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-17
      • 2017-11-01
      • 1970-01-01
      • 2021-01-12
      • 2020-10-07
      • 1970-01-01
      • 2021-05-08
      • 2019-05-25
      相关资源
      最近更新 更多