参考

第一种方法:在构建model的时候return对应的层的输出

def forward(self, x):
    out1 = self.conv1(x)
    out2 = self.conv2(out1)
    out3 = self.fc(out2)

    return out1, out2, out3

第2中方法:当模型用Sequential构建时,则让输入依次通过各个模块,抽取出自己需要的输出

class ConvNet(nn.Module):
    def __init__(self, num_classes=10):
        super(ConvNet, self).__init__()
        self.layer1 = nn.Sequential(
            nn.Conv2d(1, 16, kernel_size=5, stride=1, padding=2),
            nn.BatchNorm2d(16),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2, stride=2),
            nn.Conv2d(16, 32, kernel_size=5, stride=1, padding=2),
            nn.BatchNorm2d(32),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2, stride=2))
    def forward(self, x):
        out = self.layer1(x)
        return out

model = ConvNet()
print(model)

x = torch.randn(3,1,32,32)
out = model(x)
print(out)

out = x
for i in list(model.layer1):
    out = i(out)
print(out)