'Calculating dimensions of fully connected layer?

I am struggling to work out how to calculate the dimensions for the fully connected layer. I am inputing images which are (448x448) using a batch size (16). Below is the code for my convolutional layers:

class ConvolutionalNet(nn.Module):
  def __init__(self, num_classes=182):
    super().__init__()

    self.layer1 = nn.Sequential(
        nn.Conv2d(3, 16, kernal_size=5, stride=1, padding=2),
        nn.BatchNorm2d(16),
        nn.ReLU(),
        nn.MaxPool2d(kernal_size=2, stride=2)
    )

    self.layer2 = nn.Sequential(
        nn.Conv2d(16, 32, kernal_size=5, stride=1, padding=2),
        nn.BatchNorm2d(32),
        nn.ReLU(),
        nn.MaxPool2d(kernal_size=2, stride=2)
    )

    self.layer3 = nn.Sequential(
        nn.Conv2d(32, 32, kernal_size=5, stride=1, padding=2),
        nn.BatchNorm2d(32),
        nn.ReLU(),
        nn.MaxPool2d(kernal_size=2, stride=2)
    )

    self.layer4 = nn.Sequential(
        nn.Conv2d(32, 64, kernal_size=5, stride=1, padding=2),
        nn.BatchNorm2d(64),
        nn.ReLU(),
        nn.MaxPool2d(kernal_size=2, stride=2)
    )

    self.layer5 = nn.Sequential(
        nn.Conv2d(64, 64, kernal_size=5, stride=1, padding=2),
        nn.BatchNorm2d(64),
        nn.ReLU(),
        nn.MaxPool2d(kernal_size=2, stride=2)
    )

I want to add a fully connected layer:

self.fc = nn.Linear(?, num_classes)

Would anyone be able to explain the best way to go about calculating this? Also, if I have multiple fully connected layers e.g. (self.fc2, self.fc3), would the second parameter always equal the number of classes. I am new to coding and finding it hard to wrap my head around this.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source