Upload 5 files
Browse files- .gitattributes +2 -0
- app.py +436 -0
- cifar10_index.faiss +3 -0
- metadata.json +0 -0
- simclr_encoder_exp41.onnx +3 -0
- simclr_encoder_exp41.onnx.data +3 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
cifar10_index.faiss filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
simclr_encoder_exp41.onnx.data filter=lfs diff=lfs merge=lfs -text
|
app.py
ADDED
|
@@ -0,0 +1,436 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
================================================================================
|
| 3 |
+
SimCLR ResNet-50 Visual Search Engine GUI
|
| 4 |
+
-----------------------------------------
|
| 5 |
+
A premium, interactive web-based graphical user interface (GUI) built with
|
| 6 |
+
Streamlit, powered by ONNX Runtime and FAISS for real-time visual similarity
|
| 7 |
+
retrieval on CIFAR-10.
|
| 8 |
+
|
| 9 |
+
Key Features:
|
| 10 |
+
1. Premium Dark Mode UI with tailored CSS glassmorphism styling
|
| 11 |
+
2. Upload any local image or select a random test image from CIFAR-10
|
| 12 |
+
3. Lightning-fast feature extraction (2048-d) via optimized ONNX Runtime
|
| 13 |
+
4. Sub-millisecond exact Cosine Similarity search using FAISS vector database
|
| 14 |
+
5. Clean visual results grid with similarity scores and class matches
|
| 15 |
+
6. Dedicated interactive "Ablation Study Dashboard" showing the Exp 38-42 findings
|
| 16 |
+
|
| 17 |
+
Usage:
|
| 18 |
+
streamlit run app.py
|
| 19 |
+
================================================================================
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
import os
|
| 23 |
+
import sys
|
| 24 |
+
import time
|
| 25 |
+
import json
|
| 26 |
+
import random
|
| 27 |
+
import numpy as np
|
| 28 |
+
from PIL import Image
|
| 29 |
+
|
| 30 |
+
import streamlit as st
|
| 31 |
+
|
| 32 |
+
# Windows console encoding fix
|
| 33 |
+
sys.stdout.reconfigure(encoding='utf-8')
|
| 34 |
+
sys.stderr.reconfigure(encoding='utf-8')
|
| 35 |
+
|
| 36 |
+
# Ensure we can import from src/
|
| 37 |
+
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
| 38 |
+
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "src"))
|
| 39 |
+
|
| 40 |
+
# ==========================================================================
|
| 41 |
+
# Caching Assets for Instant Performance
|
| 42 |
+
# ==========================================================================
|
| 43 |
+
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 44 |
+
DEPLOY_DIR = os.path.join(BASE_DIR, "deployment")
|
| 45 |
+
ONNX_PATH = os.path.join(DEPLOY_DIR, "simclr_encoder_exp41.onnx")
|
| 46 |
+
INDEX_PATH = os.path.join(DEPLOY_DIR, "cifar10_index.faiss")
|
| 47 |
+
META_PATH = os.path.join(DEPLOY_DIR, "metadata.json")
|
| 48 |
+
|
| 49 |
+
CIFAR_MEAN = np.array([0.4914, 0.4822, 0.4465], dtype=np.float32)
|
| 50 |
+
CIFAR_STD = np.array([0.2023, 0.1994, 0.2010], dtype=np.float32)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@st.cache_resource
|
| 54 |
+
def load_onnx_model():
|
| 55 |
+
"""Load ONNX inference session and cache it."""
|
| 56 |
+
import onnxruntime as ort
|
| 57 |
+
# CPU is fast enough for single image inference, ensures compatibility
|
| 58 |
+
providers = ['CPUExecutionProvider']
|
| 59 |
+
return ort.InferenceSession(ONNX_PATH, providers=providers)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@st.cache_resource
|
| 63 |
+
def load_faiss_index():
|
| 64 |
+
"""Load FAISS index and cache it."""
|
| 65 |
+
import faiss
|
| 66 |
+
return faiss.read_index(INDEX_PATH)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@st.cache_data
|
| 70 |
+
def load_metadata():
|
| 71 |
+
"""Load metadata dictionary and cache it."""
|
| 72 |
+
with open(META_PATH, "r", encoding="utf-8") as f:
|
| 73 |
+
return json.load(f)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
# -- Check that deployment files exist ---------------------------------------
|
| 77 |
+
missing_files = []
|
| 78 |
+
for p, name in [(ONNX_PATH, "ONNX Model"), (INDEX_PATH, "FAISS Index"), (META_PATH, "Metadata JSON")]:
|
| 79 |
+
if not os.path.exists(p):
|
| 80 |
+
missing_files.append(name)
|
| 81 |
+
|
| 82 |
+
if missing_files:
|
| 83 |
+
st.error(f"β Missing deployment assets: {', '.join(missing_files)}")
|
| 84 |
+
st.warning("π Please run `export_onnx.py` then `build_faiss.py` to generate these files before running the GUI!")
|
| 85 |
+
st.stop()
|
| 86 |
+
|
| 87 |
+
# Load cached assets
|
| 88 |
+
ort_sess = load_onnx_model()
|
| 89 |
+
faiss_index = load_faiss_index()
|
| 90 |
+
metadata = load_metadata()
|
| 91 |
+
|
| 92 |
+
# ==========================================================================
|
| 93 |
+
# Preprocessing Logic
|
| 94 |
+
# ==========================================================================
|
| 95 |
+
def preprocess_image(pil_img):
|
| 96 |
+
"""
|
| 97 |
+
Resizes image to 32x32 and applies CIFAR-10 mean/std normalization.
|
| 98 |
+
Returns: numpy array of shape (1, 3, 32, 32)
|
| 99 |
+
"""
|
| 100 |
+
# 1. Resize to 32x32
|
| 101 |
+
img_resized = pil_img.resize((32, 32), Image.Resampling.BILINEAR)
|
| 102 |
+
|
| 103 |
+
# 2. Convert to numpy array and scale to [0, 1]
|
| 104 |
+
img_np = np.array(img_resized, dtype=np.float32) / 255.0
|
| 105 |
+
|
| 106 |
+
# Handle grayscale images if uploaded
|
| 107 |
+
if len(img_np.shape) == 2:
|
| 108 |
+
img_np = np.stack([img_np, img_np, img_np], axis=-1)
|
| 109 |
+
elif img_np.shape[2] == 4:
|
| 110 |
+
img_np = img_np[:, :, :3] # Drop alpha channel
|
| 111 |
+
|
| 112 |
+
# 3. Normalize: (x - mean) / std
|
| 113 |
+
img_normalized = (img_np - CIFAR_MEAN) / CIFAR_STD
|
| 114 |
+
|
| 115 |
+
# 4. Transpose to channel-first (HWC -> CHW) and add batch dimension (1, C, H, W)
|
| 116 |
+
img_transposed = np.transpose(img_normalized, (2, 0, 1))
|
| 117 |
+
img_batch = np.expand_dims(img_transposed, axis=0)
|
| 118 |
+
|
| 119 |
+
return img_batch
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def perform_search(features_batch, top_k=5):
|
| 123 |
+
"""
|
| 124 |
+
Normalizes features, queries FAISS, and returns matched metadata.
|
| 125 |
+
"""
|
| 126 |
+
# 1. L2-Normalize vector
|
| 127 |
+
norm = np.linalg.norm(features_batch, axis=1, keepdims=True)
|
| 128 |
+
features_normalized = features_batch / np.maximum(norm, 1e-12)
|
| 129 |
+
|
| 130 |
+
# 2. Search FAISS Index
|
| 131 |
+
similarities, indices = faiss_index.search(features_normalized, top_k)
|
| 132 |
+
|
| 133 |
+
results = []
|
| 134 |
+
for rank in range(top_k):
|
| 135 |
+
vector_id = int(indices[0][rank])
|
| 136 |
+
score = float(similarities[0][rank])
|
| 137 |
+
|
| 138 |
+
# Load from metadata catalog
|
| 139 |
+
match_info = metadata["images"][vector_id]
|
| 140 |
+
|
| 141 |
+
results.append({
|
| 142 |
+
"rank": rank + 1,
|
| 143 |
+
"id": vector_id,
|
| 144 |
+
"similarity": score,
|
| 145 |
+
"image_path": os.path.join(DEPLOY_DIR, match_info["image_path"]),
|
| 146 |
+
"class_name": match_info["class_name"],
|
| 147 |
+
"label_id": match_info["label_id"]
|
| 148 |
+
})
|
| 149 |
+
|
| 150 |
+
return results
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
# ==========================================================================
|
| 154 |
+
# Streamlit UI Configuration
|
| 155 |
+
# ==========================================================================
|
| 156 |
+
st.set_page_config(
|
| 157 |
+
page_title="SimCLR ResNet-50 Visual Search",
|
| 158 |
+
page_icon="π",
|
| 159 |
+
layout="wide",
|
| 160 |
+
initial_sidebar_state="expanded"
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
# Custom CSS for Premium Styling
|
| 164 |
+
st.markdown("""
|
| 165 |
+
<style>
|
| 166 |
+
/* Dark theme customizations */
|
| 167 |
+
.stApp {
|
| 168 |
+
background-color: #0F172A;
|
| 169 |
+
color: #E2E8F0;
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
/* Title and Header designs */
|
| 173 |
+
h1 {
|
| 174 |
+
background: linear-gradient(90deg, #38BDF8, #818CF8);
|
| 175 |
+
-webkit-background-clip: text;
|
| 176 |
+
-webkit-text-fill-color: transparent;
|
| 177 |
+
font-family: 'Outfit', sans-serif;
|
| 178 |
+
font-weight: 800;
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
/* Custom Card/Glassmorphism block */
|
| 182 |
+
.glass-card {
|
| 183 |
+
background: rgba(30, 41, 59, 0.7);
|
| 184 |
+
border: 1px solid rgba(255, 255, 255, 0.05);
|
| 185 |
+
border-radius: 12px;
|
| 186 |
+
padding: 20px;
|
| 187 |
+
margin-bottom: 20px;
|
| 188 |
+
box-shadow: 0 4px 30px rgba(0, 0, 0, 0.2);
|
| 189 |
+
backdrop-filter: blur(5px);
|
| 190 |
+
}
|
| 191 |
+
|
| 192 |
+
/* Metric styling */
|
| 193 |
+
.metric-value {
|
| 194 |
+
font-size: 2.2rem;
|
| 195 |
+
font-weight: 700;
|
| 196 |
+
color: #38BDF8;
|
| 197 |
+
}
|
| 198 |
+
.metric-label {
|
| 199 |
+
font-size: 0.9rem;
|
| 200 |
+
color: #94A3B8;
|
| 201 |
+
text-transform: uppercase;
|
| 202 |
+
letter-spacing: 0.05em;
|
| 203 |
+
}
|
| 204 |
+
</style>
|
| 205 |
+
""", unsafe_allow_html=True)
|
| 206 |
+
|
| 207 |
+
# ==========================================================================
|
| 208 |
+
# Sidebar Configuration
|
| 209 |
+
# ==========================================================================
|
| 210 |
+
st.sidebar.markdown("### βοΈ Engine Settings")
|
| 211 |
+
top_k_slider = st.sidebar.slider("Number of results (K)", min_value=3, max_value=20, value=6, step=1)
|
| 212 |
+
|
| 213 |
+
st.sidebar.markdown("---")
|
| 214 |
+
st.sidebar.markdown("### π Trained Backbone Model")
|
| 215 |
+
st.sidebar.markdown("""
|
| 216 |
+
* **Architecture**: ResNet-50 (CIFAR STEM adjusted)
|
| 217 |
+
* **Training Type**: Self-Supervised (SimCLR)
|
| 218 |
+
* **Best Experiment**: **Exp 41**
|
| 219 |
+
* **Augmentations**: Crop + Flip + Blur + Color Jitter
|
| 220 |
+
* **Midterm Baseline**: 64.49%
|
| 221 |
+
* **Final Linear Probe Accuracy**: **84.30%** (+19.81% Gain!)
|
| 222 |
+
* **Embedding Dimension**: 2048
|
| 223 |
+
""")
|
| 224 |
+
|
| 225 |
+
st.sidebar.markdown("---")
|
| 226 |
+
st.sidebar.markdown("### β‘ Backend Pipeline")
|
| 227 |
+
st.sidebar.markdown("""
|
| 228 |
+
* **Inference Engine**: ONNX Runtime CPU
|
| 229 |
+
* **Vector Database**: FAISS (IndexFlatIP)
|
| 230 |
+
* **Similarity Metric**: Exact Cosine Similarity
|
| 231 |
+
* **Database Size**: 10,000 Images
|
| 232 |
+
""")
|
| 233 |
+
|
| 234 |
+
st.sidebar.caption("Group 20, CISC 867, Queen's University, Spring 2026")
|
| 235 |
+
|
| 236 |
+
# ==========================================================================
|
| 237 |
+
# Main Title
|
| 238 |
+
# ==========================================================================
|
| 239 |
+
st.title("π Real-time SimCLR Image Retrieval Engine")
|
| 240 |
+
st.markdown("##### Self-Supervised Representation Learning with ResNet-50 & FAISS Indexing")
|
| 241 |
+
|
| 242 |
+
# Define Tabs
|
| 243 |
+
tab1, tab2 = st.tabs(["π Real-Time Search", "π Ablation Study Dashboard"])
|
| 244 |
+
|
| 245 |
+
# ==========================================================================
|
| 246 |
+
# TAB 1: Visual Search Engine
|
| 247 |
+
# ==========================================================================
|
| 248 |
+
with tab1:
|
| 249 |
+
col_left, col_right = st.columns([1, 2], gap="large")
|
| 250 |
+
|
| 251 |
+
# Initialize session state for random query image selection
|
| 252 |
+
if "random_img_id" not in st.session_state:
|
| 253 |
+
st.session_state.random_img_id = None
|
| 254 |
+
|
| 255 |
+
query_image = None
|
| 256 |
+
query_info = None
|
| 257 |
+
|
| 258 |
+
with col_left:
|
| 259 |
+
st.markdown("### π₯ Select Query Image")
|
| 260 |
+
|
| 261 |
+
# Method 1: Upload a file
|
| 262 |
+
uploaded_file = st.file_uploader("Upload an image...", type=["jpg", "png", "jpeg"])
|
| 263 |
+
|
| 264 |
+
# Method 2: Pick a random image from the database
|
| 265 |
+
st.markdown("<p style='text-align: center; color: #94A3B8; margin: 10px 0;'>β OR β</p>", unsafe_allow_html=True)
|
| 266 |
+
if st.button("π² Pick a Random Test Image from Database", use_container_width=True):
|
| 267 |
+
st.session_state.random_img_id = random.randint(0, len(metadata["images"]) - 1)
|
| 268 |
+
|
| 269 |
+
# Display selected/uploaded image
|
| 270 |
+
if uploaded_file is not None:
|
| 271 |
+
st.session_state.random_img_id = None # Clear random image
|
| 272 |
+
query_image = Image.open(uploaded_file).convert("RGB")
|
| 273 |
+
st.image(query_image, caption="Uploaded Query Image", use_container_width=True)
|
| 274 |
+
|
| 275 |
+
elif st.session_state.random_img_id is not None:
|
| 276 |
+
idx = st.session_state.random_img_id
|
| 277 |
+
img_info = metadata["images"][idx]
|
| 278 |
+
local_path = os.path.join(DEPLOY_DIR, img_info["image_path"])
|
| 279 |
+
|
| 280 |
+
if os.path.exists(local_path):
|
| 281 |
+
query_image = Image.open(local_path).convert("RGB")
|
| 282 |
+
query_info = img_info
|
| 283 |
+
st.image(
|
| 284 |
+
query_image,
|
| 285 |
+
caption=f"Selected Reference Image #{idx} (Class: {img_info['class_name']})",
|
| 286 |
+
use_container_width=True
|
| 287 |
+
)
|
| 288 |
+
else:
|
| 289 |
+
st.error("Reference image file not found.")
|
| 290 |
+
|
| 291 |
+
with col_right:
|
| 292 |
+
st.markdown("### π― Visual Similarity Search Results")
|
| 293 |
+
|
| 294 |
+
if query_image is not None:
|
| 295 |
+
t_start = time.time()
|
| 296 |
+
|
| 297 |
+
# 1. Preprocess
|
| 298 |
+
batch_img = preprocess_image(query_image)
|
| 299 |
+
|
| 300 |
+
# 2. ONNX Inference
|
| 301 |
+
onnx_outputs = ort_sess.run(None, {"images": batch_img})
|
| 302 |
+
feature_vector = onnx_outputs[0] # (1, 2048)
|
| 303 |
+
|
| 304 |
+
# 3. FAISS Query
|
| 305 |
+
t_search_start = time.time()
|
| 306 |
+
results = perform_search(feature_vector, top_k=top_k_slider)
|
| 307 |
+
|
| 308 |
+
t_total_ms = (time.time() - t_start) * 1000
|
| 309 |
+
t_search_ms = (time.time() - t_search_start) * 1000
|
| 310 |
+
|
| 311 |
+
# Show Metrics
|
| 312 |
+
m_col1, m_col2, m_col3 = st.columns(3)
|
| 313 |
+
with m_col1:
|
| 314 |
+
st.markdown(f'<div class="glass-card"><div class="metric-value">{t_search_ms:.2f} ms</div><div class="metric-label">FAISS Query Time</div></div>', unsafe_allow_html=True)
|
| 315 |
+
with m_col2:
|
| 316 |
+
st.markdown(f'<div class="glass-card"><div class="metric-value">{t_total_ms:.1f} ms</div><div class="metric-label">Total Pipeline Latency</div></div>', unsafe_allow_html=True)
|
| 317 |
+
with m_col3:
|
| 318 |
+
# Calculate class precision
|
| 319 |
+
if query_info is not None:
|
| 320 |
+
matches = sum(1 for r in results if r["class_name"] == query_info["class_name"])
|
| 321 |
+
precision = (matches / len(results)) * 100
|
| 322 |
+
st.markdown(f'<div class="glass-card"><div class="metric-value">{precision:.1f}%</div><div class="metric-label">Top-{len(results)} Class Precision</div></div>', unsafe_allow_html=True)
|
| 323 |
+
else:
|
| 324 |
+
st.markdown(f'<div class="glass-card"><div class="metric-value">N/A</div><div class="metric-label">Upload class unknown</div></div>', unsafe_allow_html=True)
|
| 325 |
+
|
| 326 |
+
# Display Results Grid
|
| 327 |
+
st.markdown("#### Retreived Nearest Neighbors")
|
| 328 |
+
|
| 329 |
+
# Create dynamic grid columns
|
| 330 |
+
grid_cols = st.columns(3)
|
| 331 |
+
|
| 332 |
+
for idx, res in enumerate(results):
|
| 333 |
+
col = grid_cols[idx % 3]
|
| 334 |
+
|
| 335 |
+
with col:
|
| 336 |
+
# Determine styling color based on class match if query info exists
|
| 337 |
+
is_match = False
|
| 338 |
+
border_color = "rgba(255, 255, 255, 0.05)"
|
| 339 |
+
bg_color = "rgba(30, 41, 59, 0.7)"
|
| 340 |
+
badge_html = f'<span style="background-color: #475569; padding: 2px 8px; border-radius: 4px; font-size: 0.8rem; font-weight: 600; color: white;">{res["class_name"]}</span>'
|
| 341 |
+
|
| 342 |
+
if query_info is not None:
|
| 343 |
+
is_match = (res["class_name"] == query_info["class_name"])
|
| 344 |
+
if is_match:
|
| 345 |
+
border_color = "rgba(16, 185, 129, 0.3)"
|
| 346 |
+
bg_color = "rgba(6, 78, 59, 0.3)"
|
| 347 |
+
badge_html = f'<span style="background-color: #10B981; padding: 2px 8px; border-radius: 4px; font-size: 0.8rem; font-weight: 600; color: white;">{res["class_name"]} (MATCH)</span>'
|
| 348 |
+
else:
|
| 349 |
+
border_color = "rgba(239, 68, 68, 0.2)"
|
| 350 |
+
bg_color = "rgba(127, 29, 29, 0.1)"
|
| 351 |
+
badge_html = f'<span style="background-color: #EF4444; padding: 2px 8px; border-radius: 4px; font-size: 0.8rem; font-weight: 600; color: white;">{res["class_name"]}</span>'
|
| 352 |
+
|
| 353 |
+
# Custom card container
|
| 354 |
+
card_content = f"""
|
| 355 |
+
<div style="background: {bg_color}; border: 1px solid {border_color}; border-radius: 8px; padding: 12px; margin-bottom: 12px; text-align: center;">
|
| 356 |
+
<div style="color: #38BDF8; font-size: 1.1rem; font-weight: 700; margin-bottom: 8px;">Rank #{res["rank"]}</div>
|
| 357 |
+
<div style="margin-bottom: 10px;">{badge_html}</div>
|
| 358 |
+
<div style="color: #94A3B8; font-size: 0.9rem; margin-bottom: 4px;">Cosine Similarity:</div>
|
| 359 |
+
<div style="color: #E2E8F0; font-size: 1.4rem; font-weight: 700; margin-bottom: 10px;">{res["similarity"] * 100:.2f}%</div>
|
| 360 |
+
<div style="color: #64748B; font-size: 0.8rem;">Vector ID: {res["id"]}</div>
|
| 361 |
+
</div>
|
| 362 |
+
"""
|
| 363 |
+
|
| 364 |
+
# Render matched image and custom card
|
| 365 |
+
if os.path.exists(res["image_path"]):
|
| 366 |
+
matched_img = Image.open(res["image_path"])
|
| 367 |
+
col.image(matched_img, use_container_width=True)
|
| 368 |
+
else:
|
| 369 |
+
col.error("Image file missing.")
|
| 370 |
+
|
| 371 |
+
col.markdown(card_content, unsafe_allow_html=True)
|
| 372 |
+
|
| 373 |
+
else:
|
| 374 |
+
st.info("π‘ Please upload a custom image or click the button to select a random test image to query the visual search engine!")
|
| 375 |
+
|
| 376 |
+
# ==========================================================================
|
| 377 |
+
# TAB 2: Ablation Study Dashboard
|
| 378 |
+
# ==========================================================================
|
| 379 |
+
with tab2:
|
| 380 |
+
st.markdown("### π Experiment Ablation Study & Color Jitter Findings")
|
| 381 |
+
st.markdown("##### Evaluating Natalie's Midterm Pipelines against Mahmoud's Final Jittered Re-runs")
|
| 382 |
+
|
| 383 |
+
st.markdown("""
|
| 384 |
+
This section presents the results of the complete **Color Jitter Shortcut-Learning Ablation Study** (Experiments 38-42).
|
| 385 |
+
By comparing the self-supervised representations learned with and without photometric distortion (Color Jitter), we demonstrate how SimCLR ResNet-50 encoders learn rich semantic representations instead of exploiting simple pixel-level color shortcuts.
|
| 386 |
+
""")
|
| 387 |
+
|
| 388 |
+
# 3x2 Grid for Ablation Statistics
|
| 389 |
+
ablation_data = [
|
| 390 |
+
{"exp": "Exp 38 vs 36", "desc": "Pure Discrete Rotation", "base": "34.40%", "jitter": "51.21%", "gain": "+16.81 pp"},
|
| 391 |
+
{"exp": "Exp 39 vs 35", "desc": "Weak Spatial Baseline", "base": "59.22%", "jitter": "80.53%", "gain": "+21.31 pp"},
|
| 392 |
+
{"exp": "Exp 40 vs 9", "desc": "Crop + Gaussian Blur", "base": "63.01%", "jitter": "80.65%", "gain": "+17.64 pp"},
|
| 393 |
+
{"exp": "Exp 41 vs 13", "desc": "Crop + Flip + Blur", "base": "64.49%", "jitter": "84.30%", "gain": "+19.81 pp"},
|
| 394 |
+
{"exp": "Exp 42 vs 10", "desc": "Crop + Random Cutout", "base": "66.27%", "jitter": "81.21%", "gain": "+14.94 pp"}
|
| 395 |
+
]
|
| 396 |
+
|
| 397 |
+
cols_ablation = st.columns(5)
|
| 398 |
+
for i, data in enumerate(ablation_data):
|
| 399 |
+
with cols_ablation[i]:
|
| 400 |
+
card_html = f"""
|
| 401 |
+
<div style="background: rgba(30, 41, 59, 0.5); border: 1px solid rgba(56, 189, 248, 0.2); border-radius: 8px; padding: 15px; text-align: center;">
|
| 402 |
+
<div style="color: #38BDF8; font-size: 1.1rem; font-weight: 700;">{data["exp"]}</div>
|
| 403 |
+
<div style="color: #94A3B8; font-size: 0.85rem; height: 35px; overflow: hidden; margin-top: 4px;">{data["desc"]}</div>
|
| 404 |
+
<hr style="border: 0; border-top: 1px solid rgba(255,255,255,0.05); margin: 8px 0;"/>
|
| 405 |
+
<div style="color: #94A3B8; font-size: 0.8rem;">Without Jitter: <b>{data["base"]}</b></div>
|
| 406 |
+
<div style="color: #10B981; font-size: 0.85rem; font-weight: 600; margin-top: 2px;">With Jitter: {data["jitter"]}</div>
|
| 407 |
+
<div style="background-color: rgba(16, 185, 129, 0.15); color: #10B981; border-radius: 4px; padding: 2px 6px; font-size: 0.9rem; font-weight: 700; margin-top: 8px; display: inline-block;">
|
| 408 |
+
{data["gain"]} Gain
|
| 409 |
+
</div>
|
| 410 |
+
</div>
|
| 411 |
+
"""
|
| 412 |
+
st.markdown(card_html, unsafe_allow_html=True)
|
| 413 |
+
|
| 414 |
+
st.markdown("---")
|
| 415 |
+
st.markdown("#### π Key Project Takeaways")
|
| 416 |
+
col1, col2 = st.columns(2)
|
| 417 |
+
|
| 418 |
+
with col1:
|
| 419 |
+
st.markdown("""
|
| 420 |
+
##### 1. The Shortcut-Learning Problem π§©
|
| 421 |
+
Without Color Jitter, contrastive self-supervised encoders exploit low-level **color histograms** as a shortcut to maximize mutual information, rather than learning general shapes and semantic features. This results in weaker downstream representations, showing a severe performance limit (e.g. baseline Crop+Flip+Blur achieves only **64.49%**).
|
| 422 |
+
|
| 423 |
+
##### 2. The Color Jitter Shield π‘οΈ
|
| 424 |
+
Adding photometric distortion (color jittering) forces the model to ignore color profiles and focus on invariant structures, spatial boundaries, and contours. This single ablation yields a massive average boost of **+18.1 pp** across all settings, pushing our best encoder (Exp 41) to a stellar **84.30% Top-1 accuracy**!
|
| 425 |
+
""")
|
| 426 |
+
|
| 427 |
+
with col2:
|
| 428 |
+
st.markdown("""
|
| 429 |
+
##### 3. Model Architecture & Stem Tuning βοΈ
|
| 430 |
+
Modifying the standard ResNet-50 conv1 stem from $7\\times7$ (stride 2) to a custom $3\\times3$ (stride 1) and removing the initial MaxPool was crucial to preserve the resolution of $32\\times32$ CIFAR-10 images.
|
| 431 |
+
|
| 432 |
+
##### 4. Near Foundation-Model Upper Bound π
|
| 433 |
+
Our zero-shot CLIP ViT-B/32 foundation model evaluation sets the academic upper bound at **88.80%**. Our custom-trained SimCLR ResNet-50 achieves **95% of this performance** (**84.30%**) while using **8,000x less training data**!
|
| 434 |
+
""")
|
| 435 |
+
|
| 436 |
+
st.success("π Weights & Biases Dashboard has archived all 5 experiments complete with training curves, checkpoints, and t-SNE files.")
|
cifar10_index.faiss
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0339ffc050dd1d5fd951905baecabebeb30969e1e005fc35c21857bed4319097
|
| 3 |
+
size 81920045
|
metadata.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
simclr_encoder_exp41.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:87aa945812518880fb1853205a857f0087010f46829eab05442ce0f5a9b2c9b6
|
| 3 |
+
size 93924524
|
simclr_encoder_exp41.onnx.data
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4ff387f194ffa540559b80cc0a9a23babd3fef4068af49e311b8f476450efab7
|
| 3 |
+
size 93913088
|