Search code examples
neural-networkpytorch

How to get an output dimension for each layer of the Neural Network in Pytorch?


class Model(nn.Module):
  def __init__(self):
    super(Model, self).__init__()
    self.net = nn.Sequential(
      nn.Conv2d(in_channels = 3, out_channels = 16), 
      nn.ReLU(), 
      nn.MaxPool2d(2),
      nn.Conv2d(in_channels = 16, out_channels = 16), 
      nn.ReLU(),
      Flatten(),
      nn.Linear(4096, 64),
      nn.ReLU(),
      nn.Linear(64, 10))

  def forward(self, x):
    return self.net(x)

I have created this model without a firm knowledge in Neural Network and I just fixed parameters until it worked in the training. I am not sure how to get the output dimension for each layer (e.g. output dimension after the first layer).

Is there an easy way to do this in Pytorch?


Solution

  • A simple way is:

    1. Pass the input to the model.
    2. Print the size of the output after passing every layer.
    class Model(nn.Module):
      def __init__(self):
        super(Model, self).__init__()
        self.net = nn.Sequential(
          nn.Conv2d(in_channels = 3, out_channels = 16), 
          nn.ReLU(), 
          nn.MaxPool2d(2),
          nn.Conv2d(in_channels = 16, out_channels = 16), 
          nn.ReLU(),
          Flatten(),
          nn.Linear(4096, 64),
          nn.ReLU(),
          nn.Linear(64, 10))
    
      def forward(self, x):
        for layer in self.net:
            x = layer(x)
            print(x.size())
        return x
    
    model = Model()
    x = torch.randn(1, 3, 224, 224)
    
    # Let's print it
    model(x)
    

    But be careful with the input size because you are using nn.Linear in your net. It would cause incompatible input size for nn.Linear if your input size is not 4096.