🐱🐢 MobileNetV2 β€” Cat vs Dog Image Classifier

The shortest accurate model possible β€” 3.5M parameters, ~13.5 MB on disk, 85%+ validation accuracy

πŸ“‹ Model Summary

Property Value
Architecture MobileNetV2
Base Checkpoint google/mobilenet_v2_1.0_224
Total Parameters ~3,504,872
Model Size (FP32) ~13.37 MB
Input Resolution 224 Γ— 224
Num Classes 2 (cat, dog)
Framework PyTorch + HuggingFace Transformers

Why MobileNetV2?

MobileNetV2 is the smallest viable architecture that achieves 85%+ accuracy on cats vs dogs:

  • Inverted residual blocks with depthwise separable convolutions β€” 10Γ— fewer FLOPs than standard convolutions
  • Linear bottlenecks prevent information loss in low-dimensional representations
  • Only 3.5M parameters vs. EfficientNet-B0 (5.3M), ResNet-50 (25.6M), or ViT-Base (86M)
  • Originally designed for mobile and edge deployment

πŸ“Š Dataset

Property Value
Source microsoft/cats_vs_dogs
Total Images 23,262
Train Split 18,609 (80%)
Validation Split 4,653 (20%)
Split Strategy Stratified by class, seed=42
Classes Cat (0), Dog (1)
Class Balance ~50/50 (balanced)

πŸ‹οΈ Training Steps

Step 1: Dataset Preparation

  • Load microsoft/cats_vs_dogs from HuggingFace Datasets
  • Manual 80/20 stratified train/validation split (dataset only has a single train split)
  • Verify class balance: ~50% cats, ~50% dogs in both splits

Step 2: Model Initialization

  • Load pretrained MobileNetV2 from google/mobilenet_v2_1.0_224 (ImageNet-1K weights)
  • Replace 1000-class classification head β†’ 2-class head (cat/dog)
  • ignore_mismatched_sizes=True handles the head swap automatically

Step 3: Data Augmentation & Preprocessing

Training transforms:

  • RandomResizedCrop(224, scale=(0.8, 1.0)) β€” random crop with scale augmentation
  • RandomHorizontalFlip(p=0.5) β€” mirror augmentation
  • ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.1) β€” color augmentation
  • Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) β€” ImageNet normalization

Validation transforms:

  • Resize(256) β†’ CenterCrop(224) β€” deterministic center crop
  • Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])

Step 4: Training Configuration

Hyperparameter Value
Optimizer AdamW
Learning Rate 2e-4
LR Scheduler Cosine with warmup (10%)
Weight Decay 1e-4
Epochs 10
Batch Size 32
Mixed Precision FP16
Metric Accuracy (best model selected)

Step 5: Training Execution

  • Fine-tune all layers (no frozen backbone)
  • Evaluate after every epoch
  • Save best model based on validation accuracy
  • Push final model to HuggingFace Hub

Step 6: Evaluation & Visualization

  • Compute final validation accuracy and loss
  • Generate training loss vs validation loss curves
  • Generate validation accuracy curve with 85% target line

πŸ“ˆ Training Curves

Training Curves

πŸ”¬ How to Use

from transformers import pipeline

classifier = pipeline("image-classification", model="DsJASPREET/mobilenetv2-cats-dogs-classifier")
result = classifier("path/to/cat_or_dog.jpg")
print(result)
# [{'label': 'cat', 'score': 0.98}, {'label': 'dog', 'score': 0.02}]

Or with manual preprocessing:

from transformers import AutoImageProcessor, AutoModelForImageClassification
from PIL import Image
import torch

processor = AutoImageProcessor.from_pretrained("DsJASPREET/mobilenetv2-cats-dogs-classifier")
model = AutoModelForImageClassification.from_pretrained("DsJASPREET/mobilenetv2-cats-dogs-classifier")

image = Image.open("cat.jpg")
inputs = processor(image, return_tensors="pt")

with torch.no_grad():
    logits = model(**inputs).logits
    
predicted_class = logits.argmax(-1).item()
print(model.config.id2label[predicted_class])  # "cat" or "dog"

πŸ“‘ Reference Papers

Paper Venue Link Relevance
MobileNetV2: Inverted Residuals and Linear Bottlenecks CVPR 2018 arxiv:1801.04381 Base architecture β€” inverted residual blocks + depthwise separable convolutions
EfficientNet: Rethinking Model Scaling for CNNs ICML 2019 arxiv:1905.11946 Compound scaling reference β€” larger but more accurate alternative
Cross-Dataset Generalization of Mobile CNN Architectures 2024 arxiv:2511.00335 Benchmarked 11 mobile architectures; MobileNetV2 ranked 3rd in cross-dataset generalization
MobileNetV3: Searching for MobileNetV3 ICCV 2019 arxiv:1905.02244 Successor with hardware-aware NAS; better accuracy but larger

πŸ—οΈ Architecture Details

MobileNetV2 Architecture:
β”œβ”€β”€ Conv2d (3β†’32, stride=2)           # Initial convolution
β”œβ”€β”€ InvertedResidual Γ—1  (32β†’16)      # Bottleneck block 1
β”œβ”€β”€ InvertedResidual Γ—2  (16β†’24)      # Bottleneck block 2  
β”œβ”€β”€ InvertedResidual Γ—3  (24β†’32)      # Bottleneck block 3
β”œβ”€β”€ InvertedResidual Γ—4  (32β†’64)      # Bottleneck block 4
β”œβ”€β”€ InvertedResidual Γ—3  (64β†’96)      # Bottleneck block 5
β”œβ”€β”€ InvertedResidual Γ—3  (96β†’160)     # Bottleneck block 6
β”œβ”€β”€ InvertedResidual Γ—1  (160β†’320)    # Bottleneck block 7
β”œβ”€β”€ Conv2d (320β†’1280)                 # Feature extraction
β”œβ”€β”€ AdaptiveAvgPool2d                 # Global pooling
β”œβ”€β”€ Dropout(0.2)                      # Regularization
└── Linear (1280β†’2)                   # Classification head (cat/dog)

Key Innovation β€” Inverted Residual Block:

Input β†’ 1Γ—1 Conv (expand) β†’ 3Γ—3 Depthwise Conv β†’ 1Γ—1 Conv (project) β†’ + Input
         ↑ expansion ratio                              ↑ linear bottleneck

🎯 Training Space

Train and try the model interactively: DsJASPREET/train-cats-dogs-classifier

License

Apache 2.0

Downloads last month

-

Downloads are not tracked for this model. How to track
Inference Providers NEW
This model isn't deployed by any Inference Provider. πŸ™‹ Ask for provider support

Dataset used to train DsJASPREET/mobilenetv2-cats-dogs-classifier

Space using DsJASPREET/mobilenetv2-cats-dogs-classifier 1

Papers for DsJASPREET/mobilenetv2-cats-dogs-classifier

Evaluation results