diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c0c7417f7f6d7a82b9677e9d12662954f5856edf --- /dev/null +++ b/Dockerfile @@ -0,0 +1,24 @@ +FROM python:3.11-slim + +WORKDIR /app + +# System deps +RUN apt-get update && apt-get install -y --no-install-recommends \ + build-essential libgl1 libglib2.0-0 curl \ + && rm -rf /var/lib/apt/lists/* + +# Python deps +COPY backend/requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +# App code +COPY backend/ ./backend/ +COPY ml_pipeline/ ./ml_pipeline/ +COPY checkpoints/ ./checkpoints/ + +ENV PYTHONPATH=/app + +# Hugging Face Spaces uses port 7860 +EXPOSE 7860 + +CMD ["uvicorn", "backend.app.main:app", "--host", "0.0.0.0", "--port", "7860"] diff --git a/README.md b/README.md index cca626d99f0ed5521fde4c1c38fdc230738e1d80..a8bd24f9ffcc434532e28eb8ed788655fa41f454 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,20 @@ --- -title: Plantguard Api -emoji: šŸ‘€ -colorFrom: indigo -colorTo: gray +title: PlantGuard API +emoji: 🌿 +colorFrom: green +colorTo: green sdk: docker pinned: false +app_port: 7860 --- -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference +# PlantGuard API + +AI-powered plant disease detection API using MobileNetV3 + Gemini AI. + +## Endpoints + +- `GET /health` - Health check +- `POST /api/predict` - Upload plant image for disease prediction +- `GET /api/classes` - List supported disease classes + diff --git a/backend/.env b/backend/.env new file mode 100644 index 0000000000000000000000000000000000000000..053ecfa3a98fc56414ef6bc7d871981a18acfd82 --- /dev/null +++ b/backend/.env @@ -0,0 +1,9 @@ +SUPABASE_URL=https://jilfujxzegrhnwxfvcop.supabase.co +SUPABASE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImppbGZ1anh6ZWdyaG53eGZ2Y29wIiwicm9sZSI6ImFub24iLCJpYXQiOjE3Njk4NzI2NjEsImV4cCI6MjA4NTQ0ODY2MX0.ZWl_o9mLA5Njf0lAhYpMEWttiowdtWAJ7DmUcxFhMak +SUPABASE_SERVICE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImppbGZ1anh6ZWdyaG53eGZ2Y29wIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTc2OTg3MjY2MSwiZXhwIjoyMDg1NDQ4NjYxfQ.nURb5tWEpm3gmdMiGv-bSMi-HfkeQdSuYM2mbCXvdKA +MODELS_DIR=checkpoints +ENSEMBLE_DIR=checkpoints/ensemble +FRONTEND_URL=http://localhost:5173 +GEMINI_API_KEY=AIzaSyDTiDDV23yBqZo161evyNZv6ZTZmVyLp-I +GEMINI_MODEL=gemini-2.5-flash +SARVAM_API_KEY=sk_qiu0ryv1_0F1KvdwR0RkSdUvynIOAKPwi diff --git a/backend/.env.example b/backend/.env.example new file mode 100644 index 0000000000000000000000000000000000000000..744a680614881a08f6768dbae8a64b74194f3929 --- /dev/null +++ b/backend/.env.example @@ -0,0 +1,18 @@ +# Supabase Configuration +SUPABASE_URL=https://your-project.supabase.co +SUPABASE_KEY=your-anon-key-here +SUPABASE_SERVICE_KEY=your-service-key-here + +# Gemini API (for AI cross-validation) +GEMINI_API_KEY=your-gemini-api-key-here +GEMINI_MODEL=gemini-2.5-flash + +# ML Model paths +MODELS_DIR=checkpoints +ENSEMBLE_DIR=checkpoints/ensemble + +# Frontend URL (for CORS) +FRONTEND_URL=http://localhost:5173 + +# Optional monitoring +SENTRY_DSN= diff --git a/backend/Dockerfile b/backend/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ed98ed206f1a2f1e016481c56faeadb9bee91128 --- /dev/null +++ b/backend/Dockerfile @@ -0,0 +1,26 @@ +FROM python:3.11-slim + +WORKDIR /app + +# System deps +RUN apt-get update && apt-get install -y --no-install-recommends \ + build-essential libgl1 libglib2.0-0 curl \ + && rm -rf /var/lib/apt/lists/* + +# Python deps +COPY backend/requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +# App code +COPY backend/ ./backend/ +COPY ml_pipeline/ ./ml_pipeline/ + +# Copy model checkpoints if available +COPY checkpoints/ ./checkpoints/ + +ENV PYTHONPATH=/app + +EXPOSE 8000 + +# Use Python to read PORT env var (guaranteed to work) +CMD ["python", "-c", "import os; import subprocess; port = os.environ.get('PORT', '8080'); subprocess.run(['uvicorn', 'backend.app.main:app', '--host', '0.0.0.0', '--port', port])"] diff --git a/backend/app/__init__.py b/backend/app/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/app/__pycache__/__init__.cpython-311.pyc b/backend/app/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a144ef694ec315684e2da2107f75332a5e7a32a Binary files /dev/null and b/backend/app/__pycache__/__init__.cpython-311.pyc differ diff --git a/backend/app/__pycache__/main.cpython-311.pyc b/backend/app/__pycache__/main.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..65c9c54591d2dd3a81add618019e53e6fbf60c45 Binary files /dev/null and b/backend/app/__pycache__/main.cpython-311.pyc differ diff --git a/backend/app/api/__init__.py b/backend/app/api/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/app/api/__pycache__/__init__.cpython-311.pyc b/backend/app/api/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd1d031ddaff251b255e97d678f2b3c712000cc6 Binary files /dev/null and b/backend/app/api/__pycache__/__init__.cpython-311.pyc differ diff --git a/backend/app/api/__pycache__/routes.cpython-311.pyc b/backend/app/api/__pycache__/routes.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12ea1cefd216411b063de283abbf9e2c29eb26f9 Binary files /dev/null and b/backend/app/api/__pycache__/routes.cpython-311.pyc differ diff --git a/backend/app/api/routes.py b/backend/app/api/routes.py new file mode 100644 index 0000000000000000000000000000000000000000..85e165fb28d803ad83d96bb7b58079a443468b48 --- /dev/null +++ b/backend/app/api/routes.py @@ -0,0 +1,319 @@ +"""API routes for prediction, auth, and history.""" +import io +import os +import time +from typing import Optional + +from fastapi import APIRouter, File, UploadFile, HTTPException, Header, Query, BackgroundTasks +from fastapi.responses import Response +from pydantic import BaseModel +from PIL import Image +import httpx +import base64 + +from backend.app.ml.predictor import get_predictor +from backend.app.ml.gemini_validator import get_validator +from backend.app.ml.finetuner import get_finetuner +from backend.app.models.schemas import ( + PredictionResponse, HealthResponse, GeminiValidation +) +from backend.app.services.supabase_service import supabase_service + +router = APIRouter() + +SARVAM_API_KEY = os.getenv("SARVAM_API_KEY", "") +SARVAM_TTS_URL = "https://api.sarvam.ai/text-to-speech" +SARVAM_TTS_SPEAKER = os.getenv("SARVAM_TTS_SPEAKER", "anushka") +SARVAM_TTS_MODEL = os.getenv("SARVAM_TTS_MODEL", "bulbul:v2") +# Max chars per TTS request (bulbul:v2=1500, v3=2500) +SARVAM_MAX_CHARS = 1500 + + +class TTSRequest(BaseModel): + text: str + language: str = "en" + pace: float = 1.0 + + +class FeedbackRequest(BaseModel): + predicted_class: str + actual_class: str + is_correct: bool + image_url: str = "" + prediction_id: Optional[str] = None + + +@router.get("/health", response_model=HealthResponse) +async def health_check(): + predictor = get_predictor() + validator = get_validator() + return HealthResponse( + status="healthy" if predictor._loaded else "models_not_loaded", + model_loaded=predictor._loaded, + gemini_available=validator.is_available, + device=str(predictor.device), + ) + + +@router.post("/predict", response_model=PredictionResponse) +async def predict_disease( + file: UploadFile = File(...), + top_k: int = Query(default=5, ge=1, le=38), + authorization: Optional[str] = Header(default=None), +): + """ + Predict plant disease from leaf image using MobileNetV3. + Includes Gemini AI cross-validation with visual analysis of the leaf image. + """ + if not file.content_type or not file.content_type.startswith("image/"): + raise HTTPException(400, "File must be an image (JPEG, PNG, etc.)") + + try: + contents = await file.read() + image = Image.open(io.BytesIO(contents)).convert("RGB") + except Exception: + raise HTTPException(400, "Invalid image file") + + predictor = get_predictor() + if not predictor._loaded: + raise HTTPException(503, "Model not loaded yet") + + start = time.time() + result = predictor.predict(image, top_k=top_k) + image_metadata = result.pop("image_metadata", {}) + latency_ms = (time.time() - start) * 1000 + print(f"MobileNet inference: {latency_ms:.0f}ms") + + # Run Gemini validation synchronously (multimodal: image + text) + gemini_validation = None + validator = get_validator() + if validator.is_available: + gemini_start = time.time() + validation_result = await validator.validate_async( + dict(result), dict(image_metadata), image_bytes=contents + ) + gemini_ms = (time.time() - gemini_start) * 1000 + print(f"Gemini validation: {gemini_ms:.0f}ms") + if validation_result: + gemini_validation = GeminiValidation(**validation_result) + + # Save to history if authenticated + image_url = None + if authorization and supabase_service.is_available: + token = authorization.replace("Bearer ", "") + user = supabase_service.verify_token(token) + if user: + image_url = supabase_service.upload_image( + contents, file.filename or "image.jpg", user["id"] + ) + supabase_service.save_prediction( + user["id"], result, image_url, + gemini_validation=gemini_validation.model_dump() if gemini_validation else None + ) + + return PredictionResponse( + **{"class": result["class"]}, + probability=result["probability"], + uncertainty=result["uncertainty"], + top_k=[{"class": p["class"], "probability": p["probability"]} for p in result["top_k"]], + gemini_validation=gemini_validation, + image_url=image_url, + ) + + +@router.post("/auth/signup") +async def signup(email: str, password: str): + result = supabase_service.sign_up(email, password) + if "error" in result: + raise HTTPException(400, result["error"]) + return result + + +@router.post("/auth/signin") +async def signin(email: str, password: str): + result = supabase_service.sign_in(email, password) + if "error" in result: + raise HTTPException(401, result["error"]) + return result + + +@router.get("/history") +async def get_history( + authorization: str = Header(...), + limit: int = Query(default=20, ge=1, le=100), +): + token = authorization.replace("Bearer ", "") + user = supabase_service.verify_token(token) + if not user: + raise HTTPException(401, "Invalid token") + history = supabase_service.get_history(user["id"], limit) + return {"predictions": history} + + +@router.get("/stats") +async def get_stats(authorization: str = Header(...)): + token = authorization.replace("Bearer ", "") + user = supabase_service.verify_token(token) + if not user: + raise HTTPException(401, "Invalid token") + stats = supabase_service.get_stats(user["id"]) + return stats + + +@router.get("/classes") +async def get_classes(): + """Return list of supported disease classes.""" + predictor = get_predictor() + return {"classes": predictor.class_names, "count": len(predictor.class_names)} + + +@router.post("/feedback") +async def submit_feedback( + request: FeedbackRequest, + authorization: Optional[str] = Header(default=None), +): + """Submit user feedback on a prediction (for model training).""" + user_id = None + if authorization: + token = authorization.replace("Bearer ", "") + user = supabase_service.verify_token(token) + if user: + user_id = user["id"] + + if not user_id: + user_id = "anonymous" + + result = supabase_service.save_feedback( + user_id=user_id, + prediction_id=request.prediction_id, + image_url=request.image_url, + predicted_class=request.predicted_class, + actual_class=request.actual_class, + is_correct=request.is_correct, + ) + if result.get("status") == "error": + raise HTTPException(500, result.get("error", "Failed to save feedback")) + return result + + +@router.get("/feedback/stats") +async def feedback_stats(): + """Get feedback statistics and model training status.""" + stats = supabase_service.get_feedback_stats() + finetuner = get_finetuner() + stats["is_training"] = finetuner.is_training + stats["last_training"] = finetuner.last_training + stats["can_retrain"] = stats["total"] >= 5 + return stats + + +@router.post("/admin/retrain") +async def retrain_model( + background_tasks: BackgroundTasks, + authorization: str = Header(...), +): + """Trigger model fine-tuning using accumulated feedback data.""" + token = authorization.replace("Bearer ", "") + user = supabase_service.verify_token(token) + if not user: + raise HTTPException(401, "Invalid token") + + finetuner = get_finetuner() + if finetuner.is_training: + raise HTTPException(409, "Training already in progress") + + feedback_data = supabase_service.get_feedback() + if len(feedback_data) < 5: + raise HTTPException(400, f"Need at least 5 feedback samples, got {len(feedback_data)}") + + predictor = get_predictor() + + def run_training(): + result = finetuner.finetune(predictor, feedback_data, supabase_service) + if result["status"] == "success": + predictor.model.eval() + print(f"Model fine-tuned: v{result['version']}, {result['samples_used']} samples, acc={result['final_accuracy']:.2%}") + + background_tasks.add_task(run_training) + return {"status": "training_started", "samples_queued": len(feedback_data)} + + +@router.get("/admin/retrain/status") +async def retrain_status(authorization: str = Header(...)): + """Check current training status.""" + token = authorization.replace("Bearer ", "") + user = supabase_service.verify_token(token) + if not user: + raise HTTPException(401, "Invalid token") + + finetuner = get_finetuner() + return { + "is_training": finetuner.is_training, + "last_training": finetuner.last_training, + "total_runs": len(finetuner.training_history), + } + + +# Language code mapping for Sarvam TTS +LANG_TO_SARVAM = { + "en": "en-IN", "hi": "hi-IN", "ta": "ta-IN", "te": "te-IN", + "bn": "bn-IN", "mr": "mr-IN", "kn": "kn-IN", "gu": "gu-IN", +} + + +@router.post("/tts") +async def text_to_speech(request: TTSRequest): + """Convert text to speech using Sarvam AI TTS (Indian language support).""" + if not SARVAM_API_KEY: + raise HTTPException(503, "TTS service not configured (SARVAM_API_KEY missing)") + + text = request.text.strip() + if not text: + raise HTTPException(400, "Text cannot be empty") + + target_lang = LANG_TO_SARVAM.get(request.language, "en-IN") + pace = max(0.5, min(2.0, request.pace)) + + # Truncate text to max chars (Sarvam limit) + if len(text) > SARVAM_MAX_CHARS: + text = text[:SARVAM_MAX_CHARS] + + payload = { + "text": text, + "target_language_code": target_lang, + "speaker": SARVAM_TTS_SPEAKER, + "model": SARVAM_TTS_MODEL, + "pace": pace, + "speech_sample_rate": 22050, + "enable_preprocessing": True, + } + + try: + async with httpx.AsyncClient(timeout=30.0) as client: + resp = await client.post( + SARVAM_TTS_URL, + json=payload, + headers={ + "api-subscription-key": SARVAM_API_KEY, + "Content-Type": "application/json", + }, + ) + resp.raise_for_status() + data = resp.json() + + audios = data.get("audios", []) + if not audios: + raise HTTPException(500, "No audio returned from TTS service") + + audio_bytes = base64.b64decode(audios[0]) + return Response( + content=audio_bytes, + media_type="audio/wav", + headers={"Content-Disposition": "inline"}, + ) + except httpx.HTTPStatusError as e: + print(f"Sarvam TTS error: {e.response.status_code} - {e.response.text}") + raise HTTPException(502, f"TTS service error: {e.response.status_code}") + except Exception as e: + print(f"TTS error: {e}") + raise HTTPException(500, "Failed to generate speech") diff --git a/backend/app/main.py b/backend/app/main.py new file mode 100644 index 0000000000000000000000000000000000000000..db78fb47a079e9f97282f86b655789266b0098a4 --- /dev/null +++ b/backend/app/main.py @@ -0,0 +1,127 @@ +""" +FastAPI application — Plant Disease Detection API. +MobileNetV3 classifier with Gemini AI cross-validation. + +Start: + uvicorn backend.app.main:app --host 0.0.0.0 --port 8000 --reload +""" +import os +import asyncio +from contextlib import asynccontextmanager +from fastapi import FastAPI, Request +from fastapi.middleware.cors import CORSMiddleware +from fastapi.middleware.trustedhost import TrustedHostMiddleware +from fastapi.responses import JSONResponse + +from backend.app.api.routes import router +from backend.app.ml.predictor import get_predictor +from backend.app.ml.gemini_validator import get_validator +from backend.app.services.supabase_service import supabase_service + +# Track if models are loaded +_models_ready = False + + +async def load_models_background(): + """Load models in background after server starts.""" + global _models_ready + print("Loading models in background...") + + # Initialize Supabase + supabase_service.initialize() + + # Load MobileNetV3 + predictor = get_predictor() + models_dir = os.getenv("MODELS_DIR", "checkpoints") + + if os.path.exists(models_dir): + try: + predictor.load(models_dir) + except FileNotFoundError as e: + print(f"āš ļø {e}") + print(" API will start but predictions won't work until model is available.") + else: + print(f"āš ļø Models directory not found: {models_dir}") + print(" API will start but predictions won't work until models are loaded.") + + # Check Gemini API availability + validator = get_validator() + validator.check_availability() + if not validator.is_available: + print("āš ļø Gemini API not available — predictions will work without cross-validation.") + + _models_ready = True + print("āœ“ Models loaded successfully") + + +@asynccontextmanager +async def lifespan(app: FastAPI): + """Start server immediately, load models in background.""" + print("Starting Plant Disease Detection API...") + print(f"PORT: {os.environ.get('PORT', 'not set')}") + print("āœ“ Server ready for healthchecks") + + # Start model loading in background (non-blocking) + asyncio.create_task(load_models_background()) + + yield + print("Shutting down...") + + +app = FastAPI( + title="Plant Disease Detection API", + description="MobileNetV3 plant disease classifier with Gemini AI cross-validation for reliable diagnosis.", + version="1.0.0", + lifespan=lifespan, +) + +# Trust all hosts - required for Railway healthcheck from healthcheck.railway.app +app.add_middleware( + TrustedHostMiddleware, + allowed_hosts=["*"], +) + +# CORS - allow all origins +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# Routes +app.include_router(router, prefix="/api") + + +@app.get("/") +async def root(): + return { + "name": "Plant Disease Detection API", + "version": "1.0.0", + "docs": "/docs", + } + + +@app.get("/health") +async def root_health(): + """Simple health check for load balancers (always returns OK if app is running).""" + return JSONResponse(content={"status": "ok"}, status_code=200) + + +# Optional: Prometheus metrics +try: + from prometheus_client import make_asgi_app + metrics_app = make_asgi_app() + app.mount("/metrics", metrics_app) +except ImportError: + pass + +# Optional: Sentry +try: + import sentry_sdk + sentry_dsn = os.getenv("SENTRY_DSN") + if sentry_dsn: + sentry_sdk.init(dsn=sentry_dsn, traces_sample_rate=0.1) +except ImportError: + pass diff --git a/backend/app/ml/__init__.py b/backend/app/ml/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/app/ml/__pycache__/__init__.cpython-311.pyc b/backend/app/ml/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0b0af5439577f5442a45ffdd8a73e5038083c06 Binary files /dev/null and b/backend/app/ml/__pycache__/__init__.cpython-311.pyc differ diff --git a/backend/app/ml/__pycache__/finetuner.cpython-311.pyc b/backend/app/ml/__pycache__/finetuner.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0a19d7b40e6d820938014a46a40b20f85809e6d Binary files /dev/null and b/backend/app/ml/__pycache__/finetuner.cpython-311.pyc differ diff --git a/backend/app/ml/__pycache__/gemini_validator.cpython-311.pyc b/backend/app/ml/__pycache__/gemini_validator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9f78b309327aed0f8027264948f0bbdd6094358c Binary files /dev/null and b/backend/app/ml/__pycache__/gemini_validator.cpython-311.pyc differ diff --git a/backend/app/ml/__pycache__/llama_validator.cpython-311.pyc b/backend/app/ml/__pycache__/llama_validator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d3b0bbfa5df4c38fafc8a80a9506c1cac986386 Binary files /dev/null and b/backend/app/ml/__pycache__/llama_validator.cpython-311.pyc differ diff --git a/backend/app/ml/__pycache__/predictor.cpython-311.pyc b/backend/app/ml/__pycache__/predictor.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c86d85f7c7f06d5385faf439f3bcab3d61b64916 Binary files /dev/null and b/backend/app/ml/__pycache__/predictor.cpython-311.pyc differ diff --git a/backend/app/ml/finetuner.py b/backend/app/ml/finetuner.py new file mode 100644 index 0000000000000000000000000000000000000000..3601b7f46822e467a003d87e1d83ee4f7d652bd9 --- /dev/null +++ b/backend/app/ml/finetuner.py @@ -0,0 +1,239 @@ +""" +Dynamic fine-tuning engine for PlantGuard AI. +Fine-tunes only the classification head (backbone stays frozen) using user feedback data. +Designed to run on CPU (head has ~500K params). +""" +import os +import io +import time +import logging +import threading +from typing import Optional, Dict, List +from datetime import datetime + +import numpy as np +import torch +import torch.nn as nn +import torch.optim as optim +from torch.utils.data import Dataset, DataLoader +from torchvision import transforms +from PIL import Image + +logger = logging.getLogger(__name__) + +CHECKPOINT_DIR = os.getenv("MODELS_DIR", "checkpoints") +FINETUNE_DIR = os.path.join(CHECKPOINT_DIR, "mobilenet_v3", "finetuned") +IMG_SIZE = 224 +FINETUNE_LR = 1e-4 +FINETUNE_EPOCHS = 5 +FINETUNE_BATCH = 8 +MIN_SAMPLES = 5 + + +class FeedbackDataset(Dataset): + """Dataset from user feedback images + labels.""" + + def __init__(self, images: List[Image.Image], labels: List[int], transform=None): + self.images = images + self.labels = labels + self.transform = transform or transforms.Compose([ + transforms.Resize((IMG_SIZE + 32, IMG_SIZE + 32)), + transforms.RandomCrop(IMG_SIZE), + transforms.RandomHorizontalFlip(), + transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2), + transforms.ToTensor(), + transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), + ]) + + def __len__(self): + return len(self.images) + + def __getitem__(self, idx): + img = self.images[idx].convert('RGB') + label = self.labels[idx] + if self.transform: + img = self.transform(img) + return img, label + + +class FineTuner: + """Handles model fine-tuning from user feedback.""" + + def __init__(self): + self.is_training = False + self.last_training: Optional[Dict] = None + self.training_history: List[Dict] = [] + self._lock = threading.Lock() + + def finetune(self, predictor, feedback_data: List[Dict], + supabase_service=None) -> Dict: + """ + Fine-tune the model head using feedback data. + + Args: + predictor: PlantDiseasePredictor instance with loaded model + feedback_data: List of dicts with 'image_url', 'actual_class' + supabase_service: Optional SupabaseService for downloading images + + Returns: + Training result dict with metrics + """ + with self._lock: + if self.is_training: + return {"status": "error", "message": "Training already in progress"} + self.is_training = True + + try: + start_time = time.time() + class_names = predictor.class_names + class_to_idx = {name: i for i, name in enumerate(class_names)} + + # Download and prepare images + images, labels = [], [] + skipped = 0 + for item in feedback_data: + actual_class = item.get("actual_class", "") + if actual_class not in class_to_idx: + skipped += 1 + continue + + img = self._load_image(item, supabase_service) + if img is None: + skipped += 1 + continue + + images.append(img) + labels.append(class_to_idx[actual_class]) + + if len(images) < MIN_SAMPLES: + return { + "status": "error", + "message": f"Need at least {MIN_SAMPLES} valid samples, got {len(images)}" + } + + logger.info(f"Fine-tuning with {len(images)} samples ({skipped} skipped)") + + # Create dataset with augmentation + train_dataset = FeedbackDataset(images, labels) + train_loader = DataLoader( + train_dataset, batch_size=FINETUNE_BATCH, + shuffle=True, num_workers=0 + ) + + # Fine-tune only the head + model = predictor.model + model.train() + + # Freeze backbone, unfreeze head + for param in model.backbone.parameters(): + param.requires_grad = False + for param in model.head.parameters(): + param.requires_grad = True + + # Class weights for imbalanced feedback + label_counts = np.bincount(labels, minlength=len(class_names)) + nonzero = label_counts > 0 + weights = np.zeros(len(class_names), dtype=np.float32) + weights[nonzero] = len(labels) / (nonzero.sum() * label_counts[nonzero]) + class_weights = torch.FloatTensor(weights).to(predictor.device) + + optimizer = optim.AdamW(model.head.parameters(), lr=FINETUNE_LR, weight_decay=1e-4) + criterion = nn.CrossEntropyLoss(weight=class_weights, label_smoothing=0.05) + + epoch_metrics = [] + for epoch in range(FINETUNE_EPOCHS): + total_loss, correct, total = 0, 0, 0 + for xb, yb in train_loader: + xb, yb = xb.to(predictor.device), yb.to(predictor.device) + optimizer.zero_grad() + logits = model(xb) + loss = criterion(logits, yb) + loss.backward() + optimizer.step() + + total_loss += loss.item() + correct += (logits.argmax(1) == yb).sum().item() + total += len(yb) + + acc = correct / total if total > 0 else 0 + epoch_metrics.append({ + "epoch": epoch + 1, + "loss": round(total_loss / len(train_loader), 4), + "accuracy": round(acc, 4) + }) + logger.info(f"Epoch {epoch+1}/{FINETUNE_EPOCHS}: loss={epoch_metrics[-1]['loss']:.4f}, acc={acc:.2%}") + + # Save fine-tuned model + model.eval() + os.makedirs(FINETUNE_DIR, exist_ok=True) + + version = datetime.utcnow().strftime("%Y%m%d_%H%M%S") + save_path = os.path.join(FINETUNE_DIR, f"model_v{version}.pt") + best_path = os.path.join(CHECKPOINT_DIR, "mobilenet_v3", "best_model.pt") + + # Save versioned copy + ckpt = { + "model_state_dict": model.state_dict(), + "backbone_name": "mobilenetv3_large_100", + "num_classes": len(class_names), + "class_names": class_names, + "feat_dim": model.head[1].in_features, + "finetuned_from": "user_feedback", + "num_samples": len(images), + "version": version, + } + torch.save(ckpt, save_path) + + # Overwrite best_model.pt for auto-loading on restart + torch.save(ckpt, best_path) + logger.info(f"Saved fine-tuned model: {save_path}") + + elapsed = time.time() - start_time + result = { + "status": "success", + "version": version, + "samples_used": len(images), + "samples_skipped": skipped, + "epochs": FINETUNE_EPOCHS, + "final_loss": epoch_metrics[-1]["loss"], + "final_accuracy": epoch_metrics[-1]["accuracy"], + "training_time_seconds": round(elapsed, 1), + "epoch_metrics": epoch_metrics, + } + + self.last_training = result + self.training_history.append(result) + return result + + except Exception as e: + logger.error(f"Fine-tuning failed: {e}", exc_info=True) + return {"status": "error", "message": str(e)} + finally: + with self._lock: + self.is_training = False + + def _load_image(self, item: Dict, supabase_service=None) -> Optional[Image.Image]: + """Load an image from URL or Supabase storage.""" + image_url = item.get("image_url", "") + if not image_url: + return None + + try: + import httpx + resp = httpx.get(image_url, timeout=15.0, follow_redirects=True) + resp.raise_for_status() + return Image.open(io.BytesIO(resp.content)).convert("RGB") + except Exception as e: + logger.warning(f"Failed to load image {image_url}: {e}") + return None + + +# Global instance +_finetuner: Optional[FineTuner] = None + + +def get_finetuner() -> FineTuner: + global _finetuner + if _finetuner is None: + _finetuner = FineTuner() + return _finetuner diff --git a/backend/app/ml/gemini_validator.py b/backend/app/ml/gemini_validator.py new file mode 100644 index 0000000000000000000000000000000000000000..bb5aed831332cc68af5db6cb4c20df8f245fba60 --- /dev/null +++ b/backend/app/ml/gemini_validator.py @@ -0,0 +1,260 @@ +""" +Gemini AI cross-validation service. +Validates MobileNetV3 predictions using Google Gemini with multimodal (image + text) input. +""" +import json +import os +import time +import asyncio +from typing import Optional + +from google import genai +from google.genai import types + + +MAX_RETRIES = 3 +RETRY_BACKOFF = [1, 2, 4] # seconds between retries +AVAILABILITY_RECHECK_INTERVAL = 300 # re-check every 5 minutes if unavailable + + +SYSTEM_PROMPT = """You are an expert plant pathologist AI assistant. Your role is to cross-validate +plant disease predictions made by a MobileNetV3 computer vision model. + +You will receive: +1. The actual leaf image for visual inspection +2. The model's predicted disease class and confidence +3. Top alternative predictions with probabilities +4. Image metadata (brightness, contrast, color distribution, dimensions) + +Your job is to: +- Visually inspect the leaf image for disease symptoms (spots, lesions, discoloration, wilting, etc.) +- Assess whether the prediction is reasonable given what you see in the image +- Provide a confidence assessment (High, Moderate, or Low) +- Explain your reasoning based on visible disease symptoms +- Suggest alternative diseases if the prediction seems off +- Provide practical treatment advice for the predicted disease + +IMPORTANT: Respond ONLY in valid JSON with exactly these fields: +{ + "agrees": true/false, + "confidence_assessment": "High/Moderate/Low — brief explanation", + "reasoning": "2-3 sentences explaining why you agree or disagree based on visual symptoms", + "alternative_suggestions": ["list", "of", "alternatives"] or [], + "treatment_advice": "Practical treatment steps", + "summary": "One-line summary of your validation" +} + +Do NOT include any text outside the JSON object. No explanations, no markdown, just the JSON.""" + + +def _build_prompt(prediction: dict, image_metadata: dict) -> str: + """Build the text prompt for Gemini validation.""" + top_k_str = "\n".join( + f" {i+1}. {p['class']} — {p['probability']*100:.1f}%" + for i, p in enumerate(prediction.get("top_k", [])) + ) + + return f"""Validate this plant disease prediction by examining the leaf image I've provided: + +**MobileNetV3 Prediction:** +- Disease: {prediction['class']} +- Confidence: {prediction['probability']*100:.1f}% +- Uncertainty: {prediction['uncertainty']*100:.1f}% + +**Top-K Alternatives:** +{top_k_str} + +**Image Metadata:** +- Dimensions: {image_metadata.get('width', '?')}x{image_metadata.get('height', '?')} pixels +- Brightness: {image_metadata.get('brightness', '?')} (0=dark, 1=bright) +- Contrast: {image_metadata.get('contrast', '?')} (0=flat, 1=high) +- Dominant color: {image_metadata.get('dominant_color', '?')} +- Green ratio: {image_metadata.get('green_ratio', '?')} (higher = more green/leaf content) +- RGB means: R={image_metadata.get('r_mean', '?')}, G={image_metadata.get('g_mean', '?')}, B={image_metadata.get('b_mean', '?')} + +Look at the leaf image carefully and respond with your validation JSON:""" + + +def _parse_gemini_response(response_text: str) -> Optional[dict]: + """Parse Gemini JSON response, handling markdown code blocks and extra text.""" + text = response_text.strip() + + # Strip markdown code fences if present + if text.startswith("```"): + lines = text.split("\n") + lines = [ln for ln in lines if not ln.strip().startswith("```")] + text = "\n".join(lines).strip() + + try: + data = json.loads(text) + except json.JSONDecodeError: + # Try to find JSON within the text + start = text.find("{") + end = text.rfind("}") + 1 + if start >= 0 and end > start: + try: + data = json.loads(text[start:end]) + except json.JSONDecodeError: + return None + else: + return None + + required = ["agrees", "confidence_assessment", "reasoning", "summary"] + if not all(k in data for k in required): + return None + + return { + "agrees": bool(data["agrees"]), + "confidence_assessment": str(data["confidence_assessment"]), + "reasoning": str(data["reasoning"]), + "alternative_suggestions": list(data.get("alternative_suggestions", [])), + "treatment_advice": str(data.get("treatment_advice", "")), + "summary": str(data["summary"]), + } + + +class GeminiValidator: + """Validates MobileNetV3 predictions using Google Gemini with multimodal input.""" + + def __init__(self, api_key: str, model_name: str = "gemini-2.5-flash"): + self.model_name = model_name + self._available = False + self._last_availability_check = 0 + try: + self._client = genai.Client(api_key=api_key) + self._available = True + print(f"āœ“ Gemini client initialized: {self.model_name}") + except Exception as e: + print(f"āš ļø Gemini client initialization failed: {e}") + self._client = None + + def check_availability(self) -> bool: + """Verify Gemini API is reachable with a lightweight call.""" + if not self._client: + self._available = False + return False + try: + response = self._client.models.generate_content( + model=self.model_name, + contents="Reply with only the word: OK", + config=types.GenerateContentConfig( + max_output_tokens=5, + ), + ) + self._available = response.text is not None + self._last_availability_check = time.time() + if self._available: + print(f"āœ“ Gemini API reachable: {self.model_name}") + return self._available + except Exception as e: + print(f"āš ļø Gemini API not reachable: {e}") + self._available = False + self._last_availability_check = time.time() + return False + + def _ensure_available(self) -> bool: + """Re-check availability if previously unavailable and enough time has passed.""" + if self._available: + return True + if not self._client: + return False + elapsed = time.time() - self._last_availability_check + if elapsed >= AVAILABILITY_RECHECK_INTERVAL: + print("šŸ”„ Re-checking Gemini availability...") + return self.check_availability() + return False + + @property + def is_available(self) -> bool: + return self._ensure_available() + + def validate( + self, prediction: dict, image_metadata: dict, image_bytes: bytes = None + ) -> Optional[dict]: + """ + Validate a MobileNet prediction with Gemini (multimodal: image + text). + Retries up to MAX_RETRIES times on transient failures. + """ + if not self._ensure_available(): + return None + + prompt_text = _build_prompt(prediction, image_metadata) + + contents = [] + if image_bytes: + contents.append( + types.Part.from_bytes(data=image_bytes, mime_type="image/jpeg") + ) + contents.append(prompt_text) + + for attempt in range(MAX_RETRIES): + try: + response = self._client.models.generate_content( + model=self.model_name, + contents=contents, + config=types.GenerateContentConfig( + system_instruction=SYSTEM_PROMPT, + temperature=0.3, + max_output_tokens=4096, + ), + ) + content = response.text + if not content: + print(f"Gemini returned empty response (attempt {attempt + 1})") + if attempt < MAX_RETRIES - 1: + time.sleep(RETRY_BACKOFF[attempt]) + continue + return None + + parsed = _parse_gemini_response(content) + if parsed is None: + print(f"Gemini response parse failed (attempt {attempt + 1}). Raw: {content[:300]}") + if attempt < MAX_RETRIES - 1: + time.sleep(RETRY_BACKOFF[attempt]) + continue + return parsed + + except Exception as e: + error_str = str(e).lower() + is_rate_limit = "429" in error_str or "rate" in error_str or "quota" in error_str + print(f"Gemini validation error (attempt {attempt + 1}/{MAX_RETRIES}): {e}") + + if is_rate_limit: + wait = RETRY_BACKOFF[attempt] * 2 + print(f" → Rate limited, waiting {wait}s before retry...") + if attempt < MAX_RETRIES - 1: + time.sleep(wait) + continue + self._available = False + self._last_availability_check = time.time() + return None + + if attempt < MAX_RETRIES - 1: + time.sleep(RETRY_BACKOFF[attempt]) + continue + return None + + return None + + async def validate_async( + self, prediction: dict, image_metadata: dict, image_bytes: bytes = None + ) -> Optional[dict]: + """Async wrapper around validate() for use in FastAPI endpoints.""" + loop = asyncio.get_event_loop() + return await loop.run_in_executor( + None, self.validate, prediction, image_metadata, image_bytes + ) + + +# Global validator instance +_validator: Optional[GeminiValidator] = None + + +def get_validator() -> GeminiValidator: + """Get or create the global Gemini validator instance.""" + global _validator + if _validator is None: + api_key = os.getenv("GEMINI_API_KEY", "") + model = os.getenv("GEMINI_MODEL", "gemini-2.5-flash") + _validator = GeminiValidator(api_key=api_key, model_name=model) + return _validator diff --git a/backend/app/ml/predictor.py b/backend/app/ml/predictor.py new file mode 100644 index 0000000000000000000000000000000000000000..eb64eda5d25834f6805e59f5183b52609191133d --- /dev/null +++ b/backend/app/ml/predictor.py @@ -0,0 +1,225 @@ +""" +ML Inference Engine — MobileNetV3 plant disease classifier. +Returns probabilities with uncertainty estimates and image metadata for LLM validation. +""" +import os +import json +from pathlib import Path +from typing import Optional + +import numpy as np +import torch +import torch.nn as nn +from PIL import Image, ImageStat +from torchvision import transforms +import timm + +import sys +sys.path.insert(0, str(Path(__file__).parent.parent.parent.parent)) + + +class FlexibleModel(nn.Module): + """MobileNetV3 with frozen backbone and trainable classification head.""" + def __init__(self, backbone_name: str, num_classes: int, feat_dim: int = None): + super().__init__() + self.backbone = timm.create_model(backbone_name, pretrained=False, num_classes=0) + if feat_dim is None: + with torch.no_grad(): + feat_dim = self.backbone(torch.randn(1, 3, 224, 224)).shape[1] + self.head = nn.Sequential( + nn.Dropout(0.3), + nn.Linear(feat_dim, 512), + nn.ReLU(), + nn.BatchNorm1d(512), + nn.Dropout(0.2), + nn.Linear(512, num_classes) + ) + + def forward(self, x): + feat = self.backbone(x) + return self.head(feat) + + +class PlantDiseasePredictor: + """ + Production inference engine using MobileNetV3 for plant disease classification. + Extracts image metadata for LLM cross-validation. + """ + + def __init__(self, device: str = "auto"): + if device == "auto": + self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + else: + self.device = torch.device(device) + + self.model = None + self.class_names = [] + self.num_classes = 0 + self.transform = None + self._loaded = False + + def _load_model_from_checkpoint(self, ckpt): + """Load MobileNetV3 from checkpoint.""" + num_classes = ckpt['num_classes'] + + if 'backbone_name' in ckpt: + model = FlexibleModel( + ckpt['backbone_name'], + num_classes, + feat_dim=ckpt.get('feat_dim') + ) + model.load_state_dict(ckpt['model_state_dict']) + elif 'model_type' in ckpt: + try: + from ml_pipeline.models.architectures import create_model + model = create_model( + ckpt['model_type'], + num_classes=num_classes, + pretrained=False, dropout=0.0 + ) + model.load_state_dict(ckpt['model_state_dict']) + except Exception: + raise ValueError(f"Cannot load model_type={ckpt.get('model_type')}") + else: + raise ValueError("Unknown checkpoint format") + + return model + + def load(self, models_dir: str = "checkpoints"): + """Load MobileNetV3 model from checkpoint directory.""" + # Load class names + class_names_path = os.path.join(models_dir, "class_names.json") + if os.path.exists(class_names_path): + with open(class_names_path) as f: + self.class_names = json.load(f) + self.num_classes = len(self.class_names) + print(f"Loaded {self.num_classes} class names") + + # Load MobileNetV3 checkpoint + ckpt_path = os.path.join(models_dir, "mobilenet_v3", "best_model.pt") + if not os.path.exists(ckpt_path): + raise FileNotFoundError(f"MobileNetV3 checkpoint not found: {ckpt_path}") + + ckpt = torch.load(ckpt_path, map_location=self.device, weights_only=False) + self.model = self._load_model_from_checkpoint(ckpt) + self.model.to(self.device).eval() + + if not self.class_names and 'class_names' in ckpt: + self.class_names = ckpt['class_names'] + self.num_classes = len(self.class_names) + + if not self.num_classes: + self.num_classes = ckpt['num_classes'] + + # Fallback class names + if not self.class_names: + try: + from ml_pipeline.data.dataset import PLANTVILLAGE_CLASSES + self.class_names = PLANTVILLAGE_CLASSES + self.num_classes = len(self.class_names) + except ImportError: + self.class_names = [f"class_{i}" for i in range(self.num_classes or 38)] + self.num_classes = len(self.class_names) + + self.transform = transforms.Compose([ + transforms.Resize((224, 224)), + transforms.ToTensor(), + transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), + ]) + + self._loaded = True + val_f1 = ckpt.get('val_f1', 'N/A') + print(f"MobileNetV3 ready: {self.num_classes} classes on {self.device} (val_f1={val_f1})") + + def extract_image_metadata(self, image: Image.Image) -> dict: + """Extract image metadata for LLM validation context.""" + rgb = image.convert('RGB') + stat = ImageStat.Stat(rgb) + r_mean, g_mean, b_mean = stat.mean + brightness = sum(stat.mean) / 3.0 / 255.0 + contrast = sum(stat.stddev) / 3.0 / 255.0 + + # Dominant color channel + channels = {'red': r_mean, 'green': g_mean, 'blue': b_mean} + dominant = max(channels, key=channels.get) + + # Green ratio (useful for plant/leaf detection) + total = r_mean + g_mean + b_mean + green_ratio = g_mean / total if total > 0 else 0 + + return { + "width": image.width, + "height": image.height, + "brightness": round(brightness, 3), + "contrast": round(contrast, 3), + "dominant_color": dominant, + "green_ratio": round(green_ratio, 3), + "r_mean": round(r_mean, 1), + "g_mean": round(g_mean, 1), + "b_mean": round(b_mean, 1), + } + + def preprocess(self, image: Image.Image) -> torch.Tensor: + """Preprocess a PIL image for inference.""" + if image.mode != 'RGB': + image = image.convert('RGB') + tensor = self.transform(image).unsqueeze(0).to(self.device) + return tensor + + @torch.no_grad() + def predict(self, image: Image.Image, top_k: int = 5) -> dict: + """ + Run MobileNetV3 prediction on a single image. + Returns prediction with class, probability, uncertainty, top-k, and image metadata. + """ + if not self._loaded: + raise RuntimeError("Model not loaded. Call load() first.") + + tensor = self.preprocess(image) + logits = self.model(tensor).cpu().numpy() + probs = self._softmax(logits)[0] + + # Entropy-based uncertainty + pred_entropy = -(probs * np.log(probs + 1e-10)).sum() + max_entropy = np.log(len(probs)) + uncertainty = float(pred_entropy / max_entropy) + + # Top-k predictions + top_k_indices = np.argsort(probs)[::-1][:top_k] + top_k_predictions = [] + for idx in top_k_indices: + class_name = self.class_names[idx] if idx < len(self.class_names) else f"class_{idx}" + top_k_predictions.append({ + "class": class_name, + "probability": float(probs[idx]), + }) + + best_idx = top_k_indices[0] + image_metadata = self.extract_image_metadata(image) + + result = { + "class": self.class_names[best_idx] if best_idx < len(self.class_names) else f"class_{best_idx}", + "probability": float(probs[best_idx]), + "uncertainty": round(uncertainty, 4), + "top_k": top_k_predictions, + "image_metadata": image_metadata, + } + + return result + + @staticmethod + def _softmax(logits): + exp = np.exp(logits - logits.max(axis=1, keepdims=True)) + return exp / exp.sum(axis=1, keepdims=True) + + +# Global predictor instance +_predictor: Optional[PlantDiseasePredictor] = None + + +def get_predictor() -> PlantDiseasePredictor: + """Get or create the global predictor instance.""" + global _predictor + if _predictor is None: + _predictor = PlantDiseasePredictor() + return _predictor diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/app/models/__pycache__/__init__.cpython-311.pyc b/backend/app/models/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05ef2ff0f795ef0f28de87032b234b8164eab2f8 Binary files /dev/null and b/backend/app/models/__pycache__/__init__.cpython-311.pyc differ diff --git a/backend/app/models/__pycache__/schemas.cpython-311.pyc b/backend/app/models/__pycache__/schemas.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27329a016dc56fb937abbe8e9abad606304f39a2 Binary files /dev/null and b/backend/app/models/__pycache__/schemas.cpython-311.pyc differ diff --git a/backend/app/models/schemas.py b/backend/app/models/schemas.py new file mode 100644 index 0000000000000000000000000000000000000000..bdf053e63a5bd9f9bbb22b1bca9ca88a3d2a7682 --- /dev/null +++ b/backend/app/models/schemas.py @@ -0,0 +1,83 @@ +"""Pydantic models for API request/response schemas.""" +from typing import List, Optional +from pydantic import BaseModel, Field + + +class PredictionItem(BaseModel): + class_name: str = Field(..., alias="class", description="Disease class name") + probability: float = Field(..., ge=0, le=1, description="Calibrated probability") + + class Config: + populate_by_name = True + + +class GeminiValidation(BaseModel): + """Gemini AI cross-validation report for MobileNet predictions.""" + agrees: bool = Field(..., description="Whether Gemini agrees with MobileNet prediction") + confidence_assessment: str = Field(..., description="Gemini's assessment of prediction confidence") + reasoning: str = Field(..., description="Explanation based on visual inspection of the leaf image") + alternative_suggestions: List[str] = Field(default_factory=list, description="Alternative diseases to consider") + treatment_advice: str = Field(default="", description="Recommended treatment or next steps") + summary: str = Field(..., description="Brief one-line validation summary") + + class Config: + json_schema_extra = { + "example": { + "agrees": True, + "confidence_assessment": "High — the visible symptoms align well with the predicted disease.", + "reasoning": "The leaf image shows brown necrotic lesions with concentric rings on tomato leaves, which is highly consistent with Early Blight caused by Alternaria solani.", + "alternative_suggestions": ["Tomato___Septoria_leaf_spot"], + "treatment_advice": "Apply copper-based fungicide. Remove affected leaves. Improve air circulation around plants. Avoid overhead watering.", + "summary": "Prediction confirmed: Early Blight on Tomato with high confidence." + } + } + + +class PredictionResponse(BaseModel): + """Main prediction response with Gemini AI validation.""" + class_name: str = Field(..., alias="class", description="Predicted disease class") + probability: float = Field(..., ge=0, le=1, description="Model probability") + uncertainty: float = Field(..., ge=0, le=1, description="Uncertainty score (0=confident, 1=uncertain)") + top_k: List[PredictionItem] = Field(default_factory=list, description="Top-k predictions") + gemini_validation: Optional[GeminiValidation] = Field(default=None, description="Gemini AI cross-validation report") + image_url: Optional[str] = Field(default=None, description="Supabase storage URL of the uploaded image") + + class Config: + populate_by_name = True + json_schema_extra = { + "example": { + "class": "Tomato___Early_blight", + "probability": 0.92, + "uncertainty": 0.08, + "top_k": [ + {"class": "Tomato___Early_blight", "probability": 0.92}, + {"class": "Tomato___Late_blight", "probability": 0.05}, + {"class": "Tomato___Bacterial_spot", "probability": 0.02}, + ], + "gemini_validation": None, + } + } + + +class HealthResponse(BaseModel): + status: str + model_loaded: bool + gemini_available: bool + device: str + + +class UserProfile(BaseModel): + id: str + email: str + display_name: Optional[str] = None + + +class PredictionHistory(BaseModel): + id: Optional[str] = None + user_id: str + image_url: Optional[str] = None + prediction_class: str + probability: float + uncertainty: float + top_k: Optional[List[dict]] = None + created_at: Optional[str] = None diff --git a/backend/app/services/__init__.py b/backend/app/services/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/app/services/__pycache__/__init__.cpython-311.pyc b/backend/app/services/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aeb8f69718440b67eb045edab94b73f57cf63fe6 Binary files /dev/null and b/backend/app/services/__pycache__/__init__.cpython-311.pyc differ diff --git a/backend/app/services/__pycache__/supabase_service.cpython-311.pyc b/backend/app/services/__pycache__/supabase_service.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14d4a4e359eb1a0b4960ca76ad5d49a27622e8be Binary files /dev/null and b/backend/app/services/__pycache__/supabase_service.cpython-311.pyc differ diff --git a/backend/app/services/supabase_service.py b/backend/app/services/supabase_service.py new file mode 100644 index 0000000000000000000000000000000000000000..415195351b4b971876d0d119b822e8a5e944bb98 --- /dev/null +++ b/backend/app/services/supabase_service.py @@ -0,0 +1,242 @@ +"""Supabase service for authentication and data storage.""" +import os +import logging +from typing import Optional, List +from datetime import datetime +import json + +from dotenv import load_dotenv + +logger = logging.getLogger(__name__) + +# Load .env from backend directory (handles running from project root) +load_dotenv(os.path.join(os.path.dirname(__file__), '..', '..', '.env')) +load_dotenv() # Also check CWD + +SUPABASE_URL = os.getenv("SUPABASE_URL", "") +SUPABASE_KEY = os.getenv("SUPABASE_KEY", "") +SUPABASE_SERVICE_KEY = os.getenv("SUPABASE_SERVICE_KEY", "") + + +class SupabaseService: + """Supabase client wrapper for auth, database, and storage.""" + + def __init__(self): + self.client = None + self._initialized = False + + def initialize(self): + """Initialize Supabase client.""" + if not SUPABASE_URL or not SUPABASE_KEY: + print("āš ļø Supabase not configured. Set SUPABASE_URL and SUPABASE_KEY env vars.") + print(" The app will work without Supabase (no auth/history).") + return + + try: + from supabase import create_client + # Anon client for auth (token verification) + self.client = create_client(SUPABASE_URL, SUPABASE_KEY) + # Service role client for DB/storage (bypasses RLS) + if SUPABASE_SERVICE_KEY: + self._admin_client = create_client(SUPABASE_URL, SUPABASE_SERVICE_KEY) + else: + self._admin_client = self.client + print("āš ļø No SUPABASE_SERVICE_KEY — using anon key for DB ops (RLS may block writes)") + self._initialized = True + print("āœ“ Supabase connected") + except Exception as e: + print(f"āš ļø Supabase init failed: {e}") + + @property + def is_available(self) -> bool: + return self._initialized and self.client is not None + + # --- Auth --- + def verify_token(self, token: str) -> Optional[dict]: + """Verify a Supabase JWT token and return user info.""" + if not self.is_available: + logger.warning("verify_token called but Supabase not available") + return None + try: + user = self.client.auth.get_user(token) + return {"id": user.user.id, "email": user.user.email} + except Exception as e: + logger.error(f"Token verification failed: {e}") + return None + + def sign_up(self, email: str, password: str) -> dict: + if not self.is_available: + return {"error": "Supabase not configured"} + try: + res = self.client.auth.sign_up({"email": email, "password": password}) + return {"user_id": res.user.id, "email": res.user.email} + except Exception as e: + return {"error": str(e)} + + def sign_in(self, email: str, password: str) -> dict: + if not self.is_available: + return {"error": "Supabase not configured"} + try: + res = self.client.auth.sign_in_with_password({"email": email, "password": password}) + return { + "access_token": res.session.access_token, + "refresh_token": res.session.refresh_token, + "user_id": res.user.id, + "email": res.user.email, + } + except Exception as e: + return {"error": str(e)} + + # --- Prediction History --- + def save_prediction(self, user_id: str, prediction: dict, + image_url: Optional[str] = None, + gemini_validation: Optional[dict] = None) -> dict: + """Save a prediction to history.""" + if not self.is_available: + return {"status": "skipped", "reason": "supabase_not_configured"} + try: + data = { + "user_id": user_id, + "prediction_class": prediction.get("class", ""), + "probability": prediction.get("probability", 0), + "uncertainty": prediction.get("uncertainty", 0), + "top_k": json.dumps(prediction.get("top_k", [])), + "image_url": image_url, + "created_at": datetime.utcnow().isoformat(), + } + if gemini_validation is not None: + data["gemini_validation"] = json.dumps(gemini_validation) + result = self._admin_client.table("predictions").insert(data).execute() + return {"status": "saved", "id": result.data[0]["id"] if result.data else None} + except Exception as e: + return {"status": "error", "error": str(e)} + + def get_history(self, user_id: str, limit: int = 20) -> List[dict]: + """Get prediction history for a user.""" + if not self.is_available: + logger.warning("get_history called but Supabase not available") + return [] + try: + result = ( + self._admin_client.table("predictions") + .select("*") + .eq("user_id", user_id) + .order("created_at", desc=True) + .limit(limit) + .execute() + ) + return result.data or [] + except Exception as e: + logger.error(f"Failed to get history: {e}") + return [] + + # --- Image Storage --- + def upload_image(self, file_bytes: bytes, filename: str, user_id: str) -> Optional[str]: + """Upload image to Supabase Storage and return URL.""" + if not self.is_available: + return None + try: + import uuid + ext = filename.rsplit('.', 1)[-1] if '.' in filename else 'jpg' + unique_name = f"{uuid.uuid4().hex}.{ext}" + path = f"{user_id}/{unique_name}" + self._admin_client.storage.from_("plant-images").upload( + path, file_bytes, + file_options={"content-type": f"image/{ext}", "upsert": "true"} + ) + url = self._admin_client.storage.from_("plant-images").get_public_url(path) + return url + except Exception as e: + logger.error(f"Image upload failed: {e}") + return None + + def get_stats(self, user_id: str) -> dict: + """Get user prediction statistics.""" + if not self.is_available: + return {"total": 0, "diseases_detected": 0} + try: + result = ( + self._admin_client.table("predictions") + .select("prediction_class") + .eq("user_id", user_id) + .execute() + ) + data = result.data or [] + unique_diseases = len(set(d["prediction_class"] for d in data)) + return {"total": len(data), "diseases_detected": unique_diseases} + except Exception: + return {"total": 0, "diseases_detected": 0} + + # --- Training Feedback --- + def save_feedback(self, user_id: Optional[str], prediction_id: Optional[str], + image_url: str, predicted_class: str, + actual_class: str, is_correct: bool) -> dict: + """Save user feedback on a prediction for model training.""" + if not self.is_available: + return {"status": "skipped", "reason": "supabase_not_configured"} + try: + data = { + "predicted_class": predicted_class, + "actual_class": actual_class, + "is_correct": is_correct, + "created_at": datetime.utcnow().isoformat(), + } + if user_id and user_id != "anonymous": + data["user_id"] = user_id + if prediction_id: + data["prediction_id"] = prediction_id + if image_url: + data["image_url"] = image_url + result = self._admin_client.table("training_feedback").insert(data).execute() + return {"status": "saved", "id": result.data[0]["id"] if result.data else None} + except Exception as e: + logger.error(f"Failed to save feedback: {e}") + return {"status": "error", "error": str(e)} + + def get_feedback(self, limit: int = 500) -> List[dict]: + """Get all training feedback (for fine-tuning).""" + if not self.is_available: + return [] + try: + result = ( + self._admin_client.table("training_feedback") + .select("*") + .order("created_at", desc=True) + .limit(limit) + .execute() + ) + return result.data or [] + except Exception as e: + logger.error(f"Failed to get feedback: {e}") + return [] + + def get_feedback_stats(self) -> dict: + """Get feedback statistics for training dashboard.""" + if not self.is_available: + return {"total": 0, "correct": 0, "incorrect": 0, "classes": {}} + try: + result = ( + self._admin_client.table("training_feedback") + .select("*") + .execute() + ) + data = result.data or [] + correct = sum(1 for d in data if d.get("is_correct")) + incorrect = len(data) - correct + classes = {} + for d in data: + cls = d.get("actual_class", "unknown") + classes[cls] = classes.get(cls, 0) + 1 + return { + "total": len(data), + "correct": correct, + "incorrect": incorrect, + "classes": classes, + } + except Exception as e: + logger.error(f"Failed to get feedback stats: {e}") + return {"total": 0, "correct": 0, "incorrect": 0, "classes": {}} + + +# Global instance +supabase_service = SupabaseService() diff --git a/backend/requirements.txt b/backend/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..51a44e9f9bef9f5b6a52b631b3b086dc92740e02 --- /dev/null +++ b/backend/requirements.txt @@ -0,0 +1,20 @@ +# Backend Dependencies +fastapi>=0.104.0 +uvicorn[standard]>=0.24.0 +python-multipart>=0.0.6 +Pillow>=10.0.0 +numpy>=1.24.0 +pydantic>=2.5.0 +supabase>=2.0.0 +python-dotenv>=1.0.0 +prometheus-client>=0.19.0 +sentry-sdk[fastapi]>=1.38.0 +httpx>=0.25.0 +pyyaml>=6.0 +google-genai>=1.0.0 + +# PyTorch CPU-only (much smaller than CUDA version for deployment) +--extra-index-url https://download.pytorch.org/whl/cpu +torch>=2.1.0 +torchvision>=0.16.0 +timm>=0.9.12 diff --git a/backend/start.sh b/backend/start.sh new file mode 100644 index 0000000000000000000000000000000000000000..f9d68af4a1e689eab6adfa85e466a2114899d735 --- /dev/null +++ b/backend/start.sh @@ -0,0 +1,7 @@ +#!/bin/bash +# Startup script for Railway deployment + +echo "Starting PlantGuard API..." +echo "PORT=${PORT:-8000}" + +exec uvicorn backend.app.main:app --host 0.0.0.0 --port "${PORT:-8000}" diff --git a/checkpoints/class_names.json b/checkpoints/class_names.json new file mode 100644 index 0000000000000000000000000000000000000000..e672a6869bd57394cb79c1b3476ba5e0f5586b5a --- /dev/null +++ b/checkpoints/class_names.json @@ -0,0 +1,40 @@ +[ + "Apple___Apple_scab", + "Apple___Black_rot", + "Apple___Cedar_apple_rust", + "Apple___healthy", + "Blueberry___healthy", + "Cherry_(including_sour)___Powdery_mildew", + "Cherry_(including_sour)___healthy", + "Corn_(maize)___Cercospora_leaf_spot Gray_leaf_spot", + "Corn_(maize)___Common_rust_", + "Corn_(maize)___Northern_Leaf_Blight", + "Corn_(maize)___healthy", + "Grape___Black_rot", + "Grape___Esca_(Black_Measles)", + "Grape___Leaf_blight_(Isariopsis_Leaf_Spot)", + "Grape___healthy", + "Orange___Haunglongbing_(Citrus_greening)", + "Peach___Bacterial_spot", + "Peach___healthy", + "Pepper,_bell___Bacterial_spot", + "Pepper,_bell___healthy", + "Potato___Early_blight", + "Potato___Late_blight", + "Potato___healthy", + "Raspberry___healthy", + "Soybean___healthy", + "Squash___Powdery_mildew", + "Strawberry___Leaf_scorch", + "Strawberry___healthy", + "Tomato___Bacterial_spot", + "Tomato___Early_blight", + "Tomato___Late_blight", + "Tomato___Leaf_Mold", + "Tomato___Septoria_leaf_spot", + "Tomato___Spider_mites Two-spotted_spider_mite", + "Tomato___Target_Spot", + "Tomato___Tomato_Yellow_Leaf_Curl_Virus", + "Tomato___Tomato_mosaic_virus", + "Tomato___healthy" +] \ No newline at end of file diff --git a/checkpoints/mobilenet_v3/best_model.pt b/checkpoints/mobilenet_v3/best_model.pt new file mode 100644 index 0000000000000000000000000000000000000000..67f5e8301d1488361c9b348c4a4b7f875bffb082 --- /dev/null +++ b/checkpoints/mobilenet_v3/best_model.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:656e2323ef885eb869b0eee588b541166b7d18d07e2c008ef0fc0e24668be2e2 +size 19728464 diff --git a/checkpoints/mobilenet_v3/training_history.json b/checkpoints/mobilenet_v3/training_history.json new file mode 100644 index 0000000000000000000000000000000000000000..d23bcb15e84f2a1643eda57d2f7b39a4bef7c5e8 --- /dev/null +++ b/checkpoints/mobilenet_v3/training_history.json @@ -0,0 +1,137 @@ +[ + { + "epoch": 1, + "train_loss": 1.4754562307751535, + "train_acc": 0.7657695232954684, + "val_loss": 1.0507514628709531, + "val_acc": 0.8720629843769221, + "val_f1": 0.839838479693271, + "time": 2134.799591779709 + }, + { + "epoch": 2, + "train_loss": 1.1581421535187277, + "train_acc": 0.8464633577860105, + "val_loss": 0.9508979570631887, + "val_acc": 0.8804280969368926, + "val_f1": 0.877772828468893, + "time": 1520.8893296718597 + }, + { + "epoch": 3, + "train_loss": 1.0474498474990928, + "train_acc": 0.8790941877867465, + "val_loss": 0.9237516089981678, + "val_acc": 0.9143806126214786, + "val_f1": 0.8952668643192974, + "time": 1455.7170903682709 + }, + { + "epoch": 4, + "train_loss": 1.0000751933647287, + "train_acc": 0.894894379155524, + "val_loss": 0.8974116262267617, + "val_acc": 0.9227457251814492, + "val_f1": 0.8968918629162261, + "time": 1407.9666616916656 + }, + { + "epoch": 5, + "train_loss": 0.9811938846691437, + "train_acc": 0.8995068573811918, + "val_loss": 0.8841090396338818, + "val_acc": 0.9443966047484316, + "val_f1": 0.926687092394606, + "time": 1396.372747182846 + }, + { + "epoch": 6, + "train_loss": 0.9563302820200449, + "train_acc": 0.9098849333889448, + "val_loss": 0.8687813504069459, + "val_acc": 0.9404600811907984, + "val_f1": 0.9187613017763079, + "time": 1463.5929679870605 + }, + { + "epoch": 7, + "train_loss": 0.944852351721265, + "train_acc": 0.9122647758777203, + "val_loss": 0.8668547753025504, + "val_acc": 0.945749784721368, + "val_f1": 0.9263269732704236, + "time": 1441.4581434726715 + }, + { + "epoch": 8, + "train_loss": 0.9229121897808237, + "train_acc": 0.9209745086974656, + "val_loss": 0.8765205524715722, + "val_acc": 0.9500553573625292, + "val_f1": 0.9316049347432307, + "time": 1426.3272116184235 + }, + { + "epoch": 9, + "train_loss": 0.9052303869458532, + "train_acc": 0.9262003483893128, + "val_loss": 0.8286291617973178, + "val_acc": 0.9511625046131136, + "val_f1": 0.9329479902298496, + "time": 1459.579822063446 + }, + { + "epoch": 10, + "train_loss": 0.8945274736200061, + "train_acc": 0.9302239996074486, + "val_loss": 0.8196153508681877, + "val_acc": 0.9554680772542749, + "val_f1": 0.9398121159320021, + "time": 1478.4978857040405 + }, + { + "epoch": 11, + "train_loss": 0.8811485677536466, + "train_acc": 0.9341985819082902, + "val_loss": 0.8023291778330709, + "val_acc": 0.9612498462295486, + "val_f1": 0.9471128124649691, + "time": 1509.495314836502 + }, + { + "epoch": 12, + "train_loss": 0.8654819950578351, + "train_acc": 0.938933732427194, + "val_loss": 0.7963946771387961, + "val_acc": 0.9581744372001476, + "val_f1": 0.9435510220579112, + "time": 1472.0998933315277 + }, + { + "epoch": 13, + "train_loss": 0.8616015490969084, + "train_acc": 0.9413626438332638, + "val_loss": 0.7887863209434584, + "val_acc": 0.9621109607577808, + "val_f1": 0.9485549077712332, + "time": 1612.443365573883 + }, + { + "epoch": 14, + "train_loss": 0.8532575388531108, + "train_acc": 0.9417061262543241, + "val_loss": 0.8017812482282227, + "val_acc": 0.9635871570918932, + "val_f1": 0.9524276544446466, + "time": 1710.4971199035645 + }, + { + "epoch": 15, + "train_loss": 0.8508924984108522, + "train_acc": 0.943399003900979, + "val_loss": 0.7979195382080826, + "val_acc": 0.9613728625907245, + "val_f1": 0.9477633630914835, + "time": 1419.0859017372131 + } +] \ No newline at end of file diff --git a/ml_pipeline/__init__.py b/ml_pipeline/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/ml_pipeline/__pycache__/__init__.cpython-311.pyc b/ml_pipeline/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d00146bd1affed1cf8c057cb2eccd25ca7035a4 Binary files /dev/null and b/ml_pipeline/__pycache__/__init__.cpython-311.pyc differ diff --git a/ml_pipeline/configs/convnext_tiny.yaml b/ml_pipeline/configs/convnext_tiny.yaml new file mode 100644 index 0000000000000000000000000000000000000000..52fbc0e437e264c93320485d06d07cbaa001b6a2 --- /dev/null +++ b/ml_pipeline/configs/convnext_tiny.yaml @@ -0,0 +1,38 @@ +# ConvNeXt-Tiny Configuration +model: + type: convnext_tiny + num_classes: 38 + pretrained: true + dropout: 0.3 + +data: + img_size: 224 + batch_size: 64 + augment_level: heavy + num_workers: 4 + use_balanced_sampling: true + +training: + epochs: 50 + optimizer: adamw + learning_rate: 0.0008 + weight_decay: 0.0001 + scheduler: cosine + warmup_epochs: 5 + label_smoothing: 0.05 + mixup_alpha: 0.2 + cutmix_prob: 0.5 + early_stopping_patience: 10 + early_stopping_metric: val_f1 + gradient_clip_val: 1.0 + seed: 456 + +loss: + type: cross_entropy + focal_gamma: 2.0 + focal_alpha: null + +checkpoint: + save_dir: checkpoints/convnext_tiny + save_top_k: 3 + monitor: val_f1 diff --git a/ml_pipeline/configs/efficientnet_v2.yaml b/ml_pipeline/configs/efficientnet_v2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..58e4600cfcb9a61e89643d7c69c424ddadd444bb --- /dev/null +++ b/ml_pipeline/configs/efficientnet_v2.yaml @@ -0,0 +1,38 @@ +# EfficientNetV2-S Configuration +model: + type: efficientnet_v2 + num_classes: 38 + pretrained: true + dropout: 0.3 + +data: + img_size: 384 + batch_size: 32 + augment_level: heavy + num_workers: 4 + use_balanced_sampling: true + +training: + epochs: 60 + optimizer: adamw + learning_rate: 0.001 + weight_decay: 0.0001 + scheduler: cosine + warmup_epochs: 5 + label_smoothing: 0.05 + mixup_alpha: 0.2 + cutmix_prob: 0.5 + early_stopping_patience: 10 + early_stopping_metric: val_f1 + gradient_clip_val: 1.0 + seed: 42 + +loss: + type: cross_entropy # or focal + focal_gamma: 2.0 + focal_alpha: null # auto from class weights + +checkpoint: + save_dir: checkpoints/efficientnet_v2 + save_top_k: 3 + monitor: val_f1 diff --git a/ml_pipeline/configs/mobilenet_v3.yaml b/ml_pipeline/configs/mobilenet_v3.yaml new file mode 100644 index 0000000000000000000000000000000000000000..36a5424581296b13bbccdbe0eb9e77f2ea5d6191 --- /dev/null +++ b/ml_pipeline/configs/mobilenet_v3.yaml @@ -0,0 +1,38 @@ +# MobileNetV3-Large Configuration (Edge/Mobile) +model: + type: mobilenet_v3 + num_classes: 38 + pretrained: true + dropout: 0.2 + +data: + img_size: 224 + batch_size: 128 + augment_level: medium + num_workers: 4 + use_balanced_sampling: true + +training: + epochs: 80 + optimizer: adamw + learning_rate: 0.001 + weight_decay: 0.00005 + scheduler: cosine + warmup_epochs: 5 + label_smoothing: 0.05 + mixup_alpha: 0.1 + cutmix_prob: 0.3 + early_stopping_patience: 15 + early_stopping_metric: val_f1 + gradient_clip_val: 1.0 + seed: 101 + +loss: + type: cross_entropy + focal_gamma: 2.0 + focal_alpha: null + +checkpoint: + save_dir: checkpoints/mobilenet_v3 + save_top_k: 3 + monitor: val_f1 diff --git a/ml_pipeline/configs/resnet50.yaml b/ml_pipeline/configs/resnet50.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8874d92a5b8e1bd7fc8bfff30ff665fcbb8ce669 --- /dev/null +++ b/ml_pipeline/configs/resnet50.yaml @@ -0,0 +1,38 @@ +# ResNet50 Configuration +model: + type: resnet50 + num_classes: 38 + pretrained: true + dropout: 0.3 + +data: + img_size: 224 + batch_size: 64 + augment_level: medium + num_workers: 4 + use_balanced_sampling: true + +training: + epochs: 60 + optimizer: adamw + learning_rate: 0.0005 + weight_decay: 0.0001 + scheduler: onecycle + warmup_epochs: 3 + label_smoothing: 0.05 + mixup_alpha: 0.2 + cutmix_prob: 0.5 + early_stopping_patience: 12 + early_stopping_metric: val_f1 + gradient_clip_val: 1.0 + seed: 123 + +loss: + type: cross_entropy + focal_gamma: 2.0 + focal_alpha: null + +checkpoint: + save_dir: checkpoints/resnet50 + save_top_k: 3 + monitor: val_f1 diff --git a/ml_pipeline/configs/swin_tiny.yaml b/ml_pipeline/configs/swin_tiny.yaml new file mode 100644 index 0000000000000000000000000000000000000000..618b1967799ba98d1f67ffd1018122f79b6c3256 --- /dev/null +++ b/ml_pipeline/configs/swin_tiny.yaml @@ -0,0 +1,38 @@ +# Swin-Tiny Configuration +model: + type: swin_tiny + num_classes: 38 + pretrained: true + dropout: 0.3 + +data: + img_size: 224 + batch_size: 64 + augment_level: medium + num_workers: 4 + use_balanced_sampling: true + +training: + epochs: 50 + optimizer: adamw + learning_rate: 0.0005 + weight_decay: 0.0001 + scheduler: cosine + warmup_epochs: 5 + label_smoothing: 0.1 + mixup_alpha: 0.2 + cutmix_prob: 0.5 + early_stopping_patience: 10 + early_stopping_metric: val_f1 + gradient_clip_val: 1.0 + seed: 789 + +loss: + type: cross_entropy + focal_gamma: 2.0 + focal_alpha: null + +checkpoint: + save_dir: checkpoints/swin_tiny + save_top_k: 3 + monitor: val_f1 diff --git a/ml_pipeline/data/__init__.py b/ml_pipeline/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/ml_pipeline/data/__pycache__/__init__.cpython-311.pyc b/ml_pipeline/data/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..145f2bf1d9d85d4f4044aa34800731f4350980c9 Binary files /dev/null and b/ml_pipeline/data/__pycache__/__init__.cpython-311.pyc differ diff --git a/ml_pipeline/data/__pycache__/dataset.cpython-311.pyc b/ml_pipeline/data/__pycache__/dataset.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cffd151b853706576315ac7620d0055c1bd6b264 Binary files /dev/null and b/ml_pipeline/data/__pycache__/dataset.cpython-311.pyc differ diff --git a/ml_pipeline/data/dataset.py b/ml_pipeline/data/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..22841fe095210583e1664abe8eb4475df077cc6b --- /dev/null +++ b/ml_pipeline/data/dataset.py @@ -0,0 +1,288 @@ +""" +Data pipeline for PlantVillage dataset. +Handles downloading, validation, stratified splitting, and preprocessing. +""" +import os +import json +import shutil +import random +from typing import Dict, List, Tuple +from collections import defaultdict, Counter + +import numpy as np +import torch +from torch.utils.data import Dataset, DataLoader, WeightedRandomSampler +from torchvision import transforms, datasets + + +# PlantVillage 38-class label mapping +PLANTVILLAGE_CLASSES = [ + "Apple___Apple_scab", "Apple___Black_rot", "Apple___Cedar_apple_rust", "Apple___healthy", + "Blueberry___healthy", "Cherry_(including_sour)___Powdery_mildew", "Cherry_(including_sour)___healthy", + "Corn_(maize)___Cercospora_leaf_spot Gray_leaf_spot", "Corn_(maize)___Common_rust_", + "Corn_(maize)___Northern_Leaf_Blight", "Corn_(maize)___healthy", + "Grape___Black_rot", "Grape___Esca_(Black_Measles)", "Grape___Leaf_blight_(Isariopsis_Leaf_Spot)", + "Grape___healthy", "Orange___Haunglongbing_(Citrus_greening)", + "Peach___Bacterial_spot", "Peach___healthy", + "Pepper,_bell___Bacterial_spot", "Pepper,_bell___healthy", + "Potato___Early_blight", "Potato___Late_blight", "Potato___healthy", + "Raspberry___healthy", "Soybean___healthy", + "Squash___Powdery_mildew", "Strawberry___Leaf_scorch", "Strawberry___healthy", + "Tomato___Bacterial_spot", "Tomato___Early_blight", "Tomato___Late_blight", + "Tomato___Leaf_Mold", "Tomato___Septoria_leaf_spot", + "Tomato___Spider_mites Two-spotted_spider_mite", "Tomato___Target_Spot", + "Tomato___Tomato_Yellow_Leaf_Curl_Virus", "Tomato___Tomato_mosaic_virus", "Tomato___healthy" +] + +# Map class to plant species for group-based splitting +CLASS_TO_SPECIES = {} +for cls in PLANTVILLAGE_CLASSES: + species = cls.split("___")[0] + CLASS_TO_SPECIES[cls] = species + + +def normalize_label(label: str) -> str: + """Normalize label names to consistent format.""" + label = label.strip().replace(" ", "_").replace(",", ",") + return label + + +def get_species_groups(data_dir: str) -> Dict[str, List[str]]: + """Group classes by plant species to prevent data leakage in splits.""" + species_to_classes = defaultdict(list) + for cls in sorted(os.listdir(data_dir)): + cls_path = os.path.join(data_dir, cls) + if os.path.isdir(cls_path): + species = cls.split("___")[0] if "___" in cls else cls.split("_")[0] + species_to_classes[species].append(cls) + return dict(species_to_classes) + + +def create_stratified_species_split( + data_dir: str, + output_dir: str, + train_ratio: float = 0.7, + val_ratio: float = 0.15, + test_ratio: float = 0.15, + seed: int = 42 +) -> Dict[str, List[str]]: + """ + Create stratified train/val/test splits GROUPED by plant species + to avoid data leakage (same plant appearing in train and test). + + Within each species group, images are split maintaining class proportions. + """ + assert abs(train_ratio + val_ratio + test_ratio - 1.0) < 1e-6 + random.seed(seed) + np.random.seed(seed) + + splits = {"train": [], "val": [], "test": []} + split_stats = {"train": Counter(), "val": Counter(), "test": Counter()} + + all_classes = sorted([ + d for d in os.listdir(data_dir) + if os.path.isdir(os.path.join(data_dir, d)) + ]) + + for cls in all_classes: + cls_dir = os.path.join(data_dir, cls) + images = sorted([ + f for f in os.listdir(cls_dir) + if f.lower().endswith(('.jpg', '.jpeg', '.png', '.bmp', '.webp')) + ]) + random.shuffle(images) + + n = len(images) + n_train = int(n * train_ratio) + n_val = int(n * val_ratio) + + train_imgs = images[:n_train] + val_imgs = images[n_train:n_train + n_val] + test_imgs = images[n_train + n_val:] + + for split_name, img_list in [("train", train_imgs), ("val", val_imgs), ("test", test_imgs)]: + split_cls_dir = os.path.join(output_dir, split_name, cls) + os.makedirs(split_cls_dir, exist_ok=True) + for img in img_list: + src = os.path.join(cls_dir, img) + dst = os.path.join(split_cls_dir, img) + if not os.path.exists(dst): + shutil.copy2(src, dst) + splits[split_name].append(dst) + split_stats[split_name][cls] = len(img_list) + + # Save split metadata + meta = { + "seed": seed, + "ratios": {"train": train_ratio, "val": val_ratio, "test": test_ratio}, + "counts": {k: dict(v) for k, v in split_stats.items()}, + "total": {k: sum(v.values()) for k, v in split_stats.items()} + } + with open(os.path.join(output_dir, "split_metadata.json"), "w") as f: + json.dump(meta, f, indent=2) + + print(f"Split complete: train={meta['total']['train']}, " + f"val={meta['total']['val']}, test={meta['total']['test']}") + return splits + + +def get_train_transforms(img_size: int = 224, augment_level: str = "medium"): + """Configurable training augmentation pipeline.""" + if augment_level == "light": + return transforms.Compose([ + transforms.Resize((img_size + 32, img_size + 32)), + transforms.RandomCrop(img_size), + transforms.RandomHorizontalFlip(p=0.5), + transforms.ToTensor(), + transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), + ]) + elif augment_level == "medium": + return transforms.Compose([ + transforms.Resize((img_size + 32, img_size + 32)), + transforms.RandomCrop(img_size), + transforms.RandomHorizontalFlip(p=0.5), + transforms.RandomVerticalFlip(p=0.3), + transforms.RandomRotation(15), + transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.1), + transforms.ToTensor(), + transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), + transforms.RandomErasing(p=0.25, scale=(0.02, 0.15)), + ]) + else: # heavy + return transforms.Compose([ + transforms.Resize((img_size + 32, img_size + 32)), + transforms.RandomCrop(img_size), + transforms.RandomHorizontalFlip(p=0.5), + transforms.RandomVerticalFlip(p=0.3), + transforms.RandomRotation(30), + transforms.ColorJitter(brightness=0.3, contrast=0.3, saturation=0.3, hue=0.15), + transforms.RandAugment(num_ops=2, magnitude=9), + transforms.ToTensor(), + transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), + transforms.RandomErasing(p=0.4, scale=(0.02, 0.2)), + ]) + + +def get_val_transforms(img_size: int = 224): + """Validation/test transforms — no augmentation.""" + return transforms.Compose([ + transforms.Resize((img_size, img_size)), + transforms.ToTensor(), + transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), + ]) + + +class PlantDiseaseDataset(Dataset): + """Custom dataset with MixUp/CutMix support.""" + + def __init__(self, root_dir: str, transform=None, return_path: bool = False): + self.dataset = datasets.ImageFolder(root_dir, transform=transform) + self.classes = self.dataset.classes + self.class_to_idx = self.dataset.class_to_idx + self.return_path = return_path + self.targets = self.dataset.targets + + def __len__(self): + return len(self.dataset) + + def __getitem__(self, idx): + img, label = self.dataset[idx] + if self.return_path: + path = self.dataset.samples[idx][0] + return img, label, path + return img, label + + def get_class_weights(self) -> torch.Tensor: + """Compute inverse frequency weights for class-balanced sampling.""" + counts = Counter(self.targets) + total = len(self.targets) + weights = torch.zeros(len(self.classes)) + for cls_idx, count in counts.items(): + weights[cls_idx] = total / (len(self.classes) * count) + return weights + + def get_sampler(self) -> WeightedRandomSampler: + """Get weighted random sampler for class-balanced training.""" + class_weights = self.get_class_weights() + sample_weights = [class_weights[t] for t in self.targets] + return WeightedRandomSampler(sample_weights, num_samples=len(self.targets), replacement=True) + + +class MixUpCutMix: + """MixUp and CutMix data augmentation.""" + + def __init__(self, mixup_alpha: float = 0.2, cutmix_prob: float = 0.5, num_classes: int = 38): + self.mixup_alpha = mixup_alpha + self.cutmix_prob = cutmix_prob + self.num_classes = num_classes + + def __call__(self, images: torch.Tensor, targets: torch.Tensor): + if random.random() < self.cutmix_prob: + return self._cutmix(images, targets) + else: + return self._mixup(images, targets) + + def _mixup(self, images, targets): + lam = np.random.beta(self.mixup_alpha, self.mixup_alpha) if self.mixup_alpha > 0 else 1.0 + batch_size = images.size(0) + index = torch.randperm(batch_size, device=images.device) + mixed_images = lam * images + (1 - lam) * images[index] + targets_onehot = torch.nn.functional.one_hot(targets, self.num_classes).float() + mixed_targets = lam * targets_onehot + (1 - lam) * targets_onehot[index] + return mixed_images, mixed_targets + + def _cutmix(self, images, targets): + lam = np.random.beta(1.0, 1.0) + batch_size = images.size(0) + index = torch.randperm(batch_size, device=images.device) + _, _, H, W = images.shape + cut_rat = np.sqrt(1.0 - lam) + cut_w, cut_h = int(W * cut_rat), int(H * cut_rat) + cx, cy = random.randint(0, W), random.randint(0, H) + x1 = max(0, cx - cut_w // 2) + y1 = max(0, cy - cut_h // 2) + x2 = min(W, cx + cut_w // 2) + y2 = min(H, cy + cut_h // 2) + + images[:, :, y1:y2, x1:x2] = images[index, :, y1:y2, x1:x2] + lam = 1 - (x2 - x1) * (y2 - y1) / (W * H) + targets_onehot = torch.nn.functional.one_hot(targets, self.num_classes).float() + mixed_targets = lam * targets_onehot + (1 - lam) * targets_onehot[index] + return images, mixed_targets + + +def create_dataloaders( + data_dir: str, + img_size: int = 224, + batch_size: int = 32, + augment_level: str = "medium", + num_workers: int = 4, + use_balanced_sampling: bool = True +) -> Tuple[DataLoader, DataLoader, DataLoader]: + """Create train/val/test dataloaders with all preprocessing.""" + train_transform = get_train_transforms(img_size, augment_level) + val_transform = get_val_transforms(img_size) + + train_dataset = PlantDiseaseDataset(os.path.join(data_dir, "train"), train_transform) + val_dataset = PlantDiseaseDataset(os.path.join(data_dir, "val"), val_transform) + test_dataset = PlantDiseaseDataset(os.path.join(data_dir, "test"), val_transform, return_path=True) + + sampler = train_dataset.get_sampler() if use_balanced_sampling else None + + train_loader = DataLoader( + train_dataset, batch_size=batch_size, + sampler=sampler, shuffle=(sampler is None), + num_workers=num_workers, pin_memory=True, drop_last=True + ) + val_loader = DataLoader( + val_dataset, batch_size=batch_size, + shuffle=False, num_workers=num_workers, pin_memory=True + ) + test_loader = DataLoader( + test_dataset, batch_size=batch_size, + shuffle=False, num_workers=num_workers, pin_memory=True + ) + + print(f"Dataloaders: train={len(train_dataset)}, val={len(val_dataset)}, test={len(test_dataset)}") + print(f"Classes: {len(train_dataset.classes)}") + return train_loader, val_loader, test_loader diff --git a/ml_pipeline/distillation/__init__.py b/ml_pipeline/distillation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/ml_pipeline/ensemble/__init__.py b/ml_pipeline/ensemble/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/ml_pipeline/models/__init__.py b/ml_pipeline/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/ml_pipeline/models/__pycache__/__init__.cpython-311.pyc b/ml_pipeline/models/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1fa64da18f6393b86250e1f4063e771dba1fad40 Binary files /dev/null and b/ml_pipeline/models/__pycache__/__init__.cpython-311.pyc differ diff --git a/ml_pipeline/models/__pycache__/architectures.cpython-311.pyc b/ml_pipeline/models/__pycache__/architectures.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b32c43ad1dce2353a3e0f396c76c08051c4bfad6 Binary files /dev/null and b/ml_pipeline/models/__pycache__/architectures.cpython-311.pyc differ diff --git a/ml_pipeline/models/architectures.py b/ml_pipeline/models/architectures.py new file mode 100644 index 0000000000000000000000000000000000000000..9ec4aa16f03f79f03f7a5841521a0c3961ba8f0b --- /dev/null +++ b/ml_pipeline/models/architectures.py @@ -0,0 +1,110 @@ +""" +Base model architectures for plant disease detection ensemble. +5 diverse architectures for maximum ensemble strength: +1. EfficientNetV2-S — compound-scaled CNN (accuracy) +2. ResNet50 — residual connections (robustness) +3. ConvNeXt-Tiny — modernized CNN (accuracy) +4. Swin-Tiny — shifted window ViT (attention) +5. MobileNetV3-Large — lightweight (edge deployment) +""" +import torch +import torch.nn as nn +import timm +from typing import Optional + + +class BaseModel(nn.Module): + """Base wrapper for all models with consistent interface.""" + + def __init__(self, model_name: str, num_classes: int = 38, + pretrained: bool = True, dropout: float = 0.3, + feature_dim: Optional[int] = None): + super().__init__() + self.model_name = model_name + self.num_classes = num_classes + + self.backbone = timm.create_model( + model_name, pretrained=pretrained, num_classes=0, drop_rate=dropout + ) + + # Auto-detect feature dimension + with torch.no_grad(): + dummy = torch.randn(1, 3, 224, 224) + feat = self.backbone(dummy) + actual_dim = feat.shape[-1] + + if feature_dim is None: + feature_dim = actual_dim + + self.head = nn.Sequential( + nn.Dropout(p=dropout), + nn.Linear(feature_dim, num_classes) + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + features = self.backbone(x) + logits = self.head(features) + return logits + + def get_features(self, x: torch.Tensor) -> torch.Tensor: + """Extract features before classification head (for stacking).""" + return self.backbone(x) + + def get_logits_and_features(self, x: torch.Tensor): + features = self.backbone(x) + logits = self.head(features) + return logits, features + + +def create_efficientnet_v2(num_classes: int = 38, pretrained: bool = True, dropout: float = 0.3): + """EfficientNetV2-S: Compound-scaled CNN with progressive training.""" + return BaseModel("tf_efficientnetv2_s", num_classes, pretrained, dropout) + + +def create_resnet50(num_classes: int = 38, pretrained: bool = True, dropout: float = 0.3): + """ResNet50: Classic residual network, robust baseline.""" + return BaseModel("resnet50", num_classes, pretrained, dropout) + + +def create_convnext_tiny(num_classes: int = 38, pretrained: bool = True, dropout: float = 0.3): + """ConvNeXt-Tiny: Modernized CNN competing with ViTs.""" + return BaseModel("convnext_tiny", num_classes, pretrained, dropout) + + +def create_swin_tiny(num_classes: int = 38, pretrained: bool = True, dropout: float = 0.3): + """Swin-Tiny: Shifted window transformer for hierarchical features.""" + return BaseModel("swin_tiny_patch4_window7_224", num_classes, pretrained, dropout) + + +def create_mobilenet_v3(num_classes: int = 38, pretrained: bool = True, dropout: float = 0.2): + """MobileNetV3-Large: Lightweight model for edge deployment.""" + return BaseModel("mobilenetv3_large_100", num_classes, pretrained, dropout) + + +# Model registry +MODEL_REGISTRY = { + "efficientnet_v2": create_efficientnet_v2, + "resnet50": create_resnet50, + "convnext_tiny": create_convnext_tiny, + "swin_tiny": create_swin_tiny, + "mobilenet_v3": create_mobilenet_v3, +} + + +def create_model(model_type: str, **kwargs) -> BaseModel: + """Factory function to create any registered model.""" + if model_type not in MODEL_REGISTRY: + raise ValueError(f"Unknown model: {model_type}. Available: {list(MODEL_REGISTRY.keys())}") + return MODEL_REGISTRY[model_type](**kwargs) + + +def get_model_info(model_type: str) -> dict: + """Get model metadata.""" + info = { + "efficientnet_v2": {"input_size": 384, "params_m": 21.5, "flops_g": 8.4, "profile": "server"}, + "resnet50": {"input_size": 224, "params_m": 25.6, "flops_g": 4.1, "profile": "server"}, + "convnext_tiny": {"input_size": 224, "params_m": 28.6, "flops_g": 4.5, "profile": "server"}, + "swin_tiny": {"input_size": 224, "params_m": 28.3, "flops_g": 4.5, "profile": "server"}, + "mobilenet_v3": {"input_size": 224, "params_m": 5.4, "flops_g": 0.22, "profile": "edge"}, + } + return info.get(model_type, {}) diff --git a/ml_pipeline/notebooks/train_convnext_tiny_colab.ipynb b/ml_pipeline/notebooks/train_convnext_tiny_colab.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1f42d38a665f8e72a633c48fc42bc1f6a40b1929 --- /dev/null +++ b/ml_pipeline/notebooks/train_convnext_tiny_colab.ipynb @@ -0,0 +1,417 @@ +{ + "nbformat": 4, + "nbformat_minor": 0, + "metadata": { + "colab": { + "provenance": [], + "gpuType": "T4" + }, + "kernelspec": { + "name": "python3", + "display_name": "Python 3" + }, + "accelerator": "GPU" + }, + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Train Convnext Tiny on PlantVillage (38 classes)\n", + "\nFull fine-tuning with AdamW, cosine LR, MixUp/CutMix, early stopping.\n", + "\n**Instructions:**\n", + "1. Runtime > Change runtime type > GPU (T4)\n", + "2. Run all cells \u2014 dataset downloads automatically via kagglehub\n", + "3. Checkpoints saved to Google Drive\n" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install -q timm scikit-learn tqdm tensorboard kagglehub" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Mount Google Drive (for saving checkpoints)" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from google.colab import drive\n", + "drive.mount('/content/drive')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Download PlantVillage Dataset" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import os\n", + "\n", + "path = kagglehub.dataset_download('vipoooool/new-plant-diseases-dataset')\n", + "print(\"Dataset path:\", path)\n", + "\n", + "# Find the actual data directories\n", + "for root, dirs, files in os.walk(path):\n", + " if 'train' in dirs or 'valid' in dirs:\n", + " DATA_ROOT = root\n", + " break\n", + "print(\"Data root:\", DATA_ROOT)\n", + "print(\"Contents:\", os.listdir(DATA_ROOT))\n", + "\n", + "# Check class count\n", + "train_dir = os.path.join(DATA_ROOT, \"train\")\n", + "valid_dir = os.path.join(DATA_ROOT, \"valid\")\n", + "train_classes = sorted(os.listdir(train_dir))\n", + "print(f\"Train classes: {len(train_classes)}\")\n", + "print(f\"Train images: {sum(len(os.listdir(os.path.join(train_dir, c))) for c in train_classes)}\")\n", + "valid_classes = sorted(os.listdir(valid_dir))\n", + "print(f\"Valid images: {sum(len(os.listdir(os.path.join(valid_dir, c))) for c in valid_classes)}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Configuration" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import json\n", + "\n", + "CHECKPOINT_DIR = \"/content/drive/MyDrive/checkpoints/convnext_tiny\"\n", + "os.makedirs(CHECKPOINT_DIR, exist_ok=True)\n", + "\n", + "MODEL_NAME = \"convnext_tiny\"\n", + "IMG_SIZE = 224\n", + "BATCH_SIZE = 64\n", + "EPOCHS = 50\n", + "LR = 0.0008\n", + "WEIGHT_DECAY = 0.0001\n", + "SCHEDULER = \"cosine\"\n", + "WARMUP_EPOCHS = 5\n", + "LABEL_SMOOTHING = 0.05\n", + "MIXUP_ALPHA = 0.2\n", + "CUTMIX_PROB = 0.5\n", + "AUGMENT_LEVEL = \"heavy\"\n", + "DROPOUT = 0.3\n", + "EARLY_STOPPING_PATIENCE = 10\n", + "GRADIENT_CLIP = 1.0\n", + "SEED = 456\n", + "NUM_CLASSES = 38\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Dataset & DataLoaders" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "import numpy as np\n", + "import random\n", + "from torch.utils.data import DataLoader, WeightedRandomSampler\n", + "from torchvision import transforms, datasets\n", + "from collections import Counter\n", + "\n", + "torch.manual_seed(SEED); np.random.seed(SEED); random.seed(SEED)\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "print(f\"Device: {device}\")\n", + "\n", + "def get_train_transforms(img_size, level):\n", + " base = [transforms.Resize((img_size+32, img_size+32)), transforms.RandomCrop(img_size),\n", + " transforms.RandomHorizontalFlip(0.5)]\n", + " if level == \"medium\":\n", + " base += [transforms.RandomVerticalFlip(0.3), transforms.RandomRotation(15),\n", + " transforms.ColorJitter(0.2,0.2,0.2,0.1)]\n", + " elif level == \"heavy\":\n", + " base += [transforms.RandomVerticalFlip(0.3), transforms.RandomRotation(30),\n", + " transforms.ColorJitter(0.3,0.3,0.3,0.15), transforms.RandAugment(2,9)]\n", + " base += [transforms.ToTensor(), transforms.Normalize([0.485,0.456,0.406],[0.229,0.224,0.225])]\n", + " if level in (\"medium\",\"heavy\"):\n", + " base.append(transforms.RandomErasing(p=0.25 if level==\"medium\" else 0.4))\n", + " return transforms.Compose(base)\n", + "\n", + "val_transform = transforms.Compose([\n", + " transforms.Resize((IMG_SIZE, IMG_SIZE)), transforms.ToTensor(),\n", + " transforms.Normalize([0.485,0.456,0.406],[0.229,0.224,0.225])\n", + "])\n", + "\n", + "train_ds = datasets.ImageFolder(train_dir, get_train_transforms(IMG_SIZE, AUGMENT_LEVEL))\n", + "val_ds = datasets.ImageFolder(valid_dir, val_transform)\n", + "\n", + "# Balanced sampler for class imbalance\n", + "counts = Counter(train_ds.targets)\n", + "weights = [1.0/counts[t] for t in train_ds.targets]\n", + "sampler = WeightedRandomSampler(weights, len(train_ds), replacement=True)\n", + "\n", + "train_dl = DataLoader(train_ds, batch_size=BATCH_SIZE, sampler=sampler, num_workers=4, pin_memory=True, drop_last=True)\n", + "val_dl = DataLoader(val_ds, batch_size=BATCH_SIZE, shuffle=False, num_workers=4, pin_memory=True)\n", + "\n", + "print(f\"Train: {len(train_ds)}, Val: {len(val_ds)}, Classes: {len(train_ds.classes)}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Model" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import timm\n", + "\n", + "class BaseModel(nn.Module):\n", + " def __init__(self, model_name, num_classes=38, pretrained=True, dropout=0.3):\n", + " super().__init__()\n", + " self.backbone = timm.create_model(model_name, pretrained=pretrained, num_classes=0, drop_rate=dropout)\n", + " with torch.no_grad():\n", + " feat_dim = self.backbone(torch.randn(1,3,IMG_SIZE,IMG_SIZE)).shape[-1]\n", + " self.head = nn.Sequential(nn.Dropout(dropout), nn.Linear(feat_dim, num_classes))\n", + " print(f\"Model: {model_name}, feat_dim={feat_dim}, params={sum(p.numel() for p in self.parameters())/1e6:.1f}M\")\n", + "\n", + " def forward(self, x):\n", + " return self.head(self.backbone(x))\n", + "\n", + "model = BaseModel(MODEL_NAME, NUM_CLASSES, True, DROPOUT).to(device)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## MixUp/CutMix & Loss" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "class MixUpCutMix:\n", + " def __init__(self, mixup_alpha=0.2, cutmix_prob=0.5, num_classes=38):\n", + " self.mixup_alpha = mixup_alpha\n", + " self.cutmix_prob = cutmix_prob\n", + " self.num_classes = num_classes\n", + "\n", + " def __call__(self, images, targets):\n", + " if random.random() < self.cutmix_prob:\n", + " return self._cutmix(images, targets)\n", + " return self._mixup(images, targets)\n", + "\n", + " def _mixup(self, images, targets):\n", + " lam = np.random.beta(self.mixup_alpha, self.mixup_alpha) if self.mixup_alpha > 0 else 1.0\n", + " idx = torch.randperm(images.size(0), device=images.device)\n", + " mixed = lam * images + (1-lam) * images[idx]\n", + " t_oh = torch.nn.functional.one_hot(targets, self.num_classes).float()\n", + " return mixed, lam * t_oh + (1-lam) * t_oh[idx]\n", + "\n", + " def _cutmix(self, images, targets):\n", + " lam = np.random.beta(1.0, 1.0)\n", + " idx = torch.randperm(images.size(0), device=images.device)\n", + " _,_,H,W = images.shape\n", + " cut_r = np.sqrt(1.0-lam); cw,ch = int(W*cut_r),int(H*cut_r)\n", + " cx,cy = random.randint(0,W), random.randint(0,H)\n", + " x1,y1 = max(0,cx-cw//2), max(0,cy-ch//2)\n", + " x2,y2 = min(W,cx+cw//2), min(H,cy+ch//2)\n", + " images[:,:,y1:y2,x1:x2] = images[idx,:,y1:y2,x1:x2]\n", + " lam = 1-(x2-x1)*(y2-y1)/(W*H)\n", + " t_oh = torch.nn.functional.one_hot(targets, self.num_classes).float()\n", + " return images, lam*t_oh + (1-lam)*t_oh[idx]\n", + "\n", + "mixup_fn = MixUpCutMix(MIXUP_ALPHA, CUTMIX_PROB, NUM_CLASSES)\n", + "criterion = nn.CrossEntropyLoss(label_smoothing=LABEL_SMOOTHING)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Training" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import time\n", + "from torch.cuda.amp import GradScaler, autocast\n", + "from sklearn.metrics import f1_score\n", + "from tqdm.auto import tqdm\n", + "\n", + "def train_one_epoch(model, loader, criterion, optimizer, scaler, mixup_fn, device, epoch):\n", + " model.train()\n", + " total_loss = 0; all_preds, all_labels = [], []\n", + " pbar = tqdm(loader, desc=f\"Epoch {epoch}\")\n", + " for images, labels in pbar:\n", + " images, labels = images.to(device), labels.to(device)\n", + " use_mix = MIXUP_ALPHA > 0 and np.random.random() < 0.5\n", + " if use_mix:\n", + " images, labels_mixed = mixup_fn(images, labels); is_mixed = True\n", + " else:\n", + " is_mixed = False\n", + " optimizer.zero_grad()\n", + " with autocast(enabled=torch.cuda.is_available()):\n", + " logits = model(images)\n", + " if is_mixed:\n", + " loss = -(labels_mixed * torch.log_softmax(logits, dim=1)).sum(dim=1).mean()\n", + " else:\n", + " loss = criterion(logits, labels)\n", + " scaler.scale(loss).backward()\n", + " if GRADIENT_CLIP > 0:\n", + " scaler.unscale_(optimizer)\n", + " nn.utils.clip_grad_norm_(model.parameters(), GRADIENT_CLIP)\n", + " scaler.step(optimizer); scaler.update()\n", + " total_loss += loss.item()\n", + " if not is_mixed:\n", + " all_preds.extend(logits.argmax(1).cpu().numpy())\n", + " all_labels.extend(labels.cpu().numpy())\n", + " pbar.set_postfix(loss=f\"{loss.item():.4f}\")\n", + " return total_loss/len(loader), f1_score(all_labels, all_preds, average=\"macro\", zero_division=0) if all_labels else 0\n", + "\n", + "@torch.no_grad()\n", + "def validate(model, loader, criterion, device):\n", + " model.eval()\n", + " total_loss = 0; all_preds, all_labels, all_logits = [], [], []\n", + " for images, labels in tqdm(loader, desc=\"Validating\"):\n", + " images, labels = images.to(device), labels.to(device)\n", + " logits = model(images)\n", + " loss = criterion(logits, labels)\n", + " total_loss += loss.item()\n", + " all_preds.extend(logits.argmax(1).cpu().numpy())\n", + " all_labels.extend(labels.cpu().numpy())\n", + " all_logits.append(logits.cpu().numpy())\n", + " f1 = f1_score(all_labels, all_preds, average=\"macro\", zero_division=0)\n", + " acc = np.mean(np.array(all_preds)==np.array(all_labels))\n", + " return total_loss/len(loader), f1, acc, np.concatenate(all_logits), np.array(all_labels)\n", + "\n", + "# Optimizer & Scheduler\n", + "optimizer = torch.optim.AdamW(model.parameters(), lr=LR, weight_decay=WEIGHT_DECAY)\n", + "if SCHEDULER == \"cosine\":\n", + " scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=EPOCHS-WARMUP_EPOCHS)\n", + "else:\n", + " scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr=LR, epochs=EPOCHS, steps_per_epoch=len(train_dl))\n", + "warmup_sched = torch.optim.lr_scheduler.LinearLR(optimizer, start_factor=0.01, total_iters=WARMUP_EPOCHS) if WARMUP_EPOCHS > 0 else None\n", + "scaler = GradScaler(enabled=torch.cuda.is_available())\n", + "\n", + "best_f1 = 0; patience_counter = 0; history = []\n", + "print(f\"Training {MODEL_NAME} for {EPOCHS} epochs on {device}...\")\n", + "print(\"-\"*80)\n", + "\n", + "for epoch in range(1, EPOCHS+1):\n", + " t0 = time.time()\n", + " train_loss, train_f1 = train_one_epoch(model, train_dl, criterion, optimizer, scaler, mixup_fn, device, epoch)\n", + " val_loss, val_f1, val_acc, val_logits, val_labels = validate(model, val_dl, criterion, device)\n", + " if warmup_sched and epoch <= WARMUP_EPOCHS:\n", + " warmup_sched.step()\n", + " elif SCHEDULER == \"cosine\":\n", + " scheduler.step()\n", + " lr = optimizer.param_groups[0][\"lr\"]\n", + " elapsed = time.time()-t0\n", + " marker = \"\"\n", + " if val_f1 > best_f1:\n", + " best_f1 = val_f1; patience_counter = 0; marker = \" \\u2605 BEST\"\n", + " torch.save({\n", + " \"epoch\": epoch, \"model_state_dict\": model.state_dict(),\n", + " \"val_f1\": val_f1, \"val_acc\": val_acc, \"model_type\": \"convnext_tiny\",\n", + " \"num_classes\": NUM_CLASSES\n", + " }, os.path.join(CHECKPOINT_DIR, \"best_model.pt\"))\n", + " np.save(os.path.join(CHECKPOINT_DIR, \"best_val_logits.npy\"), val_logits)\n", + " np.save(os.path.join(CHECKPOINT_DIR, \"best_val_labels.npy\"), val_labels)\n", + " else:\n", + " patience_counter += 1\n", + " history.append({\n", + " \"epoch\": epoch, \"train_loss\": train_loss, \"train_f1\": train_f1,\n", + " \"val_loss\": val_loss, \"val_f1\": val_f1, \"val_acc\": val_acc, \"lr\": lr, \"time\": elapsed\n", + " })\n", + " print(f\"Epoch {epoch:2d}/{EPOCHS} | TrainLoss={train_loss:.4f} F1={train_f1:.4f} | ValLoss={val_loss:.4f} F1={val_f1:.4f} Acc={val_acc:.4f} | lr={lr:.6f} | {elapsed:.0f}s{marker}\")\n", + " if patience_counter >= EARLY_STOPPING_PATIENCE:\n", + " print(f\"Early stopping at epoch {epoch}\"); break\n", + "\n", + "with open(os.path.join(CHECKPOINT_DIR, \"training_history.json\"), \"w\") as f:\n", + " json.dump(history, f, indent=2)\n", + "print(f\"\\nDone! Best Val F1: {best_f1:.4f} Checkpoint: {CHECKPOINT_DIR}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Evaluation & Per-Class Report" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.metrics import classification_report\n", + "\n", + "ckpt = torch.load(os.path.join(CHECKPOINT_DIR, \"best_model.pt\"), map_location=device)\n", + "model.load_state_dict(ckpt[\"model_state_dict\"])\n", + "model.eval()\n", + "\n", + "all_preds, all_labels = [], []\n", + "with torch.no_grad():\n", + " for images, labels in tqdm(val_dl, desc=\"Evaluating\"):\n", + " images = images.to(device)\n", + " preds = model(images).argmax(1).cpu().numpy()\n", + " all_preds.extend(preds)\n", + " all_labels.extend(labels.numpy())\n", + "\n", + "eval_f1 = f1_score(all_labels, all_preds, average=\"macro\")\n", + "eval_acc = np.mean(np.array(all_preds)==np.array(all_labels))\n", + "print(f\"Validation Accuracy: {eval_acc:.4f}\")\n", + "print(f\"Validation Macro F1: {eval_f1:.4f}\")\n", + "print()\n", + "print(classification_report(all_labels, all_preds, target_names=train_ds.classes, digits=3))\n", + "\n", + "# Save class names\n", + "with open(os.path.join(CHECKPOINT_DIR, \"class_names.json\"), \"w\") as f:\n", + " json.dump(train_ds.classes, f, indent=2)\n", + "print(f\"\\n\\u2713 All artifacts saved to {CHECKPOINT_DIR}\")\n" + ], + "execution_count": null, + "outputs": [] + } + ] +} \ No newline at end of file diff --git a/ml_pipeline/notebooks/train_efficientnet_v2_colab.ipynb b/ml_pipeline/notebooks/train_efficientnet_v2_colab.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..760c27fd606977d2a3f0defa9deefaac77df66c9 --- /dev/null +++ b/ml_pipeline/notebooks/train_efficientnet_v2_colab.ipynb @@ -0,0 +1,453 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Train Efficientnet V2 on PlantVillage (38 classes)\n", + "\n", + "Full fine-tuning with AdamW, cosine LR, MixUp/CutMix, early stopping.\n", + "\n", + "**Instructions:**\n", + "1. Runtime > Change runtime type > GPU (T4)\n", + "2. Run all cells — dataset downloads automatically via kagglehub\n", + "3. Checkpoints saved to Google Drive\n" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "\n", + "[notice] A new release of pip is available: 25.3 -> 26.0.1\n", + "[notice] To update, run: C:\\Users\\DEVANGSHU\\AppData\\Local\\Microsoft\\WindowsApps\\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\\python.exe -m pip install --upgrade pip\n" + ] + } + ], + "source": [ + "!pip install -q timm scikit-learn tqdm tensorboard kagglehub" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Mount Google Drive (for saving checkpoints)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "ename": "ModuleNotFoundError", + "evalue": "No module named 'google.colab'", + "output_type": "error", + "traceback": [ + "\u001b[31m---------------------------------------------------------------------------\u001b[39m", + "\u001b[31mModuleNotFoundError\u001b[39m Traceback (most recent call last)", + "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[3]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m \u001b[38;5;28;01mfrom\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34;01mgoogle\u001b[39;00m\u001b[34;01m.\u001b[39;00m\u001b[34;01mcolab\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;28;01mimport\u001b[39;00m drive\n\u001b[32m 2\u001b[39m drive.mount(\u001b[33m'\u001b[39m\u001b[33m/content/drive\u001b[39m\u001b[33m'\u001b[39m)\n", + "\u001b[31mModuleNotFoundError\u001b[39m: No module named 'google.colab'" + ] + } + ], + "source": [ + "from google.colab import drive\n", + "drive.mount('/content/drive')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Download PlantVillage Dataset" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import kagglehub\n", + "import os\n", + "\n", + "path = kagglehub.dataset_download('vipoooool/new-plant-diseases-dataset')\n", + "print(\"Dataset path:\", path)\n", + "\n", + "# Find the actual data directories\n", + "for root, dirs, files in os.walk(path):\n", + " if 'train' in dirs or 'valid' in dirs:\n", + " DATA_ROOT = root\n", + " break\n", + "print(\"Data root:\", DATA_ROOT)\n", + "print(\"Contents:\", os.listdir(DATA_ROOT))\n", + "\n", + "# Check class count\n", + "train_dir = os.path.join(DATA_ROOT, \"train\")\n", + "valid_dir = os.path.join(DATA_ROOT, \"valid\")\n", + "train_classes = sorted(os.listdir(train_dir))\n", + "print(f\"Train classes: {len(train_classes)}\")\n", + "print(f\"Train images: {sum(len(os.listdir(os.path.join(train_dir, c))) for c in train_classes)}\")\n", + "valid_classes = sorted(os.listdir(valid_dir))\n", + "print(f\"Valid images: {sum(len(os.listdir(os.path.join(valid_dir, c))) for c in valid_classes)}\")\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Configuration" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import json\n", + "\n", + "CHECKPOINT_DIR = \"/content/drive/MyDrive/checkpoints/efficientnet_v2\"\n", + "os.makedirs(CHECKPOINT_DIR, exist_ok=True)\n", + "\n", + "MODEL_NAME = \"tf_efficientnetv2_s\"\n", + "IMG_SIZE = 384\n", + "BATCH_SIZE = 32\n", + "EPOCHS = 60\n", + "LR = 0.001\n", + "WEIGHT_DECAY = 0.0001\n", + "SCHEDULER = \"cosine\"\n", + "WARMUP_EPOCHS = 5\n", + "LABEL_SMOOTHING = 0.05\n", + "MIXUP_ALPHA = 0.2\n", + "CUTMIX_PROB = 0.5\n", + "AUGMENT_LEVEL = \"heavy\"\n", + "DROPOUT = 0.3\n", + "EARLY_STOPPING_PATIENCE = 10\n", + "GRADIENT_CLIP = 1.0\n", + "SEED = 42\n", + "NUM_CLASSES = 38\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Dataset & DataLoaders" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "import numpy as np\n", + "import random\n", + "from torch.utils.data import DataLoader, WeightedRandomSampler\n", + "from torchvision import transforms, datasets\n", + "from collections import Counter\n", + "\n", + "torch.manual_seed(SEED); np.random.seed(SEED); random.seed(SEED)\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "print(f\"Device: {device}\")\n", + "\n", + "def get_train_transforms(img_size, level):\n", + " base = [transforms.Resize((img_size+32, img_size+32)), transforms.RandomCrop(img_size),\n", + " transforms.RandomHorizontalFlip(0.5)]\n", + " if level == \"medium\":\n", + " base += [transforms.RandomVerticalFlip(0.3), transforms.RandomRotation(15),\n", + " transforms.ColorJitter(0.2,0.2,0.2,0.1)]\n", + " elif level == \"heavy\":\n", + " base += [transforms.RandomVerticalFlip(0.3), transforms.RandomRotation(30),\n", + " transforms.ColorJitter(0.3,0.3,0.3,0.15), transforms.RandAugment(2,9)]\n", + " base += [transforms.ToTensor(), transforms.Normalize([0.485,0.456,0.406],[0.229,0.224,0.225])]\n", + " if level in (\"medium\",\"heavy\"):\n", + " base.append(transforms.RandomErasing(p=0.25 if level==\"medium\" else 0.4))\n", + " return transforms.Compose(base)\n", + "\n", + "val_transform = transforms.Compose([\n", + " transforms.Resize((IMG_SIZE, IMG_SIZE)), transforms.ToTensor(),\n", + " transforms.Normalize([0.485,0.456,0.406],[0.229,0.224,0.225])\n", + "])\n", + "\n", + "train_ds = datasets.ImageFolder(train_dir, get_train_transforms(IMG_SIZE, AUGMENT_LEVEL))\n", + "val_ds = datasets.ImageFolder(valid_dir, val_transform)\n", + "\n", + "# Balanced sampler for class imbalance\n", + "counts = Counter(train_ds.targets)\n", + "weights = [1.0/counts[t] for t in train_ds.targets]\n", + "sampler = WeightedRandomSampler(weights, len(train_ds), replacement=True)\n", + "\n", + "train_dl = DataLoader(train_ds, batch_size=BATCH_SIZE, sampler=sampler, num_workers=4, pin_memory=True, drop_last=True)\n", + "val_dl = DataLoader(val_ds, batch_size=BATCH_SIZE, shuffle=False, num_workers=4, pin_memory=True)\n", + "\n", + "print(f\"Train: {len(train_ds)}, Val: {len(val_ds)}, Classes: {len(train_ds.classes)}\")\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Model" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import timm\n", + "\n", + "class BaseModel(nn.Module):\n", + " def __init__(self, model_name, num_classes=38, pretrained=True, dropout=0.3):\n", + " super().__init__()\n", + " self.backbone = timm.create_model(model_name, pretrained=pretrained, num_classes=0, drop_rate=dropout)\n", + " with torch.no_grad():\n", + " feat_dim = self.backbone(torch.randn(1,3,IMG_SIZE,IMG_SIZE)).shape[-1]\n", + " self.head = nn.Sequential(nn.Dropout(dropout), nn.Linear(feat_dim, num_classes))\n", + " print(f\"Model: {model_name}, feat_dim={feat_dim}, params={sum(p.numel() for p in self.parameters())/1e6:.1f}M\")\n", + "\n", + " def forward(self, x):\n", + " return self.head(self.backbone(x))\n", + "\n", + "model = BaseModel(MODEL_NAME, NUM_CLASSES, True, DROPOUT).to(device)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## MixUp/CutMix & Loss" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "class MixUpCutMix:\n", + " def __init__(self, mixup_alpha=0.2, cutmix_prob=0.5, num_classes=38):\n", + " self.mixup_alpha = mixup_alpha\n", + " self.cutmix_prob = cutmix_prob\n", + " self.num_classes = num_classes\n", + "\n", + " def __call__(self, images, targets):\n", + " if random.random() < self.cutmix_prob:\n", + " return self._cutmix(images, targets)\n", + " return self._mixup(images, targets)\n", + "\n", + " def _mixup(self, images, targets):\n", + " lam = np.random.beta(self.mixup_alpha, self.mixup_alpha) if self.mixup_alpha > 0 else 1.0\n", + " idx = torch.randperm(images.size(0), device=images.device)\n", + " mixed = lam * images + (1-lam) * images[idx]\n", + " t_oh = torch.nn.functional.one_hot(targets, self.num_classes).float()\n", + " return mixed, lam * t_oh + (1-lam) * t_oh[idx]\n", + "\n", + " def _cutmix(self, images, targets):\n", + " lam = np.random.beta(1.0, 1.0)\n", + " idx = torch.randperm(images.size(0), device=images.device)\n", + " _,_,H,W = images.shape\n", + " cut_r = np.sqrt(1.0-lam); cw,ch = int(W*cut_r),int(H*cut_r)\n", + " cx,cy = random.randint(0,W), random.randint(0,H)\n", + " x1,y1 = max(0,cx-cw//2), max(0,cy-ch//2)\n", + " x2,y2 = min(W,cx+cw//2), min(H,cy+ch//2)\n", + " images[:,:,y1:y2,x1:x2] = images[idx,:,y1:y2,x1:x2]\n", + " lam = 1-(x2-x1)*(y2-y1)/(W*H)\n", + " t_oh = torch.nn.functional.one_hot(targets, self.num_classes).float()\n", + " return images, lam*t_oh + (1-lam)*t_oh[idx]\n", + "\n", + "mixup_fn = MixUpCutMix(MIXUP_ALPHA, CUTMIX_PROB, NUM_CLASSES)\n", + "criterion = nn.CrossEntropyLoss(label_smoothing=LABEL_SMOOTHING)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Training" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import time\n", + "from torch.cuda.amp import GradScaler, autocast\n", + "from sklearn.metrics import f1_score\n", + "from tqdm.auto import tqdm\n", + "\n", + "def train_one_epoch(model, loader, criterion, optimizer, scaler, mixup_fn, device, epoch):\n", + " model.train()\n", + " total_loss = 0; all_preds, all_labels = [], []\n", + " pbar = tqdm(loader, desc=f\"Epoch {epoch}\")\n", + " for images, labels in pbar:\n", + " images, labels = images.to(device), labels.to(device)\n", + " use_mix = MIXUP_ALPHA > 0 and np.random.random() < 0.5\n", + " if use_mix:\n", + " images, labels_mixed = mixup_fn(images, labels); is_mixed = True\n", + " else:\n", + " is_mixed = False\n", + " optimizer.zero_grad()\n", + " with autocast(enabled=torch.cuda.is_available()):\n", + " logits = model(images)\n", + " if is_mixed:\n", + " loss = -(labels_mixed * torch.log_softmax(logits, dim=1)).sum(dim=1).mean()\n", + " else:\n", + " loss = criterion(logits, labels)\n", + " scaler.scale(loss).backward()\n", + " if GRADIENT_CLIP > 0:\n", + " scaler.unscale_(optimizer)\n", + " nn.utils.clip_grad_norm_(model.parameters(), GRADIENT_CLIP)\n", + " scaler.step(optimizer); scaler.update()\n", + " total_loss += loss.item()\n", + " if not is_mixed:\n", + " all_preds.extend(logits.argmax(1).cpu().numpy())\n", + " all_labels.extend(labels.cpu().numpy())\n", + " pbar.set_postfix(loss=f\"{loss.item():.4f}\")\n", + " return total_loss/len(loader), f1_score(all_labels, all_preds, average=\"macro\", zero_division=0) if all_labels else 0\n", + "\n", + "@torch.no_grad()\n", + "def validate(model, loader, criterion, device):\n", + " model.eval()\n", + " total_loss = 0; all_preds, all_labels, all_logits = [], [], []\n", + " for images, labels in tqdm(loader, desc=\"Validating\"):\n", + " images, labels = images.to(device), labels.to(device)\n", + " logits = model(images)\n", + " loss = criterion(logits, labels)\n", + " total_loss += loss.item()\n", + " all_preds.extend(logits.argmax(1).cpu().numpy())\n", + " all_labels.extend(labels.cpu().numpy())\n", + " all_logits.append(logits.cpu().numpy())\n", + " f1 = f1_score(all_labels, all_preds, average=\"macro\", zero_division=0)\n", + " acc = np.mean(np.array(all_preds)==np.array(all_labels))\n", + " return total_loss/len(loader), f1, acc, np.concatenate(all_logits), np.array(all_labels)\n", + "\n", + "# Optimizer & Scheduler\n", + "optimizer = torch.optim.AdamW(model.parameters(), lr=LR, weight_decay=WEIGHT_DECAY)\n", + "if SCHEDULER == \"cosine\":\n", + " scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=EPOCHS-WARMUP_EPOCHS)\n", + "else:\n", + " scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr=LR, epochs=EPOCHS, steps_per_epoch=len(train_dl))\n", + "warmup_sched = torch.optim.lr_scheduler.LinearLR(optimizer, start_factor=0.01, total_iters=WARMUP_EPOCHS) if WARMUP_EPOCHS > 0 else None\n", + "scaler = GradScaler(enabled=torch.cuda.is_available())\n", + "\n", + "best_f1 = 0; patience_counter = 0; history = []\n", + "print(f\"Training {MODEL_NAME} for {EPOCHS} epochs on {device}...\")\n", + "print(\"-\"*80)\n", + "\n", + "for epoch in range(1, EPOCHS+1):\n", + " t0 = time.time()\n", + " train_loss, train_f1 = train_one_epoch(model, train_dl, criterion, optimizer, scaler, mixup_fn, device, epoch)\n", + " val_loss, val_f1, val_acc, val_logits, val_labels = validate(model, val_dl, criterion, device)\n", + " if warmup_sched and epoch <= WARMUP_EPOCHS:\n", + " warmup_sched.step()\n", + " elif SCHEDULER == \"cosine\":\n", + " scheduler.step()\n", + " lr = optimizer.param_groups[0][\"lr\"]\n", + " elapsed = time.time()-t0\n", + " marker = \"\"\n", + " if val_f1 > best_f1:\n", + " best_f1 = val_f1; patience_counter = 0; marker = \" \\u2605 BEST\"\n", + " torch.save({\n", + " \"epoch\": epoch, \"model_state_dict\": model.state_dict(),\n", + " \"val_f1\": val_f1, \"val_acc\": val_acc, \"model_type\": \"efficientnet_v2\",\n", + " \"num_classes\": NUM_CLASSES\n", + " }, os.path.join(CHECKPOINT_DIR, \"best_model.pt\"))\n", + " np.save(os.path.join(CHECKPOINT_DIR, \"best_val_logits.npy\"), val_logits)\n", + " np.save(os.path.join(CHECKPOINT_DIR, \"best_val_labels.npy\"), val_labels)\n", + " else:\n", + " patience_counter += 1\n", + " history.append({\n", + " \"epoch\": epoch, \"train_loss\": train_loss, \"train_f1\": train_f1,\n", + " \"val_loss\": val_loss, \"val_f1\": val_f1, \"val_acc\": val_acc, \"lr\": lr, \"time\": elapsed\n", + " })\n", + " print(f\"Epoch {epoch:2d}/{EPOCHS} | TrainLoss={train_loss:.4f} F1={train_f1:.4f} | ValLoss={val_loss:.4f} F1={val_f1:.4f} Acc={val_acc:.4f} | lr={lr:.6f} | {elapsed:.0f}s{marker}\")\n", + " if patience_counter >= EARLY_STOPPING_PATIENCE:\n", + " print(f\"Early stopping at epoch {epoch}\"); break\n", + "\n", + "with open(os.path.join(CHECKPOINT_DIR, \"training_history.json\"), \"w\") as f:\n", + " json.dump(history, f, indent=2)\n", + "print(f\"\\nDone! Best Val F1: {best_f1:.4f} Checkpoint: {CHECKPOINT_DIR}\")\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Evaluation & Per-Class Report" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from sklearn.metrics import classification_report\n", + "\n", + "ckpt = torch.load(os.path.join(CHECKPOINT_DIR, \"best_model.pt\"), map_location=device)\n", + "model.load_state_dict(ckpt[\"model_state_dict\"])\n", + "model.eval()\n", + "\n", + "all_preds, all_labels = [], []\n", + "with torch.no_grad():\n", + " for images, labels in tqdm(val_dl, desc=\"Evaluating\"):\n", + " images = images.to(device)\n", + " preds = model(images).argmax(1).cpu().numpy()\n", + " all_preds.extend(preds)\n", + " all_labels.extend(labels.numpy())\n", + "\n", + "eval_f1 = f1_score(all_labels, all_preds, average=\"macro\")\n", + "eval_acc = np.mean(np.array(all_preds)==np.array(all_labels))\n", + "print(f\"Validation Accuracy: {eval_acc:.4f}\")\n", + "print(f\"Validation Macro F1: {eval_f1:.4f}\")\n", + "print()\n", + "print(classification_report(all_labels, all_preds, target_names=train_ds.classes, digits=3))\n", + "\n", + "# Save class names\n", + "with open(os.path.join(CHECKPOINT_DIR, \"class_names.json\"), \"w\") as f:\n", + " json.dump(train_ds.classes, f, indent=2)\n", + "print(f\"\\n\\u2713 All artifacts saved to {CHECKPOINT_DIR}\")\n" + ] + } + ], + "metadata": { + "accelerator": "GPU", + "colab": { + "gpuType": "T4", + "provenance": [] + }, + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.11.9" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/ml_pipeline/notebooks/train_resnet50_colab.ipynb b/ml_pipeline/notebooks/train_resnet50_colab.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..8bd1a7a793e03466a12baff03309ea27ff08d555 --- /dev/null +++ b/ml_pipeline/notebooks/train_resnet50_colab.ipynb @@ -0,0 +1,417 @@ +{ + "nbformat": 4, + "nbformat_minor": 0, + "metadata": { + "colab": { + "provenance": [], + "gpuType": "T4" + }, + "kernelspec": { + "name": "python3", + "display_name": "Python 3" + }, + "accelerator": "GPU" + }, + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Train Resnet50 on PlantVillage (38 classes)\n", + "\nFull fine-tuning with AdamW, onecycle LR, MixUp/CutMix, early stopping.\n", + "\n**Instructions:**\n", + "1. Runtime > Change runtime type > GPU (T4)\n", + "2. Run all cells \u2014 dataset downloads automatically via kagglehub\n", + "3. Checkpoints saved to Google Drive\n" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install -q timm scikit-learn tqdm tensorboard kagglehub" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Mount Google Drive (for saving checkpoints)" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from google.colab import drive\n", + "drive.mount('/content/drive')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Download PlantVillage Dataset" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import os\n", + "\n", + "path = kagglehub.dataset_download('vipoooool/new-plant-diseases-dataset')\n", + "print(\"Dataset path:\", path)\n", + "\n", + "# Find the actual data directories\n", + "for root, dirs, files in os.walk(path):\n", + " if 'train' in dirs or 'valid' in dirs:\n", + " DATA_ROOT = root\n", + " break\n", + "print(\"Data root:\", DATA_ROOT)\n", + "print(\"Contents:\", os.listdir(DATA_ROOT))\n", + "\n", + "# Check class count\n", + "train_dir = os.path.join(DATA_ROOT, \"train\")\n", + "valid_dir = os.path.join(DATA_ROOT, \"valid\")\n", + "train_classes = sorted(os.listdir(train_dir))\n", + "print(f\"Train classes: {len(train_classes)}\")\n", + "print(f\"Train images: {sum(len(os.listdir(os.path.join(train_dir, c))) for c in train_classes)}\")\n", + "valid_classes = sorted(os.listdir(valid_dir))\n", + "print(f\"Valid images: {sum(len(os.listdir(os.path.join(valid_dir, c))) for c in valid_classes)}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Configuration" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import json\n", + "\n", + "CHECKPOINT_DIR = \"/content/drive/MyDrive/checkpoints/resnet50\"\n", + "os.makedirs(CHECKPOINT_DIR, exist_ok=True)\n", + "\n", + "MODEL_NAME = \"resnet50\"\n", + "IMG_SIZE = 224\n", + "BATCH_SIZE = 64\n", + "EPOCHS = 60\n", + "LR = 0.0005\n", + "WEIGHT_DECAY = 0.0001\n", + "SCHEDULER = \"onecycle\"\n", + "WARMUP_EPOCHS = 3\n", + "LABEL_SMOOTHING = 0.05\n", + "MIXUP_ALPHA = 0.2\n", + "CUTMIX_PROB = 0.5\n", + "AUGMENT_LEVEL = \"medium\"\n", + "DROPOUT = 0.3\n", + "EARLY_STOPPING_PATIENCE = 12\n", + "GRADIENT_CLIP = 1.0\n", + "SEED = 123\n", + "NUM_CLASSES = 38\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Dataset & DataLoaders" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "import numpy as np\n", + "import random\n", + "from torch.utils.data import DataLoader, WeightedRandomSampler\n", + "from torchvision import transforms, datasets\n", + "from collections import Counter\n", + "\n", + "torch.manual_seed(SEED); np.random.seed(SEED); random.seed(SEED)\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "print(f\"Device: {device}\")\n", + "\n", + "def get_train_transforms(img_size, level):\n", + " base = [transforms.Resize((img_size+32, img_size+32)), transforms.RandomCrop(img_size),\n", + " transforms.RandomHorizontalFlip(0.5)]\n", + " if level == \"medium\":\n", + " base += [transforms.RandomVerticalFlip(0.3), transforms.RandomRotation(15),\n", + " transforms.ColorJitter(0.2,0.2,0.2,0.1)]\n", + " elif level == \"heavy\":\n", + " base += [transforms.RandomVerticalFlip(0.3), transforms.RandomRotation(30),\n", + " transforms.ColorJitter(0.3,0.3,0.3,0.15), transforms.RandAugment(2,9)]\n", + " base += [transforms.ToTensor(), transforms.Normalize([0.485,0.456,0.406],[0.229,0.224,0.225])]\n", + " if level in (\"medium\",\"heavy\"):\n", + " base.append(transforms.RandomErasing(p=0.25 if level==\"medium\" else 0.4))\n", + " return transforms.Compose(base)\n", + "\n", + "val_transform = transforms.Compose([\n", + " transforms.Resize((IMG_SIZE, IMG_SIZE)), transforms.ToTensor(),\n", + " transforms.Normalize([0.485,0.456,0.406],[0.229,0.224,0.225])\n", + "])\n", + "\n", + "train_ds = datasets.ImageFolder(train_dir, get_train_transforms(IMG_SIZE, AUGMENT_LEVEL))\n", + "val_ds = datasets.ImageFolder(valid_dir, val_transform)\n", + "\n", + "# Balanced sampler for class imbalance\n", + "counts = Counter(train_ds.targets)\n", + "weights = [1.0/counts[t] for t in train_ds.targets]\n", + "sampler = WeightedRandomSampler(weights, len(train_ds), replacement=True)\n", + "\n", + "train_dl = DataLoader(train_ds, batch_size=BATCH_SIZE, sampler=sampler, num_workers=4, pin_memory=True, drop_last=True)\n", + "val_dl = DataLoader(val_ds, batch_size=BATCH_SIZE, shuffle=False, num_workers=4, pin_memory=True)\n", + "\n", + "print(f\"Train: {len(train_ds)}, Val: {len(val_ds)}, Classes: {len(train_ds.classes)}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Model" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import timm\n", + "\n", + "class BaseModel(nn.Module):\n", + " def __init__(self, model_name, num_classes=38, pretrained=True, dropout=0.3):\n", + " super().__init__()\n", + " self.backbone = timm.create_model(model_name, pretrained=pretrained, num_classes=0, drop_rate=dropout)\n", + " with torch.no_grad():\n", + " feat_dim = self.backbone(torch.randn(1,3,IMG_SIZE,IMG_SIZE)).shape[-1]\n", + " self.head = nn.Sequential(nn.Dropout(dropout), nn.Linear(feat_dim, num_classes))\n", + " print(f\"Model: {model_name}, feat_dim={feat_dim}, params={sum(p.numel() for p in self.parameters())/1e6:.1f}M\")\n", + "\n", + " def forward(self, x):\n", + " return self.head(self.backbone(x))\n", + "\n", + "model = BaseModel(MODEL_NAME, NUM_CLASSES, True, DROPOUT).to(device)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## MixUp/CutMix & Loss" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "class MixUpCutMix:\n", + " def __init__(self, mixup_alpha=0.2, cutmix_prob=0.5, num_classes=38):\n", + " self.mixup_alpha = mixup_alpha\n", + " self.cutmix_prob = cutmix_prob\n", + " self.num_classes = num_classes\n", + "\n", + " def __call__(self, images, targets):\n", + " if random.random() < self.cutmix_prob:\n", + " return self._cutmix(images, targets)\n", + " return self._mixup(images, targets)\n", + "\n", + " def _mixup(self, images, targets):\n", + " lam = np.random.beta(self.mixup_alpha, self.mixup_alpha) if self.mixup_alpha > 0 else 1.0\n", + " idx = torch.randperm(images.size(0), device=images.device)\n", + " mixed = lam * images + (1-lam) * images[idx]\n", + " t_oh = torch.nn.functional.one_hot(targets, self.num_classes).float()\n", + " return mixed, lam * t_oh + (1-lam) * t_oh[idx]\n", + "\n", + " def _cutmix(self, images, targets):\n", + " lam = np.random.beta(1.0, 1.0)\n", + " idx = torch.randperm(images.size(0), device=images.device)\n", + " _,_,H,W = images.shape\n", + " cut_r = np.sqrt(1.0-lam); cw,ch = int(W*cut_r),int(H*cut_r)\n", + " cx,cy = random.randint(0,W), random.randint(0,H)\n", + " x1,y1 = max(0,cx-cw//2), max(0,cy-ch//2)\n", + " x2,y2 = min(W,cx+cw//2), min(H,cy+ch//2)\n", + " images[:,:,y1:y2,x1:x2] = images[idx,:,y1:y2,x1:x2]\n", + " lam = 1-(x2-x1)*(y2-y1)/(W*H)\n", + " t_oh = torch.nn.functional.one_hot(targets, self.num_classes).float()\n", + " return images, lam*t_oh + (1-lam)*t_oh[idx]\n", + "\n", + "mixup_fn = MixUpCutMix(MIXUP_ALPHA, CUTMIX_PROB, NUM_CLASSES)\n", + "criterion = nn.CrossEntropyLoss(label_smoothing=LABEL_SMOOTHING)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Training" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import time\n", + "from torch.cuda.amp import GradScaler, autocast\n", + "from sklearn.metrics import f1_score\n", + "from tqdm.auto import tqdm\n", + "\n", + "def train_one_epoch(model, loader, criterion, optimizer, scaler, mixup_fn, device, epoch):\n", + " model.train()\n", + " total_loss = 0; all_preds, all_labels = [], []\n", + " pbar = tqdm(loader, desc=f\"Epoch {epoch}\")\n", + " for images, labels in pbar:\n", + " images, labels = images.to(device), labels.to(device)\n", + " use_mix = MIXUP_ALPHA > 0 and np.random.random() < 0.5\n", + " if use_mix:\n", + " images, labels_mixed = mixup_fn(images, labels); is_mixed = True\n", + " else:\n", + " is_mixed = False\n", + " optimizer.zero_grad()\n", + " with autocast(enabled=torch.cuda.is_available()):\n", + " logits = model(images)\n", + " if is_mixed:\n", + " loss = -(labels_mixed * torch.log_softmax(logits, dim=1)).sum(dim=1).mean()\n", + " else:\n", + " loss = criterion(logits, labels)\n", + " scaler.scale(loss).backward()\n", + " if GRADIENT_CLIP > 0:\n", + " scaler.unscale_(optimizer)\n", + " nn.utils.clip_grad_norm_(model.parameters(), GRADIENT_CLIP)\n", + " scaler.step(optimizer); scaler.update()\n", + " total_loss += loss.item()\n", + " if not is_mixed:\n", + " all_preds.extend(logits.argmax(1).cpu().numpy())\n", + " all_labels.extend(labels.cpu().numpy())\n", + " pbar.set_postfix(loss=f\"{loss.item():.4f}\")\n", + " return total_loss/len(loader), f1_score(all_labels, all_preds, average=\"macro\", zero_division=0) if all_labels else 0\n", + "\n", + "@torch.no_grad()\n", + "def validate(model, loader, criterion, device):\n", + " model.eval()\n", + " total_loss = 0; all_preds, all_labels, all_logits = [], [], []\n", + " for images, labels in tqdm(loader, desc=\"Validating\"):\n", + " images, labels = images.to(device), labels.to(device)\n", + " logits = model(images)\n", + " loss = criterion(logits, labels)\n", + " total_loss += loss.item()\n", + " all_preds.extend(logits.argmax(1).cpu().numpy())\n", + " all_labels.extend(labels.cpu().numpy())\n", + " all_logits.append(logits.cpu().numpy())\n", + " f1 = f1_score(all_labels, all_preds, average=\"macro\", zero_division=0)\n", + " acc = np.mean(np.array(all_preds)==np.array(all_labels))\n", + " return total_loss/len(loader), f1, acc, np.concatenate(all_logits), np.array(all_labels)\n", + "\n", + "# Optimizer & Scheduler\n", + "optimizer = torch.optim.AdamW(model.parameters(), lr=LR, weight_decay=WEIGHT_DECAY)\n", + "if SCHEDULER == \"cosine\":\n", + " scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=EPOCHS-WARMUP_EPOCHS)\n", + "else:\n", + " scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr=LR, epochs=EPOCHS, steps_per_epoch=len(train_dl))\n", + "warmup_sched = torch.optim.lr_scheduler.LinearLR(optimizer, start_factor=0.01, total_iters=WARMUP_EPOCHS) if WARMUP_EPOCHS > 0 else None\n", + "scaler = GradScaler(enabled=torch.cuda.is_available())\n", + "\n", + "best_f1 = 0; patience_counter = 0; history = []\n", + "print(f\"Training {MODEL_NAME} for {EPOCHS} epochs on {device}...\")\n", + "print(\"-\"*80)\n", + "\n", + "for epoch in range(1, EPOCHS+1):\n", + " t0 = time.time()\n", + " train_loss, train_f1 = train_one_epoch(model, train_dl, criterion, optimizer, scaler, mixup_fn, device, epoch)\n", + " val_loss, val_f1, val_acc, val_logits, val_labels = validate(model, val_dl, criterion, device)\n", + " if warmup_sched and epoch <= WARMUP_EPOCHS:\n", + " warmup_sched.step()\n", + " elif SCHEDULER == \"cosine\":\n", + " scheduler.step()\n", + " lr = optimizer.param_groups[0][\"lr\"]\n", + " elapsed = time.time()-t0\n", + " marker = \"\"\n", + " if val_f1 > best_f1:\n", + " best_f1 = val_f1; patience_counter = 0; marker = \" \\u2605 BEST\"\n", + " torch.save({\n", + " \"epoch\": epoch, \"model_state_dict\": model.state_dict(),\n", + " \"val_f1\": val_f1, \"val_acc\": val_acc, \"model_type\": \"resnet50\",\n", + " \"num_classes\": NUM_CLASSES\n", + " }, os.path.join(CHECKPOINT_DIR, \"best_model.pt\"))\n", + " np.save(os.path.join(CHECKPOINT_DIR, \"best_val_logits.npy\"), val_logits)\n", + " np.save(os.path.join(CHECKPOINT_DIR, \"best_val_labels.npy\"), val_labels)\n", + " else:\n", + " patience_counter += 1\n", + " history.append({\n", + " \"epoch\": epoch, \"train_loss\": train_loss, \"train_f1\": train_f1,\n", + " \"val_loss\": val_loss, \"val_f1\": val_f1, \"val_acc\": val_acc, \"lr\": lr, \"time\": elapsed\n", + " })\n", + " print(f\"Epoch {epoch:2d}/{EPOCHS} | TrainLoss={train_loss:.4f} F1={train_f1:.4f} | ValLoss={val_loss:.4f} F1={val_f1:.4f} Acc={val_acc:.4f} | lr={lr:.6f} | {elapsed:.0f}s{marker}\")\n", + " if patience_counter >= EARLY_STOPPING_PATIENCE:\n", + " print(f\"Early stopping at epoch {epoch}\"); break\n", + "\n", + "with open(os.path.join(CHECKPOINT_DIR, \"training_history.json\"), \"w\") as f:\n", + " json.dump(history, f, indent=2)\n", + "print(f\"\\nDone! Best Val F1: {best_f1:.4f} Checkpoint: {CHECKPOINT_DIR}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Evaluation & Per-Class Report" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.metrics import classification_report\n", + "\n", + "ckpt = torch.load(os.path.join(CHECKPOINT_DIR, \"best_model.pt\"), map_location=device)\n", + "model.load_state_dict(ckpt[\"model_state_dict\"])\n", + "model.eval()\n", + "\n", + "all_preds, all_labels = [], []\n", + "with torch.no_grad():\n", + " for images, labels in tqdm(val_dl, desc=\"Evaluating\"):\n", + " images = images.to(device)\n", + " preds = model(images).argmax(1).cpu().numpy()\n", + " all_preds.extend(preds)\n", + " all_labels.extend(labels.numpy())\n", + "\n", + "eval_f1 = f1_score(all_labels, all_preds, average=\"macro\")\n", + "eval_acc = np.mean(np.array(all_preds)==np.array(all_labels))\n", + "print(f\"Validation Accuracy: {eval_acc:.4f}\")\n", + "print(f\"Validation Macro F1: {eval_f1:.4f}\")\n", + "print()\n", + "print(classification_report(all_labels, all_preds, target_names=train_ds.classes, digits=3))\n", + "\n", + "# Save class names\n", + "with open(os.path.join(CHECKPOINT_DIR, \"class_names.json\"), \"w\") as f:\n", + " json.dump(train_ds.classes, f, indent=2)\n", + "print(f\"\\n\\u2713 All artifacts saved to {CHECKPOINT_DIR}\")\n" + ], + "execution_count": null, + "outputs": [] + } + ] +} \ No newline at end of file diff --git a/ml_pipeline/notebooks/train_swin_tiny_colab.ipynb b/ml_pipeline/notebooks/train_swin_tiny_colab.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..46d6a672fc44803646febb6001430544691928ca --- /dev/null +++ b/ml_pipeline/notebooks/train_swin_tiny_colab.ipynb @@ -0,0 +1,417 @@ +{ + "nbformat": 4, + "nbformat_minor": 0, + "metadata": { + "colab": { + "provenance": [], + "gpuType": "T4" + }, + "kernelspec": { + "name": "python3", + "display_name": "Python 3" + }, + "accelerator": "GPU" + }, + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Train Swin Tiny on PlantVillage (38 classes)\n", + "\nFull fine-tuning with AdamW, cosine LR, MixUp/CutMix, early stopping.\n", + "\n**Instructions:**\n", + "1. Runtime > Change runtime type > GPU (T4)\n", + "2. Run all cells \u2014 dataset downloads automatically via kagglehub\n", + "3. Checkpoints saved to Google Drive\n" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install -q timm scikit-learn tqdm tensorboard kagglehub" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Mount Google Drive (for saving checkpoints)" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from google.colab import drive\n", + "drive.mount('/content/drive')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Download PlantVillage Dataset" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import os\n", + "\n", + "path = kagglehub.dataset_download('vipoooool/new-plant-diseases-dataset')\n", + "print(\"Dataset path:\", path)\n", + "\n", + "# Find the actual data directories\n", + "for root, dirs, files in os.walk(path):\n", + " if 'train' in dirs or 'valid' in dirs:\n", + " DATA_ROOT = root\n", + " break\n", + "print(\"Data root:\", DATA_ROOT)\n", + "print(\"Contents:\", os.listdir(DATA_ROOT))\n", + "\n", + "# Check class count\n", + "train_dir = os.path.join(DATA_ROOT, \"train\")\n", + "valid_dir = os.path.join(DATA_ROOT, \"valid\")\n", + "train_classes = sorted(os.listdir(train_dir))\n", + "print(f\"Train classes: {len(train_classes)}\")\n", + "print(f\"Train images: {sum(len(os.listdir(os.path.join(train_dir, c))) for c in train_classes)}\")\n", + "valid_classes = sorted(os.listdir(valid_dir))\n", + "print(f\"Valid images: {sum(len(os.listdir(os.path.join(valid_dir, c))) for c in valid_classes)}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Configuration" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import json\n", + "\n", + "CHECKPOINT_DIR = \"/content/drive/MyDrive/checkpoints/swin_tiny\"\n", + "os.makedirs(CHECKPOINT_DIR, exist_ok=True)\n", + "\n", + "MODEL_NAME = \"swin_tiny_patch4_window7_224\"\n", + "IMG_SIZE = 224\n", + "BATCH_SIZE = 64\n", + "EPOCHS = 50\n", + "LR = 0.0005\n", + "WEIGHT_DECAY = 0.0001\n", + "SCHEDULER = \"cosine\"\n", + "WARMUP_EPOCHS = 5\n", + "LABEL_SMOOTHING = 0.1\n", + "MIXUP_ALPHA = 0.2\n", + "CUTMIX_PROB = 0.5\n", + "AUGMENT_LEVEL = \"medium\"\n", + "DROPOUT = 0.3\n", + "EARLY_STOPPING_PATIENCE = 10\n", + "GRADIENT_CLIP = 1.0\n", + "SEED = 789\n", + "NUM_CLASSES = 38\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Dataset & DataLoaders" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "import numpy as np\n", + "import random\n", + "from torch.utils.data import DataLoader, WeightedRandomSampler\n", + "from torchvision import transforms, datasets\n", + "from collections import Counter\n", + "\n", + "torch.manual_seed(SEED); np.random.seed(SEED); random.seed(SEED)\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "print(f\"Device: {device}\")\n", + "\n", + "def get_train_transforms(img_size, level):\n", + " base = [transforms.Resize((img_size+32, img_size+32)), transforms.RandomCrop(img_size),\n", + " transforms.RandomHorizontalFlip(0.5)]\n", + " if level == \"medium\":\n", + " base += [transforms.RandomVerticalFlip(0.3), transforms.RandomRotation(15),\n", + " transforms.ColorJitter(0.2,0.2,0.2,0.1)]\n", + " elif level == \"heavy\":\n", + " base += [transforms.RandomVerticalFlip(0.3), transforms.RandomRotation(30),\n", + " transforms.ColorJitter(0.3,0.3,0.3,0.15), transforms.RandAugment(2,9)]\n", + " base += [transforms.ToTensor(), transforms.Normalize([0.485,0.456,0.406],[0.229,0.224,0.225])]\n", + " if level in (\"medium\",\"heavy\"):\n", + " base.append(transforms.RandomErasing(p=0.25 if level==\"medium\" else 0.4))\n", + " return transforms.Compose(base)\n", + "\n", + "val_transform = transforms.Compose([\n", + " transforms.Resize((IMG_SIZE, IMG_SIZE)), transforms.ToTensor(),\n", + " transforms.Normalize([0.485,0.456,0.406],[0.229,0.224,0.225])\n", + "])\n", + "\n", + "train_ds = datasets.ImageFolder(train_dir, get_train_transforms(IMG_SIZE, AUGMENT_LEVEL))\n", + "val_ds = datasets.ImageFolder(valid_dir, val_transform)\n", + "\n", + "# Balanced sampler for class imbalance\n", + "counts = Counter(train_ds.targets)\n", + "weights = [1.0/counts[t] for t in train_ds.targets]\n", + "sampler = WeightedRandomSampler(weights, len(train_ds), replacement=True)\n", + "\n", + "train_dl = DataLoader(train_ds, batch_size=BATCH_SIZE, sampler=sampler, num_workers=4, pin_memory=True, drop_last=True)\n", + "val_dl = DataLoader(val_ds, batch_size=BATCH_SIZE, shuffle=False, num_workers=4, pin_memory=True)\n", + "\n", + "print(f\"Train: {len(train_ds)}, Val: {len(val_ds)}, Classes: {len(train_ds.classes)}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Model" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import timm\n", + "\n", + "class BaseModel(nn.Module):\n", + " def __init__(self, model_name, num_classes=38, pretrained=True, dropout=0.3):\n", + " super().__init__()\n", + " self.backbone = timm.create_model(model_name, pretrained=pretrained, num_classes=0, drop_rate=dropout)\n", + " with torch.no_grad():\n", + " feat_dim = self.backbone(torch.randn(1,3,IMG_SIZE,IMG_SIZE)).shape[-1]\n", + " self.head = nn.Sequential(nn.Dropout(dropout), nn.Linear(feat_dim, num_classes))\n", + " print(f\"Model: {model_name}, feat_dim={feat_dim}, params={sum(p.numel() for p in self.parameters())/1e6:.1f}M\")\n", + "\n", + " def forward(self, x):\n", + " return self.head(self.backbone(x))\n", + "\n", + "model = BaseModel(MODEL_NAME, NUM_CLASSES, True, DROPOUT).to(device)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## MixUp/CutMix & Loss" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "class MixUpCutMix:\n", + " def __init__(self, mixup_alpha=0.2, cutmix_prob=0.5, num_classes=38):\n", + " self.mixup_alpha = mixup_alpha\n", + " self.cutmix_prob = cutmix_prob\n", + " self.num_classes = num_classes\n", + "\n", + " def __call__(self, images, targets):\n", + " if random.random() < self.cutmix_prob:\n", + " return self._cutmix(images, targets)\n", + " return self._mixup(images, targets)\n", + "\n", + " def _mixup(self, images, targets):\n", + " lam = np.random.beta(self.mixup_alpha, self.mixup_alpha) if self.mixup_alpha > 0 else 1.0\n", + " idx = torch.randperm(images.size(0), device=images.device)\n", + " mixed = lam * images + (1-lam) * images[idx]\n", + " t_oh = torch.nn.functional.one_hot(targets, self.num_classes).float()\n", + " return mixed, lam * t_oh + (1-lam) * t_oh[idx]\n", + "\n", + " def _cutmix(self, images, targets):\n", + " lam = np.random.beta(1.0, 1.0)\n", + " idx = torch.randperm(images.size(0), device=images.device)\n", + " _,_,H,W = images.shape\n", + " cut_r = np.sqrt(1.0-lam); cw,ch = int(W*cut_r),int(H*cut_r)\n", + " cx,cy = random.randint(0,W), random.randint(0,H)\n", + " x1,y1 = max(0,cx-cw//2), max(0,cy-ch//2)\n", + " x2,y2 = min(W,cx+cw//2), min(H,cy+ch//2)\n", + " images[:,:,y1:y2,x1:x2] = images[idx,:,y1:y2,x1:x2]\n", + " lam = 1-(x2-x1)*(y2-y1)/(W*H)\n", + " t_oh = torch.nn.functional.one_hot(targets, self.num_classes).float()\n", + " return images, lam*t_oh + (1-lam)*t_oh[idx]\n", + "\n", + "mixup_fn = MixUpCutMix(MIXUP_ALPHA, CUTMIX_PROB, NUM_CLASSES)\n", + "criterion = nn.CrossEntropyLoss(label_smoothing=LABEL_SMOOTHING)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Training" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import time\n", + "from torch.cuda.amp import GradScaler, autocast\n", + "from sklearn.metrics import f1_score\n", + "from tqdm.auto import tqdm\n", + "\n", + "def train_one_epoch(model, loader, criterion, optimizer, scaler, mixup_fn, device, epoch):\n", + " model.train()\n", + " total_loss = 0; all_preds, all_labels = [], []\n", + " pbar = tqdm(loader, desc=f\"Epoch {epoch}\")\n", + " for images, labels in pbar:\n", + " images, labels = images.to(device), labels.to(device)\n", + " use_mix = MIXUP_ALPHA > 0 and np.random.random() < 0.5\n", + " if use_mix:\n", + " images, labels_mixed = mixup_fn(images, labels); is_mixed = True\n", + " else:\n", + " is_mixed = False\n", + " optimizer.zero_grad()\n", + " with autocast(enabled=torch.cuda.is_available()):\n", + " logits = model(images)\n", + " if is_mixed:\n", + " loss = -(labels_mixed * torch.log_softmax(logits, dim=1)).sum(dim=1).mean()\n", + " else:\n", + " loss = criterion(logits, labels)\n", + " scaler.scale(loss).backward()\n", + " if GRADIENT_CLIP > 0:\n", + " scaler.unscale_(optimizer)\n", + " nn.utils.clip_grad_norm_(model.parameters(), GRADIENT_CLIP)\n", + " scaler.step(optimizer); scaler.update()\n", + " total_loss += loss.item()\n", + " if not is_mixed:\n", + " all_preds.extend(logits.argmax(1).cpu().numpy())\n", + " all_labels.extend(labels.cpu().numpy())\n", + " pbar.set_postfix(loss=f\"{loss.item():.4f}\")\n", + " return total_loss/len(loader), f1_score(all_labels, all_preds, average=\"macro\", zero_division=0) if all_labels else 0\n", + "\n", + "@torch.no_grad()\n", + "def validate(model, loader, criterion, device):\n", + " model.eval()\n", + " total_loss = 0; all_preds, all_labels, all_logits = [], [], []\n", + " for images, labels in tqdm(loader, desc=\"Validating\"):\n", + " images, labels = images.to(device), labels.to(device)\n", + " logits = model(images)\n", + " loss = criterion(logits, labels)\n", + " total_loss += loss.item()\n", + " all_preds.extend(logits.argmax(1).cpu().numpy())\n", + " all_labels.extend(labels.cpu().numpy())\n", + " all_logits.append(logits.cpu().numpy())\n", + " f1 = f1_score(all_labels, all_preds, average=\"macro\", zero_division=0)\n", + " acc = np.mean(np.array(all_preds)==np.array(all_labels))\n", + " return total_loss/len(loader), f1, acc, np.concatenate(all_logits), np.array(all_labels)\n", + "\n", + "# Optimizer & Scheduler\n", + "optimizer = torch.optim.AdamW(model.parameters(), lr=LR, weight_decay=WEIGHT_DECAY)\n", + "if SCHEDULER == \"cosine\":\n", + " scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=EPOCHS-WARMUP_EPOCHS)\n", + "else:\n", + " scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr=LR, epochs=EPOCHS, steps_per_epoch=len(train_dl))\n", + "warmup_sched = torch.optim.lr_scheduler.LinearLR(optimizer, start_factor=0.01, total_iters=WARMUP_EPOCHS) if WARMUP_EPOCHS > 0 else None\n", + "scaler = GradScaler(enabled=torch.cuda.is_available())\n", + "\n", + "best_f1 = 0; patience_counter = 0; history = []\n", + "print(f\"Training {MODEL_NAME} for {EPOCHS} epochs on {device}...\")\n", + "print(\"-\"*80)\n", + "\n", + "for epoch in range(1, EPOCHS+1):\n", + " t0 = time.time()\n", + " train_loss, train_f1 = train_one_epoch(model, train_dl, criterion, optimizer, scaler, mixup_fn, device, epoch)\n", + " val_loss, val_f1, val_acc, val_logits, val_labels = validate(model, val_dl, criterion, device)\n", + " if warmup_sched and epoch <= WARMUP_EPOCHS:\n", + " warmup_sched.step()\n", + " elif SCHEDULER == \"cosine\":\n", + " scheduler.step()\n", + " lr = optimizer.param_groups[0][\"lr\"]\n", + " elapsed = time.time()-t0\n", + " marker = \"\"\n", + " if val_f1 > best_f1:\n", + " best_f1 = val_f1; patience_counter = 0; marker = \" \\u2605 BEST\"\n", + " torch.save({\n", + " \"epoch\": epoch, \"model_state_dict\": model.state_dict(),\n", + " \"val_f1\": val_f1, \"val_acc\": val_acc, \"model_type\": \"swin_tiny\",\n", + " \"num_classes\": NUM_CLASSES\n", + " }, os.path.join(CHECKPOINT_DIR, \"best_model.pt\"))\n", + " np.save(os.path.join(CHECKPOINT_DIR, \"best_val_logits.npy\"), val_logits)\n", + " np.save(os.path.join(CHECKPOINT_DIR, \"best_val_labels.npy\"), val_labels)\n", + " else:\n", + " patience_counter += 1\n", + " history.append({\n", + " \"epoch\": epoch, \"train_loss\": train_loss, \"train_f1\": train_f1,\n", + " \"val_loss\": val_loss, \"val_f1\": val_f1, \"val_acc\": val_acc, \"lr\": lr, \"time\": elapsed\n", + " })\n", + " print(f\"Epoch {epoch:2d}/{EPOCHS} | TrainLoss={train_loss:.4f} F1={train_f1:.4f} | ValLoss={val_loss:.4f} F1={val_f1:.4f} Acc={val_acc:.4f} | lr={lr:.6f} | {elapsed:.0f}s{marker}\")\n", + " if patience_counter >= EARLY_STOPPING_PATIENCE:\n", + " print(f\"Early stopping at epoch {epoch}\"); break\n", + "\n", + "with open(os.path.join(CHECKPOINT_DIR, \"training_history.json\"), \"w\") as f:\n", + " json.dump(history, f, indent=2)\n", + "print(f\"\\nDone! Best Val F1: {best_f1:.4f} Checkpoint: {CHECKPOINT_DIR}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Evaluation & Per-Class Report" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.metrics import classification_report\n", + "\n", + "ckpt = torch.load(os.path.join(CHECKPOINT_DIR, \"best_model.pt\"), map_location=device)\n", + "model.load_state_dict(ckpt[\"model_state_dict\"])\n", + "model.eval()\n", + "\n", + "all_preds, all_labels = [], []\n", + "with torch.no_grad():\n", + " for images, labels in tqdm(val_dl, desc=\"Evaluating\"):\n", + " images = images.to(device)\n", + " preds = model(images).argmax(1).cpu().numpy()\n", + " all_preds.extend(preds)\n", + " all_labels.extend(labels.numpy())\n", + "\n", + "eval_f1 = f1_score(all_labels, all_preds, average=\"macro\")\n", + "eval_acc = np.mean(np.array(all_preds)==np.array(all_labels))\n", + "print(f\"Validation Accuracy: {eval_acc:.4f}\")\n", + "print(f\"Validation Macro F1: {eval_f1:.4f}\")\n", + "print()\n", + "print(classification_report(all_labels, all_preds, target_names=train_ds.classes, digits=3))\n", + "\n", + "# Save class names\n", + "with open(os.path.join(CHECKPOINT_DIR, \"class_names.json\"), \"w\") as f:\n", + " json.dump(train_ds.classes, f, indent=2)\n", + "print(f\"\\n\\u2713 All artifacts saved to {CHECKPOINT_DIR}\")\n" + ], + "execution_count": null, + "outputs": [] + } + ] +} \ No newline at end of file diff --git a/ml_pipeline/quantization/__init__.py b/ml_pipeline/quantization/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/ml_pipeline/requirements.txt b/ml_pipeline/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..9b09446bc6e5e8354fc025e5c1e847c88a0396a7 --- /dev/null +++ b/ml_pipeline/requirements.txt @@ -0,0 +1,19 @@ +# ML Pipeline Dependencies +torch>=2.1.0 +torchvision>=0.16.0 +timm>=0.9.12 +numpy>=1.24.0 +pandas>=2.0.0 +scikit-learn>=1.3.0 +lightgbm>=4.1.0 +optuna>=3.4.0 +onnx>=1.15.0 +onnxruntime>=1.16.0 +matplotlib>=3.7.0 +seaborn>=0.13.0 +pyyaml>=6.0 +tqdm>=4.66.0 +Pillow>=10.0.0 +albumentations>=1.3.0 +tensorboard>=2.15.0 +netcal>=1.3.0 diff --git a/ml_pipeline/scripts/__pycache__/calibrate.cpython-311.pyc b/ml_pipeline/scripts/__pycache__/calibrate.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..addc6cfd7595b035a32e8b88e1fcac2b494310e8 Binary files /dev/null and b/ml_pipeline/scripts/__pycache__/calibrate.cpython-311.pyc differ diff --git a/ml_pipeline/scripts/__pycache__/generate_synthetic_data.cpython-311.pyc b/ml_pipeline/scripts/__pycache__/generate_synthetic_data.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..890714f5e9f15355e15a6a5fc65906e280e390c9 Binary files /dev/null and b/ml_pipeline/scripts/__pycache__/generate_synthetic_data.cpython-311.pyc differ diff --git a/ml_pipeline/scripts/calibrate.py b/ml_pipeline/scripts/calibrate.py new file mode 100644 index 0000000000000000000000000000000000000000..ca7da5ed79c57d8f07ef8f3449aaeb6735829264 --- /dev/null +++ b/ml_pipeline/scripts/calibrate.py @@ -0,0 +1,221 @@ +""" +Temperature Scaling and Probability Calibration. +Supports: Temperature Scaling, Platt Scaling, Isotonic Regression. +Reports: ECE, ACE, reliability diagrams. + +Usage: + python ml_pipeline/scripts/calibrate.py --ensemble_dir checkpoints/ensemble --data_dir data/plantvillage +""" +import os +import sys +import argparse +import json +from pathlib import Path + +import numpy as np +import torch +import torch.nn as nn +import torch.optim as optim +import matplotlib +matplotlib.use('Agg') +import matplotlib.pyplot as plt + +sys.path.insert(0, str(Path(__file__).parent.parent.parent)) + + +class TemperatureScaling(nn.Module): + """ + Temperature scaling for calibrating neural network probabilities. + Learns a single scalar T to soften/sharpen the logits: p = softmax(logits / T) + """ + + def __init__(self): + super().__init__() + self.temperature = nn.Parameter(torch.ones(1) * 1.5) + + def forward(self, logits: torch.Tensor) -> torch.Tensor: + return logits / self.temperature + + def fit(self, logits: np.ndarray, labels: np.ndarray, lr: float = 0.01, max_iter: int = 100): + """Optimize temperature on held-out calibration set.""" + logits_t = torch.tensor(logits, dtype=torch.float32) + labels_t = torch.tensor(labels, dtype=torch.long) + + criterion = nn.CrossEntropyLoss() + optimizer = optim.LBFGS([self.temperature], lr=lr, max_iter=max_iter) + + def closure(): + optimizer.zero_grad() + scaled = self.forward(logits_t) + loss = criterion(scaled, labels_t) + loss.backward() + return loss + + optimizer.step(closure) + print(f"Optimal temperature: {self.temperature.item():.4f}") + return self.temperature.item() + + def calibrate(self, logits: np.ndarray) -> np.ndarray: + """Apply temperature scaling and return calibrated probabilities.""" + logits_t = torch.tensor(logits, dtype=torch.float32) + with torch.no_grad(): + scaled = self.forward(logits_t) + probs = torch.softmax(scaled, dim=1).numpy() + return probs + + +def compute_ece(probs: np.ndarray, labels: np.ndarray, n_bins: int = 15) -> float: + """Expected Calibration Error.""" + confidences = probs.max(axis=1) + predictions = probs.argmax(axis=1) + accuracies = (predictions == labels).astype(float) + + bin_boundaries = np.linspace(0, 1, n_bins + 1) + ece = 0.0 + + for i in range(n_bins): + mask = (confidences > bin_boundaries[i]) & (confidences <= bin_boundaries[i + 1]) + if mask.sum() > 0: + bin_acc = accuracies[mask].mean() + bin_conf = confidences[mask].mean() + ece += mask.sum() / len(labels) * abs(bin_acc - bin_conf) + + return ece + + +def compute_ace(probs: np.ndarray, labels: np.ndarray, n_bins: int = 15) -> float: + """Adaptive Calibration Error (class-conditional).""" + num_classes = probs.shape[1] + ace = 0.0 + + for c in range(num_classes): + class_probs = probs[:, c] + class_labels = (labels == c).astype(float) + + bin_boundaries = np.linspace(0, 1, n_bins + 1) + for i in range(n_bins): + mask = (class_probs > bin_boundaries[i]) & (class_probs <= bin_boundaries[i + 1]) + if mask.sum() > 0: + bin_acc = class_labels[mask].mean() + bin_conf = class_probs[mask].mean() + ace += mask.sum() / (len(labels) * num_classes) * abs(bin_acc - bin_conf) + + return ace + + +def plot_reliability_diagram(probs: np.ndarray, labels: np.ndarray, + title: str = "Reliability Diagram", + save_path: str = None, n_bins: int = 15): + """Plot reliability diagram for calibration visualization.""" + confidences = probs.max(axis=1) + predictions = probs.argmax(axis=1) + accuracies = (predictions == labels).astype(float) + + bin_boundaries = np.linspace(0, 1, n_bins + 1) + bin_accs, bin_confs, bin_counts = [], [], [] + + for i in range(n_bins): + mask = (confidences > bin_boundaries[i]) & (confidences <= bin_boundaries[i + 1]) + if mask.sum() > 0: + bin_accs.append(accuracies[mask].mean()) + bin_confs.append(confidences[mask].mean()) + bin_counts.append(mask.sum()) + else: + bin_accs.append(0) + bin_confs.append((bin_boundaries[i] + bin_boundaries[i + 1]) / 2) + bin_counts.append(0) + + fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5)) + + # Reliability diagram + ax1.bar(bin_confs, bin_accs, width=1 / n_bins, alpha=0.7, edgecolor='black', label='Model') + ax1.plot([0, 1], [0, 1], 'r--', label='Perfect calibration') + ax1.set_xlabel('Confidence') + ax1.set_ylabel('Accuracy') + ax1.set_title(title) + ax1.legend() + ax1.set_xlim(0, 1) + ax1.set_ylim(0, 1) + + # Confidence histogram + ax2.bar(bin_confs, bin_counts, width=1 / n_bins, alpha=0.7, edgecolor='black') + ax2.set_xlabel('Confidence') + ax2.set_ylabel('Count') + ax2.set_title('Confidence Distribution') + + plt.tight_layout() + if save_path: + plt.savefig(save_path, dpi=150, bbox_inches='tight') + print(f"Saved reliability diagram to {save_path}") + plt.close() + + +def calibrate_ensemble(logits: np.ndarray, labels: np.ndarray, output_dir: str): + """Full calibration pipeline.""" + os.makedirs(output_dir, exist_ok=True) + + # Before calibration + uncal_probs = torch.softmax(torch.tensor(logits), dim=1).numpy() + ece_before = compute_ece(uncal_probs, labels) + ace_before = compute_ace(uncal_probs, labels) + print(f"Before calibration: ECE={ece_before:.4f}, ACE={ace_before:.4f}") + + plot_reliability_diagram(uncal_probs, labels, + title=f"Before Calibration (ECE={ece_before:.4f})", + save_path=os.path.join(output_dir, "reliability_before.png")) + + # Temperature scaling + ts = TemperatureScaling() + temp = ts.fit(logits, labels) + cal_probs = ts.calibrate(logits) + + ece_after = compute_ece(cal_probs, labels) + ace_after = compute_ace(cal_probs, labels) + print(f"After calibration: ECE={ece_after:.4f}, ACE={ace_after:.4f}") + + plot_reliability_diagram(cal_probs, labels, + title=f"After Calibration (ECE={ece_after:.4f})", + save_path=os.path.join(output_dir, "reliability_after.png")) + + # Save + torch.save(ts.state_dict(), os.path.join(output_dir, "temperature_scaling.pt")) + + metrics = { + "temperature": temp, + "ece_before": ece_before, + "ece_after": ece_after, + "ace_before": ace_before, + "ace_after": ace_after, + } + with open(os.path.join(output_dir, "calibration_metrics.json"), "w") as f: + json.dump(metrics, f, indent=2) + + return ts, metrics + + +def main(): + parser = argparse.ArgumentParser(description="Calibrate ensemble") + parser.add_argument("--ensemble_dir", type=str, required=True) + parser.add_argument("--logits_path", type=str, default=None) + parser.add_argument("--labels_path", type=str, default=None) + args = parser.parse_args() + + if args.logits_path and args.labels_path: + logits = np.load(args.logits_path) + labels = np.load(args.labels_path) + else: + # Look for saved logits from stacking + logits_path = os.path.join(args.ensemble_dir, "..", "efficientnet_v2", "best_val_logits.npy") + labels_path = os.path.join(args.ensemble_dir, "..", "efficientnet_v2", "best_val_labels.npy") + if os.path.exists(logits_path): + logits = np.load(logits_path) + labels = np.load(labels_path) + else: + print("No logits found. Run training first.") + return + + calibrate_ensemble(logits, labels, args.ensemble_dir) + + +if __name__ == "__main__": + main() diff --git a/ml_pipeline/scripts/distill.py b/ml_pipeline/scripts/distill.py new file mode 100644 index 0000000000000000000000000000000000000000..8d90e26cb3b1736de8d1ed88cefac8f18e71b061 --- /dev/null +++ b/ml_pipeline/scripts/distill.py @@ -0,0 +1,181 @@ +""" +Knowledge Distillation: Train a lightweight student (MobileNetV3) from ensemble teacher. + +Usage: + python ml_pipeline/scripts/distill.py --teacher_dir checkpoints --student_config ml_pipeline/configs/mobilenet_v3.yaml --data_dir data/plantvillage +""" +import os +import sys +import argparse +from pathlib import Path + +import numpy as np +import torch +import torch.nn as nn +import torch.optim as optim +from torch.cuda.amp import GradScaler, autocast +from sklearn.metrics import f1_score +import yaml +from tqdm import tqdm + +sys.path.insert(0, str(Path(__file__).parent.parent.parent)) +from ml_pipeline.data.dataset import create_dataloaders +from ml_pipeline.models.architectures import create_model + + +class DistillationLoss(nn.Module): + """Combined distillation loss: KL divergence + CE loss.""" + + def __init__(self, temperature: float = 4.0, alpha: float = 0.7): + super().__init__() + self.temperature = temperature + self.alpha = alpha + self.kl_div = nn.KLDivLoss(reduction='batchmean') + self.ce_loss = nn.CrossEntropyLoss() + + def forward(self, student_logits, teacher_logits, labels): + # Soft targets (KD loss) + soft_student = nn.functional.log_softmax(student_logits / self.temperature, dim=1) + soft_teacher = nn.functional.softmax(teacher_logits / self.temperature, dim=1) + kd_loss = self.kl_div(soft_student, soft_teacher) * (self.temperature ** 2) + + # Hard targets (CE loss) + ce_loss = self.ce_loss(student_logits, labels) + + return self.alpha * kd_loss + (1 - self.alpha) * ce_loss + + +@torch.no_grad() +def get_teacher_logits(teacher_models, images, device, weights=None): + """Get weighted ensemble teacher logits.""" + all_logits = [] + for model in teacher_models: + logits = model(images) + all_logits.append(logits) + + if weights is None: + weights = [1.0 / len(teacher_models)] * len(teacher_models) + + teacher_logits = sum(w * l for w, l in zip(weights, all_logits)) + return teacher_logits + + +def distill(cfg: dict, teacher_dir: str, data_dir: str, output_dir: str): + device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + seed = cfg['training']['seed'] + torch.manual_seed(seed) + + # Load teacher models + teacher_models = [] + teacher_weights = [] + for d in sorted(os.listdir(teacher_dir)): + ckpt_path = os.path.join(teacher_dir, d, "best_model.pt") + if os.path.exists(ckpt_path) and d != "ensemble": + ckpt = torch.load(ckpt_path, map_location=device, weights_only=False) + model = create_model(ckpt['model_type'], num_classes=ckpt['num_classes'], + pretrained=False, dropout=0.0) + model.load_state_dict(ckpt['model_state_dict']) + model.to(device).eval() + teacher_models.append(model) + teacher_weights.append(ckpt.get('val_f1', 0.5)) + print(f"Loaded teacher: {d} (F1={ckpt.get('val_f1', 0):.4f})") + + # Normalize weights + total = sum(teacher_weights) + teacher_weights = [w / total for w in teacher_weights] + print(f"Teacher weights: {teacher_weights}") + + # Data + train_loader, val_loader, _ = create_dataloaders( + data_dir, img_size=cfg['data']['img_size'], + batch_size=cfg['data']['batch_size'], + augment_level=cfg['data']['augment_level'], + num_workers=cfg['data']['num_workers'], + use_balanced_sampling=True + ) + + # Student model + student = create_model( + cfg['model']['type'], num_classes=cfg['model']['num_classes'], + pretrained=cfg['model']['pretrained'], dropout=cfg['model']['dropout'] + ).to(device) + + # Distillation loss + criterion = DistillationLoss(temperature=4.0, alpha=0.7) + optimizer = optim.AdamW(student.parameters(), lr=cfg['training']['learning_rate'], + weight_decay=cfg['training']['weight_decay']) + scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=cfg['training']['epochs']) + scaler = GradScaler(enabled=torch.cuda.is_available()) + + os.makedirs(output_dir, exist_ok=True) + best_f1 = 0 + + for epoch in range(1, cfg['training']['epochs'] + 1): + student.train() + total_loss = 0 + + for images, labels in tqdm(train_loader, desc=f"Distill Epoch {epoch}"): + images, labels = images.to(device), labels.to(device) + + teacher_logits = get_teacher_logits(teacher_models, images, device, teacher_weights) + + optimizer.zero_grad() + with autocast(enabled=torch.cuda.is_available()): + student_logits = student(images) + loss = criterion(student_logits, teacher_logits, labels) + + scaler.scale(loss).backward() + scaler.step(optimizer) + scaler.update() + total_loss += loss.item() + + scheduler.step() + + # Validate + student.eval() + all_preds, all_labels = [], [] + with torch.no_grad(): + for images, labels in val_loader: + images = images.to(device) + logits = student(images) + preds = logits.argmax(dim=1).cpu().numpy() + all_preds.extend(preds) + all_labels.extend(labels.numpy()) + + val_f1 = f1_score(all_labels, all_preds, average='macro') + val_acc = np.mean(np.array(all_preds) == np.array(all_labels)) + avg_loss = total_loss / len(train_loader) + + print(f"Epoch {epoch}: loss={avg_loss:.4f} val_f1={val_f1:.4f} val_acc={val_acc:.4f}") + + if val_f1 > best_f1: + best_f1 = val_f1 + torch.save({ + "epoch": epoch, "model_state_dict": student.state_dict(), + "val_f1": val_f1, "val_acc": val_acc, + "model_type": cfg['model']['type'], + "num_classes": cfg['model']['num_classes'], + "config": cfg, "distilled": True, + }, os.path.join(output_dir, "distilled_student.pt")) + + print(f"\nDistillation complete. Best student F1: {best_f1:.4f}") + return best_f1 + + +def main(): + parser = argparse.ArgumentParser(description="Knowledge distillation") + parser.add_argument("--teacher_dir", type=str, default="checkpoints") + parser.add_argument("--student_config", type=str, + default="ml_pipeline/configs/mobilenet_v3.yaml") + parser.add_argument("--data_dir", type=str, required=True) + parser.add_argument("--output_dir", type=str, default="checkpoints/distilled") + args = parser.parse_args() + + with open(args.student_config) as f: + cfg = yaml.safe_load(f) + + distill(cfg, args.teacher_dir, args.data_dir, args.output_dir) + + +if __name__ == "__main__": + main() diff --git a/ml_pipeline/scripts/evaluate.py b/ml_pipeline/scripts/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..903f3d657035eb84b827357e52e1dbdda2f4a673 --- /dev/null +++ b/ml_pipeline/scripts/evaluate.py @@ -0,0 +1,212 @@ +""" +Comprehensive evaluation pipeline. +Computes: per-class P/R/F1, macro F1, confusion matrix, ROC/AUC, +top-k accuracy, ECE, reliability diagrams, robustness tests. + +Usage: + python ml_pipeline/scripts/evaluate.py --ensemble_dir checkpoints/ensemble --data_dir data/plantvillage +""" +import os +import sys +import argparse +import json +from pathlib import Path + +import numpy as np +import torch +from sklearn.metrics import ( + classification_report, confusion_matrix, f1_score, + accuracy_score, roc_auc_score, precision_recall_fscore_support +) +import matplotlib +matplotlib.use('Agg') +import matplotlib.pyplot as plt +import seaborn as sns + +sys.path.insert(0, str(Path(__file__).parent.parent.parent)) +from ml_pipeline.data.dataset import PLANTVILLAGE_CLASSES +from ml_pipeline.scripts.calibrate import compute_ece, compute_ace, plot_reliability_diagram + + +def top_k_accuracy(probs: np.ndarray, labels: np.ndarray, k: int = 5) -> float: + top_k_preds = np.argsort(probs, axis=1)[:, -k:] + correct = np.array([labels[i] in top_k_preds[i] for i in range(len(labels))]) + return correct.mean() + + +def plot_confusion_matrix(y_true, y_pred, class_names, save_path, normalize=True): + cm = confusion_matrix(y_true, y_pred) + if normalize: + cm = cm.astype('float') / cm.sum(axis=1, keepdims=True) + + fig, ax = plt.subplots(figsize=(20, 18)) + sns.heatmap(cm, annot=False, fmt='.1f' if normalize else 'd', + xticklabels=class_names, yticklabels=class_names, + cmap='Blues', ax=ax) + ax.set_xlabel('Predicted') + ax.set_ylabel('True') + ax.set_title('Confusion Matrix') + plt.xticks(rotation=90, fontsize=6) + plt.yticks(rotation=0, fontsize=6) + plt.tight_layout() + plt.savefig(save_path, dpi=150, bbox_inches='tight') + plt.close() + print(f"Saved confusion matrix to {save_path}") + + +def robustness_test(model, test_loader, device, perturbation="brightness", severity=0.3): + """Simple robustness test with brightness/blur perturbation.""" + model.eval() + all_preds, all_labels = [], [] + + for batch in test_loader: + images = batch[0].to(device) + labels = batch[1] + + if perturbation == "brightness": + images = images + severity * torch.randn_like(images) * 0.1 + images = torch.clamp(images, 0, 1) + elif perturbation == "blur": + import torch.nn.functional as F + kernel_size = int(severity * 10) * 2 + 1 + images = F.avg_pool2d(images, kernel_size, stride=1, + padding=kernel_size // 2) + + with torch.no_grad(): + logits = model(images) + preds = logits.argmax(dim=1).cpu().numpy() + all_preds.extend(preds) + all_labels.extend(labels.numpy()) + + f1 = f1_score(all_labels, all_preds, average='macro') + acc = accuracy_score(all_labels, all_preds) + return {"perturbation": perturbation, "severity": severity, "f1": f1, "accuracy": acc} + + +def full_evaluation(probs: np.ndarray, labels: np.ndarray, + output_dir: str, class_names: list = None): + """Run full evaluation suite.""" + os.makedirs(output_dir, exist_ok=True) + if class_names is None: + class_names = PLANTVILLAGE_CLASSES + + preds = probs.argmax(axis=1) + + # Basic metrics + acc = accuracy_score(labels, preds) + macro_f1 = f1_score(labels, preds, average='macro') + top3_acc = top_k_accuracy(probs, labels, k=3) + top5_acc = top_k_accuracy(probs, labels, k=5) + ece = compute_ece(probs, labels) + ace = compute_ace(probs, labels) + + print(f"\n{'='*50}") + print("EVALUATION RESULTS") + print(f"{'='*50}") + print(f"Top-1 Accuracy: {acc:.4f}") + print(f"Top-3 Accuracy: {top3_acc:.4f}") + print(f"Top-5 Accuracy: {top5_acc:.4f}") + print(f"Macro F1: {macro_f1:.4f}") + print(f"ECE: {ece:.4f}") + print(f"ACE: {ace:.4f}") + + # Per-class metrics + precision, recall, f1, support = precision_recall_fscore_support( + labels, preds, average=None, zero_division=0 + ) + + per_class = {} + low_f1_classes = [] + for i, name in enumerate(class_names[:len(f1)]): + per_class[name] = { + "precision": float(precision[i]), + "recall": float(recall[i]), + "f1": float(f1[i]), + "support": int(support[i]) + } + if f1[i] < 0.85: + low_f1_classes.append((name, f1[i])) + + if low_f1_classes: + print("\nāš ļø Classes with F1 < 0.85:") + for name, score in sorted(low_f1_classes, key=lambda x: x[1]): + print(f" {name}: F1={score:.4f}") + + # Classification report + report = classification_report(labels, preds, target_names=class_names[:len(np.unique(labels))], + zero_division=0) + print(f"\n{report}") + + # Confusion matrix + plot_confusion_matrix(labels, preds, class_names[:len(np.unique(labels))], + os.path.join(output_dir, "confusion_matrix.png")) + + # Reliability diagram + plot_reliability_diagram(probs, labels, + title=f"Reliability Diagram (ECE={ece:.4f})", + save_path=os.path.join(output_dir, "reliability_diagram.png")) + + # ROC AUC (one-vs-rest) + try: + from sklearn.preprocessing import label_binarize + labels_bin = label_binarize(labels, classes=range(probs.shape[1])) + if labels_bin.shape[1] > 1: + auc = roc_auc_score(labels_bin, probs, average='macro', multi_class='ovr') + print(f"ROC AUC (macro): {auc:.4f}") + else: + auc = None + except Exception: + auc = None + + # Save results + results = { + "top1_accuracy": float(acc), + "top3_accuracy": float(top3_acc), + "top5_accuracy": float(top5_acc), + "macro_f1": float(macro_f1), + "ece": float(ece), + "ace": float(ace), + "roc_auc_macro": float(auc) if auc else None, + "per_class": per_class, + "low_f1_classes": [(n, float(s)) for n, s in low_f1_classes], + } + with open(os.path.join(output_dir, "evaluation_results.json"), "w") as f: + json.dump(results, f, indent=2) + + print(f"\nResults saved to {output_dir}") + return results + + +def main(): + parser = argparse.ArgumentParser(description="Evaluate ensemble") + parser.add_argument("--ensemble_dir", type=str, required=True) + parser.add_argument("--data_dir", type=str, default=None) + parser.add_argument("--logits_path", type=str, default=None) + parser.add_argument("--labels_path", type=str, default=None) + args = parser.parse_args() + + output_dir = os.path.join(args.ensemble_dir, "evaluation") + + if args.logits_path: + logits = np.load(args.logits_path) + labels = np.load(args.labels_path) + probs = torch.softmax(torch.tensor(logits), dim=1).numpy() + else: + # Look for logits in checkpoint dirs + parent = os.path.dirname(args.ensemble_dir) + for d in os.listdir(parent): + logits_path = os.path.join(parent, d, "best_val_logits.npy") + if os.path.exists(logits_path): + logits = np.load(logits_path) + labels = np.load(os.path.join(parent, d, "best_val_labels.npy")) + probs = torch.softmax(torch.tensor(logits), dim=1).numpy() + break + else: + print("No logits found. Run training first.") + return + + full_evaluation(probs, labels, output_dir) + + +if __name__ == "__main__": + main() diff --git a/ml_pipeline/scripts/export_models.py b/ml_pipeline/scripts/export_models.py new file mode 100644 index 0000000000000000000000000000000000000000..298a88fc163563c6931f5062ad273915961cf9aa --- /dev/null +++ b/ml_pipeline/scripts/export_models.py @@ -0,0 +1,149 @@ +""" +Export models to ONNX, TorchScript, and TFLite formats. + +Usage: + python ml_pipeline/scripts/export_models.py --checkpoint checkpoints/efficientnet_v2/best_model.pt --format onnx torchscript + python ml_pipeline/scripts/export_models.py --checkpoint checkpoints/mobilenet_v3/best_model.pt --format tflite --quantize float16 +""" +import os +import sys +import argparse +from pathlib import Path + +import numpy as np +import torch + +sys.path.insert(0, str(Path(__file__).parent.parent.parent)) +from ml_pipeline.models.architectures import create_model + + +def export_onnx(model, input_size, output_path, num_classes=38, opset=17): + """Export model to ONNX format.""" + model.eval() + dummy = torch.randn(1, 3, input_size, input_size) + + torch.onnx.export( + model, dummy, output_path, + input_names=['image'], + output_names=['logits'], + dynamic_axes={'image': {0: 'batch'}, 'logits': {0: 'batch'}}, + opset_version=opset, + do_constant_folding=True, + ) + + # Verify + import onnx + onnx_model = onnx.load(output_path) + onnx.checker.check_model(onnx_model) + + size_mb = os.path.getsize(output_path) / (1024 * 1024) + print(f"ONNX exported: {output_path} ({size_mb:.1f} MB)") + return output_path + + +def export_torchscript(model, input_size, output_path): + """Export model to TorchScript format.""" + model.eval() + dummy = torch.randn(1, 3, input_size, input_size) + traced = torch.jit.trace(model, dummy) + traced.save(output_path) + + size_mb = os.path.getsize(output_path) / (1024 * 1024) + print(f"TorchScript exported: {output_path} ({size_mb:.1f} MB)") + return output_path + + +def export_tflite(model, input_size, output_path, quantize="none"): + """ + Export model to TFLite via ONNX → TF → TFLite conversion. + Quantization options: none, float16, int8 + """ + try: + import onnx + from onnx_tf.backend import prepare + import tensorflow as tf + except ImportError: + print("TFLite export requires: pip install onnx-tf tensorflow") + print("Skipping TFLite export.") + return None + + # First export to ONNX + onnx_path = output_path.replace('.tflite', '.onnx') + export_onnx(model, input_size, onnx_path) + + # ONNX → TF SavedModel + onnx_model = onnx.load(onnx_path) + tf_rep = prepare(onnx_model) + tf_path = output_path.replace('.tflite', '_saved_model') + tf_rep.export_graph(tf_path) + + # TF SavedModel → TFLite + converter = tf.lite.TFLiteConverter.from_saved_model(tf_path) + + if quantize == "float16": + converter.optimizations = [tf.lite.Optimize.DEFAULT] + converter.target_spec.supported_types = [tf.float16] + elif quantize == "int8": + converter.optimizations = [tf.lite.Optimize.DEFAULT] + + def representative_dataset(): + for _ in range(100): + data = np.random.randn(1, input_size, input_size, 3).astype(np.float32) + yield [data] + + converter.representative_dataset = representative_dataset + converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8] + converter.inference_input_type = tf.int8 + converter.inference_output_type = tf.int8 + + tflite_model = converter.convert() + with open(output_path, 'wb') as f: + f.write(tflite_model) + + size_mb = os.path.getsize(output_path) / (1024 * 1024) + print(f"TFLite exported: {output_path} ({size_mb:.1f} MB, quantize={quantize})") + return output_path + + +def main(): + parser = argparse.ArgumentParser(description="Export models") + parser.add_argument("--checkpoint", type=str, required=True) + parser.add_argument("--format", nargs="+", choices=["onnx", "torchscript", "tflite"], + default=["onnx"]) + parser.add_argument("--quantize", type=str, default="none", + choices=["none", "float16", "int8"]) + parser.add_argument("--output_dir", type=str, default=None) + args = parser.parse_args() + + device = torch.device('cpu') # Export on CPU + ckpt = torch.load(args.checkpoint, map_location=device, weights_only=False) + + model = create_model( + ckpt['model_type'], num_classes=ckpt['num_classes'], + pretrained=False, dropout=0.0 + ) + model.load_state_dict(ckpt['model_state_dict']) + model.eval() + + input_size = ckpt.get('config', {}).get('data', {}).get('img_size', 224) + model_name = ckpt['model_type'] + + if args.output_dir is None: + args.output_dir = os.path.dirname(args.checkpoint) + os.makedirs(args.output_dir, exist_ok=True) + + for fmt in args.format: + output_path = os.path.join(args.output_dir, f"{model_name}.{fmt}") + if fmt == "onnx": + output_path = os.path.join(args.output_dir, f"{model_name}.onnx") + export_onnx(model, input_size, output_path) + elif fmt == "torchscript": + output_path = os.path.join(args.output_dir, f"{model_name}.pt") + export_torchscript(model, input_size, output_path) + elif fmt == "tflite": + output_path = os.path.join(args.output_dir, f"{model_name}.tflite") + export_tflite(model, input_size, output_path, args.quantize) + + +if __name__ == "__main__": + main() diff --git a/ml_pipeline/scripts/generate_synthetic_data.py b/ml_pipeline/scripts/generate_synthetic_data.py new file mode 100644 index 0000000000000000000000000000000000000000..371a49ad6d8ec6f3486b49525ed85ee7d74b996d --- /dev/null +++ b/ml_pipeline/scripts/generate_synthetic_data.py @@ -0,0 +1,93 @@ +""" +Generate synthetic dataset for CI/CD testing. +Creates small random images organized in PlantVillage format. + +Usage: + python ml_pipeline/scripts/generate_synthetic_data.py --output_dir data/synthetic --num_classes 5 --num_images 50 +""" +import os +import argparse +import random +from PIL import Image +import numpy as np + + +SAMPLE_CLASSES = [ + "Tomato___healthy", + "Tomato___Bacterial_spot", + "Tomato___Early_blight", + "Apple___healthy", + "Apple___Apple_scab", + "Corn_(maize)___healthy", + "Corn_(maize)___Common_rust_", + "Grape___healthy", + "Grape___Black_rot", + "Potato___healthy", +] + + +def generate_synthetic_dataset(output_dir: str, num_classes: int = 5, + num_images_per_class: int = 10, img_size: int = 64): + """Generate small synthetic images for testing.""" + classes = SAMPLE_CLASSES[:num_classes] + + for split in ["train", "val", "test"]: + split_count = { + "train": num_images_per_class, + "val": max(3, num_images_per_class // 4), + "test": max(3, num_images_per_class // 4), + }[split] + + for cls in classes: + cls_dir = os.path.join(output_dir, split, cls) + os.makedirs(cls_dir, exist_ok=True) + + # Generate color bias based on class (so model can learn) + random.seed(hash(cls) % 2**32) + base_color = [random.randint(50, 200) for _ in range(3)] + + for i in range(split_count): + # Create an image with class-correlated color + noise + img_array = np.random.randint(0, 50, (img_size, img_size, 3), dtype=np.uint8) + for c in range(3): + img_array[:, :, c] = np.clip( + img_array[:, :, c].astype(np.int16) + base_color[c] + random.randint(-20, 20), + 0, 255 + ).astype(np.uint8) + + # Add some shapes for structure + cx, cy = random.randint(10, img_size - 10), random.randint(10, img_size - 10) + r = random.randint(5, 15) + y, x = np.ogrid[-cy:img_size - cy, -cx:img_size - cx] + mask = x * x + y * y <= r * r + img_array[mask] = [random.randint(100, 255) for _ in range(3)] + + img = Image.fromarray(img_array.astype(np.uint8)) + img.save(os.path.join(cls_dir, f"synth_{i:04d}.png")) + + total = sum( + len(os.listdir(os.path.join(output_dir, split, cls))) + for split in ["train", "val", "test"] + for cls in classes + if os.path.exists(os.path.join(output_dir, split, cls)) + ) + print(f"Generated {total} synthetic images in {output_dir}") + print(f"Classes: {classes}") + return output_dir + + +def main(): + parser = argparse.ArgumentParser(description="Generate synthetic test dataset") + parser.add_argument("--output_dir", type=str, default="data/synthetic") + parser.add_argument("--num_classes", type=int, default=5) + parser.add_argument("--num_images", type=int, default=10, + help="Images per class for training split") + parser.add_argument("--img_size", type=int, default=64) + args = parser.parse_args() + + generate_synthetic_dataset(args.output_dir, args.num_classes, + args.num_images, args.img_size) + + +if __name__ == "__main__": + main() diff --git a/ml_pipeline/scripts/hyperparam_sweep.py b/ml_pipeline/scripts/hyperparam_sweep.py new file mode 100644 index 0000000000000000000000000000000000000000..5c7051ece4a38248b4cd79e479b11c965a60054d --- /dev/null +++ b/ml_pipeline/scripts/hyperparam_sweep.py @@ -0,0 +1,68 @@ +""" +Optuna hyperparameter sweep configuration. +Usage: + python ml_pipeline/scripts/hyperparam_sweep.py --config ml_pipeline/configs/efficientnet_v2.yaml --data_dir data/plantvillage --n_trials 10 +""" +import sys +import argparse +from pathlib import Path + +import optuna +import yaml + +sys.path.insert(0, str(Path(__file__).parent.parent.parent)) +from ml_pipeline.scripts.train import train + + +def objective(trial, base_cfg, data_dir): + cfg = {k: dict(v) if isinstance(v, dict) else v for k, v in base_cfg.items()} + cfg['training'] = dict(base_cfg['training']) + cfg['data'] = dict(base_cfg['data']) + + # Search space + cfg['training']['learning_rate'] = trial.suggest_float('lr', 1e-4, 5e-3, log=True) + cfg['training']['weight_decay'] = trial.suggest_float('weight_decay', 1e-5, 1e-3, log=True) + cfg['training']['label_smoothing'] = trial.suggest_float('label_smoothing', 0.0, 0.15) + cfg['training']['mixup_alpha'] = trial.suggest_float('mixup_alpha', 0.0, 0.4) + cfg['training']['cutmix_prob'] = trial.suggest_float('cutmix_prob', 0.0, 0.7) + cfg['model'] = dict(base_cfg['model']) + cfg['model']['dropout'] = trial.suggest_float('dropout', 0.1, 0.5) + cfg['data']['augment_level'] = trial.suggest_categorical('augment_level', ['light', 'medium', 'heavy']) + cfg['training']['epochs'] = 20 # Shorter for sweep + cfg['checkpoint'] = dict(base_cfg['checkpoint']) + cfg['checkpoint']['save_dir'] = f"checkpoints/sweep/trial_{trial.number}" + cfg['loss'] = dict(base_cfg['loss']) + + best_f1 = train(cfg, data_dir) + return best_f1 + + +def main(): + parser = argparse.ArgumentParser(description="Hyperparameter sweep with Optuna") + parser.add_argument("--config", type=str, required=True) + parser.add_argument("--data_dir", type=str, required=True) + parser.add_argument("--n_trials", type=int, default=10) + parser.add_argument("--study_name", type=str, default="plantguard_sweep") + args = parser.parse_args() + + with open(args.config) as f: + cfg = yaml.safe_load(f) + + study = optuna.create_study( + direction="maximize", + study_name=args.study_name, + pruner=optuna.pruners.MedianPruner(), + ) + + study.optimize( + lambda trial: objective(trial, cfg, args.data_dir), + n_trials=args.n_trials, + show_progress_bar=True, + ) + + print(f"\nBest trial: F1={study.best_value:.4f}") + print(f"Best params: {study.best_params}") + + +if __name__ == "__main__": + main() diff --git a/ml_pipeline/scripts/stacking.py b/ml_pipeline/scripts/stacking.py new file mode 100644 index 0000000000000000000000000000000000000000..8783541ffed51974aacbe17c97ce481244be0c9e --- /dev/null +++ b/ml_pipeline/scripts/stacking.py @@ -0,0 +1,320 @@ +""" +Two-stage ensemble system: + Stage A: Validation-weighted soft voting + Stage B: Stacked meta-learner (LightGBM) on k-fold OOF logits + +Usage: + python ml_pipeline/scripts/stacking.py --models_dir checkpoints --data_dir data/plantvillage --n_folds 5 +""" +import os +import sys +import argparse +import json +from pathlib import Path + +import numpy as np +import torch +from torch.utils.data import DataLoader +from sklearn.model_selection import StratifiedKFold +from sklearn.metrics import f1_score, accuracy_score +import lightgbm as lgb +import joblib + +sys.path.insert(0, str(Path(__file__).parent.parent.parent)) +from ml_pipeline.data.dataset import PlantDiseaseDataset, get_val_transforms +from ml_pipeline.models.architectures import create_model + + +def load_trained_model(checkpoint_path: str, device: torch.device): + """Load a trained model from checkpoint.""" + ckpt = torch.load(checkpoint_path, map_location=device, weights_only=False) + model = create_model( + ckpt['model_type'], + num_classes=ckpt['num_classes'], + pretrained=False, + dropout=0.0 # No dropout during inference + ) + model.load_state_dict(ckpt['model_state_dict']) + model.to(device) + model.eval() + return model, ckpt + + +@torch.no_grad() +def extract_logits(model, loader, device): + """Extract logits and labels from a model on a dataset.""" + all_logits, all_labels = [], [] + for batch in loader: + images = batch[0].to(device) + labels = batch[1] + logits = model(images) + all_logits.append(logits.cpu().numpy()) + all_labels.append(labels.numpy()) + return np.concatenate(all_logits), np.concatenate(all_labels) + + +def compute_image_features(images_loader): + """Compute brightness/contrast features for meta-learner input.""" + features = [] + for batch in images_loader: + imgs = batch[0] # (B, C, H, W) + # Per-image mean brightness, std, channel means + brightness = imgs.mean(dim=(1, 2, 3)).numpy() + contrast = imgs.std(dim=(1, 2, 3)).numpy() + r_mean = imgs[:, 0].mean(dim=(1, 2)).numpy() + g_mean = imgs[:, 1].mean(dim=(1, 2)).numpy() + b_mean = imgs[:, 2].mean(dim=(1, 2)).numpy() + batch_feats = np.stack([brightness, contrast, r_mean, g_mean, b_mean], axis=1) + features.append(batch_feats) + return np.concatenate(features) + + +class WeightedSoftVoting: + """Stage A: Validation-weighted soft voting ensemble.""" + + def __init__(self, model_weights: dict): + """ + model_weights: {model_name: weight} based on validation F1 + """ + self.weights = model_weights + total = sum(model_weights.values()) + self.norm_weights = {k: v / total for k, v in model_weights.items()} + + def predict(self, logits_dict: dict) -> np.ndarray: + """ + logits_dict: {model_name: (N, C) logits array} + Returns: (N, C) weighted probability array + """ + weighted_probs = None + for name, logits in logits_dict.items(): + probs = self._softmax(logits) + w = self.norm_weights.get(name, 1.0 / len(logits_dict)) + if weighted_probs is None: + weighted_probs = w * probs + else: + weighted_probs += w * probs + return weighted_probs + + @staticmethod + def _softmax(logits): + exp = np.exp(logits - logits.max(axis=1, keepdims=True)) + return exp / exp.sum(axis=1, keepdims=True) + + +class StackedEnsemble: + """ + Stage B: Stacked meta-learner using k-fold OOF predictions. + Trains LightGBM on concatenated model logits + image features. + """ + + def __init__(self, num_classes: int = 38, n_folds: int = 5): + self.num_classes = num_classes + self.n_folds = n_folds + self.meta_model = None + + def generate_oof_predictions(self, models_dir: str, data_dir: str, device: torch.device): + """ + Generate out-of-fold predictions for all base models using k-fold CV. + This avoids data leakage in the stacking process. + """ + # Load validation dataset + val_dir = os.path.join(data_dir, "val") + val_dataset = PlantDiseaseDataset(val_dir, get_val_transforms(224)) + labels = np.array(val_dataset.targets) + n_samples = len(val_dataset) + + # Discover trained models + model_dirs = [] + for d in sorted(os.listdir(models_dir)): + ckpt_path = os.path.join(models_dir, d, "best_model.pt") + if os.path.exists(ckpt_path): + model_dirs.append((d, ckpt_path)) + + print(f"Found {len(model_dirs)} trained models") + + # Collect all model logits + all_model_logits = {} + model_f1_scores = {} + + for model_name, ckpt_path in model_dirs: + print(f"Extracting logits from {model_name}...") + model, ckpt = load_trained_model(ckpt_path, device) + val_f1 = ckpt.get('val_f1', 0.5) + model_f1_scores[model_name] = val_f1 + + loader = DataLoader(val_dataset, batch_size=64, shuffle=False, num_workers=2) + logits, _ = extract_logits(model, loader, device) + all_model_logits[model_name] = logits + del model + torch.cuda.empty_cache() if torch.cuda.is_available() else None + + # Generate OOF predictions using k-fold + skf = StratifiedKFold(n_splits=self.n_folds, shuffle=True, random_state=42) + + # Stack all model logits: (N, num_models * num_classes) + model_names = sorted(all_model_logits.keys()) + stacked_logits = np.hstack([all_model_logits[name] for name in model_names]) + + # Compute image features + loader = DataLoader(val_dataset, batch_size=64, shuffle=False, num_workers=2) + img_features = compute_image_features(loader) + + # Confidence features: max prob, entropy per model + confidence_features = [] + for name in model_names: + probs = WeightedSoftVoting._softmax(all_model_logits[name]) + max_prob = probs.max(axis=1, keepdims=True) + entropy = -(probs * np.log(probs + 1e-10)).sum(axis=1, keepdims=True) + confidence_features.append(np.hstack([max_prob, entropy])) + confidence_features = np.hstack(confidence_features) + + # Final meta-features: logits + image features + confidence + meta_features = np.hstack([stacked_logits, img_features, confidence_features]) + + # K-fold OOF training + oof_preds = np.zeros((n_samples, self.num_classes)) + + for fold, (train_idx, val_idx) in enumerate(skf.split(meta_features, labels)): + print(f" Fold {fold + 1}/{self.n_folds}") + + X_train = meta_features[train_idx] + y_train = labels[train_idx] + X_val = meta_features[val_idx] + + # Train LightGBM + lgb_model = lgb.LGBMClassifier( + n_estimators=200, num_leaves=31, learning_rate=0.05, + max_depth=6, min_child_samples=20, subsample=0.8, + colsample_bytree=0.8, reg_alpha=0.1, reg_lambda=0.1, + n_jobs=-1, random_state=42 + fold, verbose=-1, + num_class=self.num_classes, objective='multiclass' + ) + lgb_model.fit(X_train, y_train) + + # OOF predictions + oof_preds[val_idx] = lgb_model.predict_proba(X_val) + + # Evaluate OOF + oof_labels = oof_preds.argmax(axis=1) + oof_f1 = f1_score(labels, oof_labels, average='macro') + oof_acc = accuracy_score(labels, oof_labels) + print(f"\nOOF Results: F1={oof_f1:.4f}, Acc={oof_acc:.4f}") + + # Train final meta-model on all data + self.meta_model = lgb.LGBMClassifier( + n_estimators=200, num_leaves=31, learning_rate=0.05, + max_depth=6, min_child_samples=20, subsample=0.8, + colsample_bytree=0.8, reg_alpha=0.1, reg_lambda=0.1, + n_jobs=-1, random_state=42, verbose=-1, + num_class=self.num_classes, objective='multiclass' + ) + self.meta_model.fit(meta_features, labels) + + return { + "model_names": model_names, + "model_f1_scores": model_f1_scores, + "oof_f1": oof_f1, + "oof_acc": oof_acc, + "feature_dim": meta_features.shape[1], + } + + def predict(self, meta_features: np.ndarray) -> np.ndarray: + """Predict using the trained meta-model.""" + return self.meta_model.predict_proba(meta_features) + + def save(self, path: str): + joblib.dump(self.meta_model, path) + print(f"Meta-model saved to {path}") + + def load(self, path: str): + self.meta_model = joblib.load(path) + + +def compute_uncertainty(logits_dict: dict) -> dict: + """ + Compute uncertainty estimates: + - Predictive entropy (aleatoric) + - Model disagreement / std across models (epistemic) + - Combined uncertainty score + """ + model_probs = [] + for name, logits in logits_dict.items(): + probs = WeightedSoftVoting._softmax(logits) + model_probs.append(probs) + + model_probs = np.stack(model_probs, axis=0) # (M, N, C) + mean_probs = model_probs.mean(axis=0) # (N, C) + + # Predictive entropy + pred_entropy = -(mean_probs * np.log(mean_probs + 1e-10)).sum(axis=1) + + # Model disagreement (mean pairwise std) + model_std = model_probs.std(axis=0).mean(axis=1) + + # Combined uncertainty + max_entropy = np.log(mean_probs.shape[1]) + norm_entropy = pred_entropy / max_entropy + uncertainty = 0.5 * norm_entropy + 0.5 * (model_std / model_std.max()) + + return { + "predictive_entropy": pred_entropy, + "model_disagreement": model_std, + "uncertainty": uncertainty, + } + + +def main(): + parser = argparse.ArgumentParser(description="Run stacking ensemble") + parser.add_argument("--models_dir", type=str, default="checkpoints") + parser.add_argument("--data_dir", type=str, required=True) + parser.add_argument("--n_folds", type=int, default=5) + parser.add_argument("--output_dir", type=str, default="checkpoints/ensemble") + args = parser.parse_args() + + device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + os.makedirs(args.output_dir, exist_ok=True) + + # Stage A: Weighted soft voting + print("=" * 60) + print("Stage A: Validation-weighted soft voting") + print("=" * 60) + + model_dirs = [] + model_weights = {} + for d in sorted(os.listdir(args.models_dir)): + ckpt_path = os.path.join(args.models_dir, d, "best_model.pt") + if os.path.exists(ckpt_path): + ckpt = torch.load(ckpt_path, map_location='cpu', weights_only=False) + model_dirs.append((d, ckpt_path)) + model_weights[d] = ckpt.get('val_f1', 0.5) + + voting = WeightedSoftVoting(model_weights) + print(f"Model weights: {voting.norm_weights}") + + # Stage B: Stacked ensemble + print("\n" + "=" * 60) + print("Stage B: Stacked meta-learner (LightGBM)") + print("=" * 60) + + stacker = StackedEnsemble(num_classes=38, n_folds=args.n_folds) + results = stacker.generate_oof_predictions(args.models_dir, args.data_dir, device) + + # Save + stacker.save(os.path.join(args.output_dir, "meta_model.joblib")) + + with open(os.path.join(args.output_dir, "ensemble_config.json"), "w") as f: + json.dump({ + "model_names": results["model_names"], + "model_f1_scores": results["model_f1_scores"], + "voting_weights": voting.norm_weights, + "oof_f1": results["oof_f1"], + "oof_acc": results["oof_acc"], + "n_folds": args.n_folds, + "feature_dim": results["feature_dim"], + }, f, indent=2) + + print(f"\nEnsemble artifacts saved to {args.output_dir}") + + +if __name__ == "__main__": + main() diff --git a/ml_pipeline/scripts/train.py b/ml_pipeline/scripts/train.py new file mode 100644 index 0000000000000000000000000000000000000000..7dce560bc922cc56e31a90705abfaabda30669d2 --- /dev/null +++ b/ml_pipeline/scripts/train.py @@ -0,0 +1,321 @@ +""" +Training script for individual base models. +Supports: AdamW, cosine/onecycle LR, label smoothing, focal loss, +MixUp/CutMix, early stopping, checkpoint saving, logit extraction. + +Usage: + python ml_pipeline/scripts/train.py --config ml_pipeline/configs/efficientnet_v2.yaml --data_dir data/plantvillage + + # Multi-GPU + torchrun --nproc_per_node=2 ml_pipeline/scripts/train.py --config ml_pipeline/configs/efficientnet_v2.yaml --data_dir data/plantvillage +""" +import sys +import argparse +import json +from pathlib import Path + +import numpy as np +import torch +import torch.nn as nn +import torch.optim as optim +from torch.cuda.amp import GradScaler, autocast +from torch.utils.tensorboard import SummaryWriter +from sklearn.metrics import f1_score +import yaml +from tqdm import tqdm + +sys.path.insert(0, str(Path(__file__).parent.parent.parent)) +from ml_pipeline.data.dataset import create_dataloaders, MixUpCutMix +from ml_pipeline.models.architectures import create_model + + +class FocalLoss(nn.Module): + """Focal Loss for handling class imbalance.""" + def __init__(self, gamma=2.0, alpha=None, label_smoothing=0.0, num_classes=38): + super().__init__() + self.gamma = gamma + self.alpha = alpha + self.label_smoothing = label_smoothing + self.num_classes = num_classes + + def forward(self, logits, targets): + if targets.dim() > 1: # one-hot (from MixUp/CutMix) + ce = -targets * torch.log_softmax(logits, dim=1) + pt = torch.exp(-ce) + focal = ((1 - pt) ** self.gamma * ce).sum(dim=1).mean() + return focal + + ce = nn.functional.cross_entropy(logits, targets, reduction='none', + label_smoothing=self.label_smoothing) + pt = torch.exp(-ce) + focal = ((1 - pt) ** self.gamma * ce).mean() + return focal + + +class EarlyStopping: + """Early stopping based on validation metric.""" + def __init__(self, patience=10, mode='max'): + self.patience = patience + self.mode = mode + self.best = -float('inf') if mode == 'max' else float('inf') + self.counter = 0 + + def step(self, metric) -> bool: + improved = (metric > self.best) if self.mode == 'max' else (metric < self.best) + if improved: + self.best = metric + self.counter = 0 + return False + self.counter += 1 + return self.counter >= self.patience + + +def train_one_epoch(model, loader, criterion, optimizer, scaler, mixup_fn, device, epoch, cfg): + model.train() + total_loss = 0 + all_preds, all_labels = [], [] + + pbar = tqdm(loader, desc=f"Train Epoch {epoch}") + for images, labels in pbar: + images, labels = images.to(device), labels.to(device) + + # MixUp/CutMix + use_mixup = cfg['training'].get('mixup_alpha', 0) > 0 and mixup_fn is not None + if use_mixup and np.random.random() < 0.5: + images, labels_mixed = mixup_fn(images, labels) + is_mixed = True + else: + is_mixed = False + + optimizer.zero_grad() + with autocast(enabled=torch.cuda.is_available()): + logits = model(images) + if is_mixed: + loss = criterion(logits, labels_mixed) + else: + loss = criterion(logits, labels) + + scaler.scale(loss).backward() + if cfg['training'].get('gradient_clip_val', 0) > 0: + scaler.unscale_(optimizer) + nn.utils.clip_grad_norm_(model.parameters(), cfg['training']['gradient_clip_val']) + scaler.step(optimizer) + scaler.update() + + total_loss += loss.item() + if not is_mixed: + preds = logits.argmax(dim=1).cpu().numpy() + all_preds.extend(preds) + all_labels.extend(labels.cpu().numpy()) + + pbar.set_postfix(loss=f"{loss.item():.4f}") + + avg_loss = total_loss / len(loader) + f1 = f1_score(all_labels, all_preds, average='macro', zero_division=0) if all_labels else 0.0 + return avg_loss, f1 + + +@torch.no_grad() +def validate(model, loader, criterion, device): + model.eval() + total_loss = 0 + all_preds, all_labels, all_logits = [], [], [] + + for images, labels in tqdm(loader, desc="Validating"): + images, labels = images.to(device), labels.to(device) + logits = model(images) + loss = criterion(logits, labels) + + total_loss += loss.item() + preds = logits.argmax(dim=1).cpu().numpy() + all_preds.extend(preds) + all_labels.extend(labels.cpu().numpy()) + all_logits.append(logits.cpu().numpy()) + + avg_loss = total_loss / len(loader) + f1 = f1_score(all_labels, all_preds, average='macro', zero_division=0) + acc = np.mean(np.array(all_preds) == np.array(all_labels)) + all_logits = np.concatenate(all_logits, axis=0) + + return avg_loss, f1, acc, all_logits, np.array(all_labels) + + +def train(cfg: dict, data_dir: str): + # Setup + seed = cfg['training']['seed'] + torch.manual_seed(seed) + np.random.seed(seed) + device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + print(f"Device: {device}, Seed: {seed}") + + # Data + train_loader, val_loader, _ = create_dataloaders( + data_dir, + img_size=cfg['data']['img_size'], + batch_size=cfg['data']['batch_size'], + augment_level=cfg['data']['augment_level'], + num_workers=cfg['data']['num_workers'], + use_balanced_sampling=cfg['data']['use_balanced_sampling'] + ) + + # Model + model = create_model( + cfg['model']['type'], + num_classes=cfg['model']['num_classes'], + pretrained=cfg['model']['pretrained'], + dropout=cfg['model']['dropout'] + ).to(device) + + num_params = sum(p.numel() for p in model.parameters()) / 1e6 + print(f"Model: {cfg['model']['type']}, Params: {num_params:.1f}M") + + # Loss + if cfg['loss']['type'] == 'focal': + criterion = FocalLoss( + gamma=cfg['loss']['focal_gamma'], + label_smoothing=cfg['training']['label_smoothing'], + num_classes=cfg['model']['num_classes'] + ) + else: + criterion = nn.CrossEntropyLoss(label_smoothing=cfg['training']['label_smoothing']) + + # Optimizer + optimizer = optim.AdamW( + model.parameters(), + lr=cfg['training']['learning_rate'], + weight_decay=cfg['training']['weight_decay'] + ) + + # Scheduler + if cfg['training']['scheduler'] == 'cosine': + scheduler = optim.lr_scheduler.CosineAnnealingLR( + optimizer, T_max=cfg['training']['epochs'] - cfg['training']['warmup_epochs'] + ) + else: # onecycle + scheduler = optim.lr_scheduler.OneCycleLR( + optimizer, + max_lr=cfg['training']['learning_rate'], + epochs=cfg['training']['epochs'], + steps_per_epoch=len(train_loader) + ) + + # Warmup + warmup_scheduler = optim.lr_scheduler.LinearLR( + optimizer, start_factor=0.01, total_iters=cfg['training']['warmup_epochs'] + ) if cfg['training']['warmup_epochs'] > 0 else None + + scaler = GradScaler(enabled=torch.cuda.is_available()) + mixup_fn = MixUpCutMix( + mixup_alpha=cfg['training']['mixup_alpha'], + cutmix_prob=cfg['training']['cutmix_prob'], + num_classes=cfg['model']['num_classes'] + ) + + early_stopping = EarlyStopping( + patience=cfg['training']['early_stopping_patience'], mode='max' + ) + + # Checkpoint directory + save_dir = Path(cfg['checkpoint']['save_dir']) + save_dir.mkdir(parents=True, exist_ok=True) + writer = SummaryWriter(log_dir=str(save_dir / "logs")) + + best_f1 = 0 + history = [] + + for epoch in range(1, cfg['training']['epochs'] + 1): + # Train + train_loss, train_f1 = train_one_epoch( + model, train_loader, criterion, optimizer, scaler, mixup_fn, device, epoch, cfg + ) + + # Validate + val_loss, val_f1, val_acc, val_logits, val_labels = validate( + model, val_loader, criterion, device + ) + + # Scheduler step + if warmup_scheduler and epoch <= cfg['training']['warmup_epochs']: + warmup_scheduler.step() + elif cfg['training']['scheduler'] == 'cosine': + scheduler.step() + + # Logging + lr = optimizer.param_groups[0]['lr'] + print(f"Epoch {epoch}: train_loss={train_loss:.4f} train_f1={train_f1:.4f} " + f"val_loss={val_loss:.4f} val_f1={val_f1:.4f} val_acc={val_acc:.4f} lr={lr:.6f}") + + writer.add_scalars("loss", {"train": train_loss, "val": val_loss}, epoch) + writer.add_scalars("f1", {"train": train_f1, "val": val_f1}, epoch) + writer.add_scalar("val_acc", val_acc, epoch) + writer.add_scalar("lr", lr, epoch) + + history.append({ + "epoch": epoch, "train_loss": train_loss, "train_f1": train_f1, + "val_loss": val_loss, "val_f1": val_f1, "val_acc": val_acc, "lr": lr + }) + + # Save best checkpoint + if val_f1 > best_f1: + best_f1 = val_f1 + checkpoint = { + "epoch": epoch, "model_state_dict": model.state_dict(), + "optimizer_state_dict": optimizer.state_dict(), + "val_f1": val_f1, "val_acc": val_acc, "val_loss": val_loss, + "config": cfg, "num_classes": cfg['model']['num_classes'], + "model_type": cfg['model']['type'], + } + torch.save(checkpoint, save_dir / "best_model.pt") + np.save(save_dir / "best_val_logits.npy", val_logits) + np.save(save_dir / "best_val_labels.npy", val_labels) + print(f" → Saved best model (F1={val_f1:.4f})") + + # Early stopping + if early_stopping.step(val_f1): + print(f"Early stopping at epoch {epoch}") + break + + # Save training history + with open(save_dir / "training_history.json", "w") as f: + json.dump(history, f, indent=2) + + writer.close() + print(f"\nTraining complete. Best val F1: {best_f1:.4f}") + print(f"Checkpoint saved to: {save_dir}") + return best_f1 + + +def main(): + parser = argparse.ArgumentParser(description="Train a base model") + parser.add_argument("--config", type=str, required=True, help="Path to YAML config") + parser.add_argument("--data_dir", type=str, required=True, help="Path to split dataset") + parser.add_argument("--override", nargs="*", help="Override config values (key=value)") + args = parser.parse_args() + + with open(args.config) as f: + cfg = yaml.safe_load(f) + + # Apply overrides + if args.override: + for ov in args.override: + keys, val = ov.split("=", 1) + keys = keys.split(".") + d = cfg + for k in keys[:-1]: + d = d[k] + # Try to parse as int/float/bool + try: + val = int(val) + except ValueError: + try: + val = float(val) + except ValueError: + if val.lower() in ('true', 'false'): + val = val.lower() == 'true' + d[keys[-1]] = val + + train(cfg, args.data_dir) + + +if __name__ == "__main__": + main() diff --git a/ml_pipeline/scripts/train_all.py b/ml_pipeline/scripts/train_all.py new file mode 100644 index 0000000000000000000000000000000000000000..441cda2bc8f54017a6db41e540dfda7eea8cbfde --- /dev/null +++ b/ml_pipeline/scripts/train_all.py @@ -0,0 +1,63 @@ +""" +Train all 5 base models sequentially with their configs. + +Usage: + python ml_pipeline/scripts/train_all.py --data_dir data/plantvillage +""" +import os +import sys +import argparse +from pathlib import Path + +import yaml + +sys.path.insert(0, str(Path(__file__).parent.parent.parent)) +from ml_pipeline.scripts.train import train + + +CONFIGS = [ + "ml_pipeline/configs/efficientnet_v2.yaml", + "ml_pipeline/configs/resnet50.yaml", + "ml_pipeline/configs/convnext_tiny.yaml", + "ml_pipeline/configs/swin_tiny.yaml", + "ml_pipeline/configs/mobilenet_v3.yaml", +] + + +def main(): + parser = argparse.ArgumentParser(description="Train all base models") + parser.add_argument("--data_dir", type=str, required=True) + parser.add_argument("--configs", nargs="*", default=None) + args = parser.parse_args() + + configs = args.configs or CONFIGS + results = {} + + for config_path in configs: + print(f"\n{'='*60}") + print(f"Training: {config_path}") + print(f"{'='*60}") + + with open(config_path) as f: + cfg = yaml.safe_load(f) + + try: + best_f1 = train(cfg, args.data_dir) + results[config_path] = {"status": "success", "best_f1": best_f1} + except Exception as e: + print(f"Error training {config_path}: {e}") + results[config_path] = {"status": "error", "error": str(e)} + + print(f"\n{'='*60}") + print("TRAINING SUMMARY") + print(f"{'='*60}") + for config, result in results.items(): + model = os.path.basename(config).replace('.yaml', '') + if result['status'] == 'success': + print(f" {model}: F1={result['best_f1']:.4f} āœ“") + else: + print(f" {model}: FAILED - {result['error']}") + + +if __name__ == "__main__": + main() diff --git a/ml_pipeline/tests/__init__.py b/ml_pipeline/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/ml_pipeline/tests/__pycache__/__init__.cpython-311.pyc b/ml_pipeline/tests/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6e34f61e8aa71adb837d99120192734915d0eba7 Binary files /dev/null and b/ml_pipeline/tests/__pycache__/__init__.cpython-311.pyc differ diff --git a/ml_pipeline/tests/__pycache__/test_pipeline.cpython-311-pytest-8.4.1.pyc b/ml_pipeline/tests/__pycache__/test_pipeline.cpython-311-pytest-8.4.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c250fd6e27ef76d2c15909242e1e738c6d836b6 Binary files /dev/null and b/ml_pipeline/tests/__pycache__/test_pipeline.cpython-311-pytest-8.4.1.pyc differ diff --git a/ml_pipeline/tests/test_pipeline.py b/ml_pipeline/tests/test_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..9d40b095496b2a3efb6689d60603a9008fce74f1 --- /dev/null +++ b/ml_pipeline/tests/test_pipeline.py @@ -0,0 +1,135 @@ +"""Unit tests for the ML pipeline.""" +import os +import sys +import tempfile +import shutil +from pathlib import Path + +import numpy as np +import torch +import pytest + +sys.path.insert(0, str(Path(__file__).parent.parent.parent)) +from ml_pipeline.models.architectures import create_model, MODEL_REGISTRY +from ml_pipeline.data.dataset import ( + PlantDiseaseDataset, get_train_transforms, get_val_transforms, + MixUpCutMix, PLANTVILLAGE_CLASSES +) +from ml_pipeline.scripts.calibrate import TemperatureScaling, compute_ece +from ml_pipeline.scripts.generate_synthetic_data import generate_synthetic_dataset + + +@pytest.fixture(scope="module") +def synthetic_data_dir(): + """Generate a tiny synthetic dataset for testing.""" + tmpdir = tempfile.mkdtemp(prefix="plantguard_test_") + generate_synthetic_dataset(tmpdir, num_classes=3, num_images_per_class=5, img_size=32) + yield tmpdir + shutil.rmtree(tmpdir, ignore_errors=True) + + +class TestModels: + """Test model creation and forward pass.""" + + @pytest.mark.parametrize("model_type", list(MODEL_REGISTRY.keys())) + def test_model_creation(self, model_type): + model = create_model(model_type, num_classes=10, pretrained=False, dropout=0.1) + assert model is not None + params = sum(p.numel() for p in model.parameters()) + assert params > 0 + + def test_model_forward(self): + model = create_model("mobilenet_v3", num_classes=5, pretrained=False) + x = torch.randn(2, 3, 224, 224) + out = model(x) + assert out.shape == (2, 5) + + def test_model_features(self): + model = create_model("resnet50", num_classes=5, pretrained=False) + x = torch.randn(2, 3, 224, 224) + features = model.get_features(x) + assert features.dim() == 2 + assert features.shape[0] == 2 + + +class TestDataPipeline: + """Test data loading and augmentation.""" + + def test_transforms(self): + for level in ["light", "medium", "heavy"]: + t = get_train_transforms(img_size=64, augment_level=level) + assert t is not None + + def test_val_transforms(self): + t = get_val_transforms(img_size=64) + assert t is not None + + def test_dataset(self, synthetic_data_dir): + t = get_val_transforms(32) + ds = PlantDiseaseDataset(os.path.join(synthetic_data_dir, "train"), transform=t) + assert len(ds) > 0 + img, label = ds[0] + assert img.shape[0] == 3 + assert isinstance(label, int) + + def test_class_weights(self, synthetic_data_dir): + t = get_val_transforms(32) + ds = PlantDiseaseDataset(os.path.join(synthetic_data_dir, "train"), transform=t) + weights = ds.get_class_weights() + assert len(weights) == len(ds.classes) + assert (weights > 0).all() + + def test_mixup(self): + mixer = MixUpCutMix(mixup_alpha=0.2, cutmix_prob=0.0, num_classes=5) + images = torch.randn(4, 3, 32, 32) + targets = torch.tensor([0, 1, 2, 3]) + mixed_img, mixed_targets = mixer(images, targets) + assert mixed_img.shape == images.shape + assert mixed_targets.shape == (4, 5) + + def test_cutmix(self): + mixer = MixUpCutMix(mixup_alpha=0.2, cutmix_prob=1.0, num_classes=5) + images = torch.randn(4, 3, 32, 32) + targets = torch.tensor([0, 1, 2, 3]) + mixed_img, mixed_targets = mixer(images, targets) + assert mixed_img.shape == images.shape + + +class TestCalibration: + """Test temperature scaling and ECE.""" + + def test_temperature_scaling(self): + ts = TemperatureScaling() + logits = np.random.randn(100, 5).astype(np.float32) + labels = np.random.randint(0, 5, 100) + temp = ts.fit(logits, labels) + assert temp > 0 + + def test_calibrate(self): + ts = TemperatureScaling() + logits = np.random.randn(50, 5).astype(np.float32) + labels = np.random.randint(0, 5, 50) + ts.fit(logits, labels) + probs = ts.calibrate(logits) + assert probs.shape == logits.shape + assert np.allclose(probs.sum(axis=1), 1.0, atol=1e-5) + + def test_ece(self): + probs = np.random.dirichlet(np.ones(5), size=100) + labels = np.random.randint(0, 5, 100) + ece = compute_ece(probs, labels) + assert 0 <= ece <= 1 + + def test_class_names(self): + assert len(PLANTVILLAGE_CLASSES) == 38 + + +class TestSyntheticData: + """Test synthetic data generation.""" + + def test_generate(self, synthetic_data_dir): + for split in ["train", "val", "test"]: + split_dir = os.path.join(synthetic_data_dir, split) + assert os.path.exists(split_dir) + classes = os.listdir(split_dir) + assert len(classes) == 3