"""Model definitions for the Oxford-IIIT Pet breed classifier. Two architectures are provided: * ``PetBreedCNN``: a convolutional network trained from scratch. * ``build_resnet18_classifier``: an ImageNet-pretrained ResNet18 with a new classification head, used as a transfer-learning baseline and as the deployed model. """ from __future__ import annotations import torch from torch import nn from torchvision import models NUM_CLASSES = 37 def _conv_block(in_channels: int, out_channels: int) -> nn.Sequential: """Two 3x3 convolutions followed by 2x2 max pooling. Each convolution is followed by batch normalization and a ReLU. The pooling layer halves the spatial resolution, so the receptive field grows with depth while the channel count increases. """ return nn.Sequential( nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, bias=False), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True), nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1, bias=False), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=2), ) class PetBreedCNN(nn.Module): """Convolutional neural network for 37-way breed classification. Architecture: 4 convolutional blocks (32, 64, 128, 256 channels) -> adaptive average pooling to a fixed 4x4 grid -> Linear(4096, 512) + ReLU + Dropout -> Linear(512, num_classes) The adaptive pooling layer makes the classifier head independent of the input resolution. The model outputs unnormalized logits, which is the input format expected by ``nn.CrossEntropyLoss``. """ def __init__(self, num_classes: int = NUM_CLASSES, dropout: float = 0.5) -> None: super().__init__() self.features = nn.Sequential( _conv_block(3, 32), _conv_block(32, 64), _conv_block(64, 128), _conv_block(128, 256), ) self.pool = nn.AdaptiveAvgPool2d((4, 4)) self.classifier = nn.Sequential( nn.Flatten(), nn.Linear(256 * 4 * 4, 512), nn.ReLU(inplace=True), nn.Dropout(p=dropout), nn.Linear(512, num_classes), ) def forward(self, x: torch.Tensor) -> torch.Tensor: """Map a batch of images (N, 3, H, W) to logits (N, num_classes).""" x = self.features(x) x = self.pool(x) return self.classifier(x) def build_resnet18_classifier( num_classes: int = NUM_CLASSES, pretrained: bool = True, dropout: float = 0.3, ) -> nn.Module: """Create a ResNet18 whose final layer is replaced for ``num_classes`` outputs. Args: num_classes: Number of output classes. pretrained: If True, initialize the backbone with ImageNet weights (requires a download on first use). Use False at inference time, because the fine-tuned weights are loaded from ``pet_breed_model.pth``. dropout: Dropout probability applied before the new linear layer. """ weights = models.ResNet18_Weights.IMAGENET1K_V1 if pretrained else None network = models.resnet18(weights=weights) network.fc = nn.Sequential( nn.Dropout(p=dropout), nn.Linear(network.fc.in_features, num_classes), ) return network def count_parameters(network: nn.Module) -> dict[str, int]: """Return the total and trainable parameter counts of ``network``.""" total = sum(parameter.numel() for parameter in network.parameters()) trainable = sum( parameter.numel() for parameter in network.parameters() if parameter.requires_grad ) return {"total": total, "trainable": trainable}