第一種方法:在構建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)