File size: 14,531 Bytes
a501b8b f1fa739 a501b8b f1fa739 a501b8b 89cdf7f a501b8b 89cdf7f a501b8b 89cdf7f a501b8b 89cdf7f a501b8b 89cdf7f a501b8b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 | # =============================================================================
# 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() |