python 22 lines · 1 tab

Convolutional neural networks for image classification in PyTorch

1 tab
import torch.nn as nn

class SmallCNN(nn.Module):
    def __init__(self, num_classes: int) -> None:
        super().__init__()
        self.features = nn.Sequential(
            nn.Conv2d(3, 32, kernel_size=3, padding=1),
            nn.ReLU(),
            nn.MaxPool2d(2),
            nn.Conv2d(32, 64, kernel_size=3, padding=1),
            nn.ReLU(),
            nn.MaxPool2d(2),
            nn.Conv2d(64, 128, kernel_size=3, padding=1),
            nn.ReLU(),
            nn.AdaptiveAvgPool2d((1, 1)),
        )
        self.classifier = nn.Linear(128, num_classes)

    def forward(self, x):
        x = self.features(x)
        x = x.view(x.size(0), -1)
        return self.classifier(x)
1 file · python Explain with highlit

For image work, I start with a compact CNN before reaching for heavy pretrained models. That baseline helps confirm whether labels, normalization, and augmentation are sane. It also makes failure cases easier to explain because the model architecture is still small enough to reason about directly.

Share this code

Here's the card — post it anywhere.

Convolutional neural networks for image classification in PyTorch — share card
Link copied