Kimmilkbreab's picture
Update app.py
f1fa739 verified
Raw History Blame Contribute Delete
14.5 kB
# =============================================================================
# COS30082 Bird Species Classification - Web Application
# =============================================================================
# Name: Kimberly George
# Student ID: 102781022
#
# This app demonstrates BOTH models for comparison:
# 1. SimpleCNN - Baseline model (3 conv layers, trained from scratch)
# 2. ResNet18 - Transfer learning model (pretrained on ImageNet)
#
# This allows side-by-side comparison to show why transfer learning works
# =============================================================================
import torch
import torch.nn as nn
from torchvision import models, transforms
from PIL import Image
import gradio as gr
# =============================================================================
# CONFIGURATION
# =============================================================================
NUM_CLASSES = 200 # CUB-200 dataset
# ImageNet normalization (used for both models)
IMAGENET_MEAN = [0.485, 0.456, 0.406]
IMAGENET_STD = [0.229, 0.224, 0.225]
# =============================================================================
# SimpleCNN MODEL DEFINITION
# =============================================================================
# This is the baseline model architecture - a simple 3-layer CNN.
# It demonstrates UNDERFITTING due to insufficient model capacity.
#
# Architecture:
# Input (224Γ—224Γ—3)
# β†’ Conv1 (32 filters) β†’ BatchNorm β†’ ReLU β†’ MaxPool β†’ 112Γ—112Γ—32
# β†’ Conv2 (64 filters) β†’ BatchNorm β†’ ReLU β†’ MaxPool β†’ 56Γ—56Γ—64
# β†’ Conv3 (128 filters) β†’ BatchNorm β†’ ReLU β†’ MaxPool β†’ 28Γ—28Γ—128
# β†’ Global Average Pooling β†’ 128
# β†’ FC (128β†’256) β†’ ReLU β†’ Dropout
# β†’ FC (256β†’200) β†’ Output
# =============================================================================
class SimpleCNN(nn.Module):
"""
Simple 3-layer CNN baseline model.
This model demonstrates underfitting - with only 3 convolutional layers,
it lacks the capacity to learn the complex features needed to distinguish
200 bird species. Expected accuracy: ~4%
"""
def __init__(self, num_classes):
super().__init__()
# Feature extraction: 3 convolutional blocks
self.features = nn.Sequential(
# Block 1: 3 β†’ 32 channels
nn.Conv2d(3, 32, kernel_size=3, padding=1),
nn.BatchNorm2d(32),
nn.ReLU(inplace=True),
nn.MaxPool2d(2), # 224β†’112
# Block 2: 32 β†’ 64 channels
nn.Conv2d(32, 64, kernel_size=3, padding=1),
nn.BatchNorm2d(64),
nn.ReLU(inplace=True),
nn.MaxPool2d(2), # 112β†’56
# Block 3: 64 β†’ 128 channels
nn.Conv2d(64, 128, kernel_size=3, padding=1),
nn.BatchNorm2d(128),
nn.ReLU(inplace=True),
nn.MaxPool2d(2) # 56β†’28
)
# Global Average Pooling: 28Γ—28Γ—128 β†’ 1Γ—1Γ—128
self.gap = nn.AdaptiveAvgPool2d(1)
# Classifier
self.classifier = nn.Sequential(
nn.Flatten(),
nn.Dropout(0.3),
nn.Linear(128, 256),
nn.ReLU(inplace=True),
nn.Dropout(0.4),
nn.Linear(256, num_classes)
)
def forward(self, x):
x = self.features(x)
x = self.gap(x)
x = self.classifier(x)
return x
# =============================================================================
# LOAD MODELS
# =============================================================================
def load_simplecnn():
"""Load the trained SimpleCNN model."""
model = SimpleCNN(NUM_CLASSES)
try:
checkpoint = torch.load("simplecnn_gap_norm_best.pth", map_location="cpu")
model.load_state_dict(checkpoint["model_state"])
print("βœ“ SimpleCNN loaded successfully")
except FileNotFoundError:
print("⚠ SimpleCNN weights not found - using random weights for demo")
print(" (This will show ~0.5% accuracy, demonstrating random guessing)")
model.eval()
return model
def load_resnet18():
"""
Load the fine-tuned ResNet18 model.
ResNet18 uses residual connections (skip connections) that allow
gradients to flow directly through the network, enabling training
of deeper networks without vanishing gradient problems.
"""
model = models.resnet18(weights=None)
model.fc = nn.Linear(model.fc.in_features, NUM_CLASSES)
try:
checkpoint = torch.load("resnet18_finetune_best.pth", map_location="cpu")
model.load_state_dict(checkpoint["model_state"])
print("βœ“ ResNet18 loaded successfully")
except FileNotFoundError:
print("⚠ ResNet18 weights not found")
model.eval()
return model
# Load both models at startup
print("Loading models...")
simplecnn_model = load_simplecnn()
resnet18_model = load_resnet18()
# =============================================================================
# IMAGE PREPROCESSING
# =============================================================================
# Both models use the same preprocessing pipeline:
# 1. Resize to 224Γ—224 (standard input size)
# 2. Convert to tensor (scale to [0,1])
# 3. Normalize with ImageNet statistics
# =============================================================================
transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD)
])
# =============================================================================
# LOAD CLASS NAMES
# =============================================================================
def load_class_names():
"""Load bird species names from file."""
try:
with open("class_names.txt", "r", encoding="utf-8") as f:
classes = [line.strip() for line in f if line.strip()]
print(f"βœ“ Loaded {len(classes)} class names")
return classes
except FileNotFoundError:
print("⚠ class_names.txt not found, using numbered labels")
return [f"Class {i}" for i in range(NUM_CLASSES)]
class_names = load_class_names()
# =============================================================================
# PREDICTION FUNCTIONS
# =============================================================================
def get_confidence_level(confidence):
"""Return confidence level indicator."""
if confidence >= 0.8:
return "🟒 High", "The model is confident in this prediction."
elif confidence >= 0.5:
return "🟑 Medium", "Consider this as a likely suggestion."
else:
return "πŸ”΄ Low", "Low confidence - prediction may be unreliable."
def predict_single_model(image, model, model_name):
"""Run prediction with a single model."""
if image is None:
return {}, f"No image provided"
try:
# Preprocess
img_tensor = transform(image).unsqueeze(0)
# Inference
with torch.no_grad():
outputs = model(img_tensor)
probs = torch.softmax(outputs, dim=1)[0]
# Get top 5
top5_probs, top5_indices = torch.topk(probs, 5)
# Results dict for gr.Label
results = {
class_names[idx.item()]: float(prob)
for prob, idx in zip(top5_probs, top5_indices)
}
# Top prediction details
top_prob = float(top5_probs[0])
top_class = class_names[top5_indices[0].item()]
level, msg = get_confidence_level(top_prob)
details = f"""**{model_name}**
**Prediction:** {top_class}
**Confidence:** {top_prob*100:.1f}%
**Level:** {level}
{msg}"""
return results, details
except Exception as e:
return {"Error": 1.0}, f"Error: {str(e)}"
def predict_comparison(image):
"""
Run prediction with BOTH models for comparison.
This is the key function for demonstrating the difference between
SimpleCNN (underfitting) and ResNet18 (transfer learning).
"""
if image is None:
empty = {"Please upload an image": 1.0}
return empty, "Upload an image to compare models", empty, "Upload an image to compare models", ""
# Run both models
simple_results, simple_details = predict_single_model(image, simplecnn_model, "SimpleCNN")
resnet_results, resnet_details = predict_single_model(image, resnet18_model, "ResNet18")
# Comparison summary
simple_top = list(simple_results.keys())[0] if simple_results else "N/A"
simple_conf = list(simple_results.values())[0] * 100 if simple_results else 0
resnet_top = list(resnet_results.keys())[0] if resnet_results else "N/A"
resnet_conf = list(resnet_results.values())[0] * 100 if resnet_results else 0
comparison = f"""## πŸ“Š Model Comparison
| Metric | SimpleCNN | ResNet18 |
|--------|-----------|----------|
| **Top Prediction** | {simple_top[:20]}{'...' if len(simple_top) > 20 else ''} | {resnet_top[:20]}{'...' if len(resnet_top) > 20 else ''} |
| **Confidence** | {simple_conf:.1f}% | {resnet_conf:.1f}% |
| **Architecture** | 3 conv layers | 18 layers + skip connections |
| **Training** | From scratch | Transfer learning |
| **Expected Accuracy** | ~4% | ~71% |
### Why the Difference?
**SimpleCNN** has insufficient capacity (only 3 layers) to learn the complex features
needed for fine-grained bird classification. It shows **underfitting**.
**ResNet18** benefits from:
1. **Transfer learning** - pretrained on 1.2M ImageNet images
2. **Deeper architecture** - 18 layers can capture complex patterns
3. **Skip connections** - enable training without vanishing gradients
"""
return simple_results, simple_details, resnet_results, resnet_details, comparison
# =============================================================================
# GRADIO INTERFACE
# =============================================================================
with gr.Blocks(title="Bird Classifier - Model Comparison") as demo:
gr.Markdown("""
# 🐦 Bird Species Classifier - Model Comparison
Compare **SimpleCNN** (baseline) vs **ResNet18** (transfer learning) on bird classification.
This demonstrates why **transfer learning** dramatically outperforms training from scratch!
| Model | Layers | Training | Validation Accuracy |
|-------|--------|----------|---------------------|
| SimpleCNN | 3 | From scratch | **4.1%** (underfitting) |
| ResNet18 | 18 | Transfer learning | **70.9%** |
""")
with gr.Row():
# Input column
with gr.Column(scale=1):
input_image = gr.Image(type="pil", label="Upload Bird Image")
compare_btn = gr.Button("πŸ” Compare Both Models", variant="primary")
clear_btn = gr.Button("πŸ—‘οΈ Clear")
gr.Markdown("---")
gr.Markdown("## Results")
with gr.Row():
# SimpleCNN results
with gr.Column(scale=1):
gr.Markdown("### πŸ”΄ SimpleCNN (Baseline)")
simple_label = gr.Label(num_top_classes=5, label="SimpleCNN Predictions")
simple_details = gr.Markdown()
# ResNet18 results
with gr.Column(scale=1):
gr.Markdown("### 🟒 ResNet18 (Transfer Learning)")
resnet_label = gr.Label(num_top_classes=5, label="ResNet18 Predictions")
resnet_details = gr.Markdown()
gr.Markdown("---")
# Comparison summary
comparison_md = gr.Markdown()
# Model info accordion
with gr.Accordion("ℹ️ Understanding the Models", open=False):
gr.Markdown("""
## SimpleCNN - Why It Fails
```
Architecture:
Input (224Γ—224Γ—3)
β†’ Conv(32) β†’ BatchNorm β†’ ReLU β†’ MaxPool [Layer 1]
β†’ Conv(64) β†’ BatchNorm β†’ ReLU β†’ MaxPool [Layer 2]
β†’ Conv(128) β†’ BatchNorm β†’ ReLU β†’ MaxPool [Layer 3]
β†’ Global Average Pooling
β†’ FC(128β†’256) β†’ FC(256β†’200)
β†’ Output (200 classes)
Problem: Only 3 convolutional layers!
- Cannot learn complex bird features
- Demonstrates UNDERFITTING
- Training accuracy: 3.1% (can't even memorize training data)
```
## ResNet18 - Why It Succeeds
```
Architecture:
Input (224Γ—224Γ—3)
β†’ Initial Conv β†’ BatchNorm β†’ MaxPool
β†’ Residual Block 1 (Γ—2) with skip connections
β†’ Residual Block 2 (Γ—2) with skip connections
β†’ Residual Block 3 (Γ—2) with skip connections
β†’ Residual Block 4 (Γ—2) with skip connections
β†’ Global Average Pooling
β†’ FC(512β†’200)
β†’ Output (200 classes)
Advantages:
1. 18 layers of feature extraction
2. Skip connections prevent vanishing gradients
3. Pretrained on ImageNet (1.2M images)
4. Two-phase training: freeze backbone β†’ fine-tune all
```
## Key Insight
With only ~4,800 training images for 200 classes, we don't have enough data
to train a CNN from scratch. Transfer learning solves this by starting with
features already learned from millions of images.
""")
# Event handlers
compare_btn.click(
fn=predict_comparison,
inputs=input_image,
outputs=[simple_label, simple_details, resnet_label, resnet_details, comparison_md]
)
input_image.change(
fn=predict_comparison,
inputs=input_image,
outputs=[simple_label, simple_details, resnet_label, resnet_details, comparison_md]
)
clear_btn.click(
fn=lambda: (None, None, "", None, "", ""),
inputs=[],
outputs=[input_image, simple_label, simple_details, resnet_label, resnet_details, comparison_md]
)
gr.Markdown("""
---
**COS30082 Applied Machine Learning** | Kimberly George (102781022)
Built with PyTorch and Gradio | [Model Comparison Demo]
""")
# =============================================================================
# LAUNCH
# =============================================================================
if __name__ == "__main__":
demo.launch()