Step 3: Designing the Convolutional Architecture
The heart of a CNN lies in its architecture, composed of convolutional layers, pooling layers, and fully connected layers. The selection of these components depends on the complexity of the task, dataset size, and available computational resources. Deeper architectures with more layers often excel in capturing intricate features but require additional computational capacity.
import torch.nn as nn# Define the CNN architecture
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = nn.Conv2d(3, 16, kernel_size=3, stride=1, padding=1)
self.relu = nn.ReLU()
self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
self.fc = nn.Linear(16 * 56 * 56, num_classes)
def forward(self, x):
x = self.conv1(x)
x = self.relu(x)
x = self.pool(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
# Create an instance of the CNN model
model = CNN()