Replace Last Fully Connected Layer with Convolutional Layer in PyTorch
To change the last fully connected layer to a convolutional layer, you need to modify the "init" function as follows:
\n```python
def init(self):
super(Model, self).init()
self.conv1 = torch.nn.Sequential(torch.nn.Conv2d(1,64,kernel_size=3,stride=1,padding=1),
torch.nn.ReLU(),
torch.nn.Conv2d(64,128,kernel_size=3,stride=1,padding=1),
torch.nn.ReLU(),
torch.nn.MaxPool2d(stride=2,kernel_size=2))
self.conv2 = torch.nn.Sequential(torch.nn.Conv2d(128,256,kernel_size=3,stride=1,padding=1),
torch.nn.ReLU(),
torch.nn.Conv2d(256,256,kernel_size=3,stride=1,padding=1),
torch.nn.ReLU(),
torch.nn.MaxPool2d(stride=2,kernel_size=2))
self.conv3 = torch.nn.Sequential(torch.nn.Conv2d(256,512,kernel_size=3,stride=1,padding=1),
torch.nn.ReLU(),
torch.nn.Conv2d(512,512,kernel_size=3,stride=1,padding=1),
torch.nn.ReLU(),
torch.nn.MaxPool2d(stride=2,kernel_size=2))
self.conv4 = torch.nn.Sequential(torch.nn.Conv2d(512,512,kernel_size=3,stride=1,padding=1),
torch.nn.ReLU(),
torch.nn.Conv2d(512,512,kernel_size=3,stride=1,padding=1),
torch.nn.ReLU(),
torch.nn.MaxPool2d(stride=2,kernel_size=2))
self.conv5 = torch.nn.Sequential(torch.nn.Conv2d(512,512,kernel_size=3,stride=1,padding=1),
torch.nn.ReLU(),
torch.nn.Conv2d(512,512,kernel_size=3,stride=1,padding=1),
torch.nn.ReLU(),
torch.nn.MaxPool2d(stride=2,kernel_size=2))
self.fc = torch.nn.Sequential(torch.nn.Linear(77512,4096),
torch.nn.ReLU(),
torch.nn.Dropout(p=0.5),
torch.nn.Linear(4096,4096),
torch.nn.ReLU(),
torch.nn.Dropout(p=0.5),
torch.nn.Conv2d(4096, 10, kernel_size=1))\
\
In this modified code, the last fully connected layer (`self.dense`) is replaced with a convolutional layer (`self.fc`). The input size for the `torch.nn.Linear` layer is set to `7*7*512`, which is the output size of the last convolutional layer (`self.conv5`). Additionally, the output size of the convolutional layer is set to `10`, which is the desired number of output classes.
原文地址: https://www.cveoy.top/t/topic/pCgc 著作权归作者所有。请勿转载和采集!