How can I print the image of each layer in CNN?

I want to print the output in image of each layer just like picture above
how can I do it??

class CNN(nn.Module):

    def __init__(self):
        super(CNN, self).__init__()
        self.layer1 = nn.Sequential(
            nn.Conv2d(1, 32, kernel_size = 3, stride = 1, padding = 1),
            nn.MaxPool2d(kernel_size = 2, stride = 2))
        self.layer2 = nn.Sequential(
            nn.Conv2d(32, 64, kernel_size = 3, stride = 1, padding =1),
            nn.MaxPool2d(kernel_size = 2, stride = 2))
        self.fc = nn.Linear(7 * 7 * 64, 10, bias = True) #0~9 10개
    def forward(self, x):
        out = self.layer1(x)
        imgprt = out.numpy()
        imgplot = plt.imshow(imgprt)
        out = torch.from_numpy(out)
        out = self.layer2(out)
        out = out.view(out.size(0), -1)
        out = self.fc(out)
        return out

RuntimeError: Can't call numpy() on Variable that requires grad. Use var.detach().numpy() instead.

i tried to change the data type in numpy and use plt.imshow() in forward but didn’t work.

1 Like

Was the suggested workaround also not working? (Use var.detach().numpy() instead.)

For a more general approach, I would recommend to store the wanted activation in a list or dict by using forward hooks as described here.

The image is really awesome, would you please share where you get the original picture?
thank you very much !

I just copied image from somewhere.

I forgot where I copied it from. It was quite a long time.

but you can try right click on that image and search image in google.
(If you are using google chrome browser)