获取pytorch模型中未由nn.Sequential定义的某些层

获取pytorch模型中未由nn.Sequential定义的某些层,pytorch,Pytorch,我有一个网络定义如下 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(1

我有一个网络定义如下

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)
)
我认为模型的
子类
方法是使用类初始化来创建模型,因此问题就出现了


如何获取模型?

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

您可以更改您的实现:

类模型dnn 2(nn.模块):
定义初始化(自):
super(model_dnn_2,self)。uuu init_uuu()
self.layers=nn.Sequential(
nn.flatte(),
nn.线性(784200),
nn.ReLU(),#现在您正在使用一个ReLU层_
nn.线性(200100),
nn.ReLU(),#这是一个不同的ReLU层_
nn.线性(100100),
nn.ReLU(),
nn.线性(100,10)
)
def前进(自身,x):
y=自分层(x)
返回y
更多关于层和函数之间差异的信息可以找到