How can I extract my fc layer ’output or my self.layer3 ’output as my picture feature?

This is my codes, and Iwant to extract the data of 128 dimensions in fc,and the output of layer3 of CNN,How can I do it ?Thank you!

class CNN(nn.Module):
    def __init__(self):
        super(CNN, self).__init__()
        self.layer1 = nn.Sequential(
            nn.Conv2d(1, 16, kernel_size=3,stride=1,padding=1),  # b, 16, 34, 34
            nn.BatchNorm2d(16),
            nn.ReLU(inplace=True))

        self.layer2 = nn.Sequential(
            nn.Conv2d(16, 32, kernel_size=3,stride=1,padding=1),  # b, 32, 34, 34
            nn.BatchNorm2d(32),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=2, stride=2)  #b, 32, 17, 17
        )
        self.layer3 = nn.Sequential(
            nn.Conv2d(32, 64, kernel_size=3,stride=1,padding=1),  #b, 64, 17, 17
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True))

        self.fc = nn.Sequential(
            nn.Linear(64 * 17 * 17, 1024),
            nn.ReLU(inplace=True),
            nn.Linear(1024, 128),
            nn.ReLU(inplace=True),
            nn.Linear(128,4))
        
        self.drop = nn.Dropout(p=0.5)

    def forward(self, x):
        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = x.view(x.size(0), -1)
        x = self.fc(x)
        return x

model=CNN()
print(model)
optimizer = torch.optim.Adam(model.parameters())
loss_func = torch.nn.CrossEntropyLoss()

go through the thread to learn how to do it.

1 Like