""" Transfer learning models for garbage classification. Supports MobileNetV3-Small, EfficientNet-B0, ResNet50. """ import torch import torch.nn as nn from torchvision import models NUM_CLASSES = 6 def build_mobilenetv3(freeze_backbone: bool = False) -> nn.Module: """MobileNetV3-Small with custom classification head.""" model = models.mobilenet_v3_small(weights=models.MobileNet_V3_Small_Weights.IMAGENET1K_V1) if freeze_backbone: for param in model.features.parameters(): param.requires_grad = False in_features = model.classifier[3].in_features model.classifier[3] = nn.Linear(in_features, NUM_CLASSES) return model def build_efficientnet_b0(freeze_backbone: bool = False) -> nn.Module: """EfficientNet-B0 with custom classification head.""" model = models.efficientnet_b0(weights=models.EfficientNet_B0_Weights.IMAGENET1K_V1) if freeze_backbone: for param in model.features.parameters(): param.requires_grad = False in_features = model.classifier[1].in_features model.classifier[1] = nn.Linear(in_features, NUM_CLASSES) return model def build_simple_cnn() -> nn.Module: """Baseline 5-layer CNN (scratch) for comparison.""" return nn.Sequential( nn.Conv2d(3, 32, 3, padding=1), nn.BatchNorm2d(32), nn.ReLU(), nn.MaxPool2d(2), nn.Conv2d(32, 64, 3, padding=1), nn.BatchNorm2d(64), nn.ReLU(), nn.MaxPool2d(2), nn.Conv2d(64, 128, 3, padding=1), nn.BatchNorm2d(128), nn.ReLU(), nn.MaxPool2d(2), nn.Conv2d(128, 256, 3, padding=1), nn.BatchNorm2d(256), nn.ReLU(), nn.AdaptiveAvgPool2d(4), nn.Flatten(), nn.Linear(256 * 4 * 4, 512), nn.ReLU(), nn.Dropout(0.4), nn.Linear(512, NUM_CLASSES), ) def build_resnet50(freeze_backbone: bool = False) -> nn.Module: """ResNet50 with custom classification head.""" model = models.resnet50(weights=models.ResNet50_Weights.IMAGENET1K_V2) if freeze_backbone: for name, param in model.named_parameters(): if "layer4" not in name and "fc" not in name: param.requires_grad = False model.fc = nn.Sequential( nn.Dropout(0.3), nn.Linear(model.fc.in_features, NUM_CLASSES) ) return model MODEL_REGISTRY = { "mobilenetv3": build_mobilenetv3, "efficientnet_b0": build_efficientnet_b0, "resnet50": build_resnet50, "simple_cnn": build_simple_cnn, }