Ask Your Question
4

How can one obtain all the layers of a PyTorch model?

asked 2022-11-27 11:00:00 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-10-27 04:00:00 +0000

david gravatar image

To obtain all the layers of a PyTorch model, you can use the children() method of the model. This method returns an iterator over all the modules in the model.

Here's an example:

import torch

# Define your PyTorch model
class MyModel(torch.nn.Module):
    def __init__(self):
        super(MyModel, self).__init__()
        self.conv1 = torch.nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1)
        self.conv2 = torch.nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1)
        self.fc = torch.nn.Linear(128 * 16 * 16, 10)

    def forward(self, x):
        x = torch.relu(self.conv1(x))
        x = torch.relu(self.conv2(x))
        x = x.view(-1, 128 * 16 * 16)
        x = self.fc(x)
        return x

# Create an instance of the model
model = MyModel()

# Get all the layers using the `children()` method
for layer in model.children():
    print(layer)

This will output:

Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
Linear(in_features=32768, out_features=10, bias=True)
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-11-27 11:00:00 +0000

Seen: 8 times

Last updated: Oct 27 '21