Spaces:
Configuration error

royajaygit commited on
Commit
fdc2547
·
0 Parent(s):

Initial commit - cleaned repo without large files

Browse files
.gitattributes ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ *.onnx filter=lfs diff=lfs merge=lfs -text
2
+ *.csv filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Ignore large model and data files
2
+ api/ViT_PreProcessing-ops11-preprocessing-int-dynam_graph.onnx
3
+ api/venomstatus_with_antivenom.csv
4
+ api/venomstatus_with_antivenom.xlsx
5
+ api/train_metadata.csv
6
+
7
+ # Python caches
8
+ __pycache__/
9
+ *.pyc
10
+ *.pyo
11
+ *.pyd
12
+
13
+ # Environment files
14
+ .env
15
+
16
+ # OS/other unnecessary files
17
+ .DS_Store
Dockerfile ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /snake-ai-api/Dockerfile
2
+
3
+ # --- STAGE 1: Build Environment ---
4
+ FROM python:3.10 as base
5
+
6
+ ENV PYTHONUNBUFFERED=1
7
+ ENV PYTHONDONTWRITEBYTECODE=1
8
+
9
+ RUN apt-get update && apt-get install -y --no-install-recommends \
10
+ build-essential \
11
+ libpq-dev \
12
+ gcc \
13
+ && rm -rf /var/lib/apt/lists/*
14
+
15
+ WORKDIR /app
16
+
17
+ # Copy requirements first (for efficient Docker caching)
18
+ COPY requirements.txt .
19
+ RUN pip install --no-cache-dir -r requirements.txt
20
+
21
+ # Install Gunicorn and Uvicorn
22
+ RUN pip install --no-cache-dir gunicorn uvicorn[standard] gdown
23
+
24
+ # --- STAGE 2: Final Production Image ---
25
+ FROM python:3.10-slim
26
+
27
+ WORKDIR /app
28
+
29
+ # Copy Python dependencies from base
30
+ COPY --from=base /usr/local /usr/local
31
+
32
+ # Copy API code
33
+ COPY api /app/api
34
+
35
+ # ✅ Copy the correct download script
36
+ COPY download_files.py /app/download_files.py
37
+
38
+ # --- Download model and dataset files automatically ---
39
+ RUN python download_files.py
40
+
41
+ # Expose the API port
42
+ EXPOSE 80
43
+
44
+ # Run FastAPI using Gunicorn + Uvicorn workers
45
+ CMD ["gunicorn", "-w", "4", "-k", "uvicorn.workers.UvicornWorker", "--bind", "0.0.0.0:80", "api.main:app"]
api/__init__.py ADDED
File without changes
api/main.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /snake-ai-api/api/main.py
2
+
3
+ import io
4
+ import base64
5
+ from fastapi import FastAPI, UploadFile, File, Form
6
+ from fastapi.responses import JSONResponse
7
+ from fastapi.middleware.cors import CORSMiddleware # CRITICAL ADDITION
8
+ from PIL import Image
9
+
10
+ # 1. Import your core logic from the service file
11
+ from .model_service import predict_snake, generate_image_from_text
12
+
13
+ # Initialize the FastAPI application
14
+ app = FastAPI(title="Snake AI Detection API")
15
+
16
+ # ====================================================================
17
+ # --- PRODUCTION CHANGE: ADD CORS MIDDLEWARE ---
18
+ # ====================================================================
19
+ # Define the allowed origins (replace the placeholder with your Next.js domain)
20
+ origins = [
21
+ "http://localhost:3000", # Next.js local development
22
+ "http://localhost:8080", # Another common dev port
23
+ "http://localhost",
24
+ "https://your-production-frontend-domain.com", # <--- **REPLACE THIS WITH YOUR LIVE NEXT.JS DOMAIN**
25
+ ]
26
+
27
+ app.add_middleware(
28
+ CORSMiddleware,
29
+ allow_origins=origins, # List of allowed origins
30
+ allow_credentials=True,
31
+ allow_methods=["*"], # Allow POST, GET, etc.
32
+ allow_headers=["*"],
33
+ )
34
+ # ====================================================================
35
+
36
+
37
+ # ====================================================================
38
+ # Endpoint 1: Image Upload and Prediction
39
+ # ====================================================================
40
+
41
+ @app.post("/predict-image")
42
+ async def predict_image_endpoint(file: UploadFile = File(...)):
43
+ """Accepts an image file upload and returns the snake identification results."""
44
+ try:
45
+ image_data = await file.read()
46
+ image = Image.open(io.BytesIO(image_data))
47
+
48
+ prediction_result = predict_snake(image)
49
+
50
+ return JSONResponse(content=prediction_result)
51
+
52
+ except Exception as e:
53
+ print(f"Prediction Error: {e}")
54
+ return JSONResponse(content={"error": "An error occurred during image prediction.", "detail": str(e)}, status_code=500)
55
+
56
+ # ====================================================================
57
+ # Endpoint 2: Text Description, Image Generation, and Prediction
58
+ # ====================================================================
59
+
60
+ @app.post("/generate-and-predict")
61
+ async def generate_and_predict_endpoint(description: str = Form(...)):
62
+ """Generates an image from text, runs prediction, and returns the image (Base64) and results."""
63
+ try:
64
+ image_bytes, gen_image_pil = generate_image_from_text(description)
65
+ prediction_result = predict_snake(gen_image_pil)
66
+
67
+ # Encode the generated image to Base64 for display
68
+ base64_image = base64.b64encode(image_bytes).decode('utf-8')
69
+
70
+ response_data = {
71
+ "generated_image_base64": base64_image,
72
+ "prediction": prediction_result
73
+ }
74
+
75
+ return JSONResponse(content=response_data)
76
+
77
+ except Exception as e:
78
+ print(f"Generation/Prediction Error: {e}")
79
+ return JSONResponse(content={"error": "An error occurred during image generation or prediction.", "detail": str(e)}, status_code=500)
api/min-train_metadata.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d796d682a6352276a124bd409de05eaafbaa05753fd8af5a0ed42770e558acb3
3
+ size 13735476
api/model_service.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /snake-ai-api/api/model_service.py
2
+
3
+ import os
4
+ import io
5
+ import pandas as pd
6
+ import numpy as np
7
+ import onnxruntime as ort
8
+ from PIL import Image
9
+ import torch # Included because torchvision requires it, though only transforms are used here
10
+ from torchvision import transforms
11
+ from scipy.special import softmax
12
+ import google.generativeai as genai
13
+ from pathlib import Path # CRITICAL for production-ready file path handling
14
+
15
+ # ===================== 1. GLOBAL INITIALIZATION (Production Ready) =====================
16
+
17
+ # Define the base directory (the 'api' folder)
18
+ BASE_DIR = Path(__file__).resolve().parent
19
+
20
+ # --- File Paths (Constructed using BASE_DIR) ---
21
+ ONNX_MODEL_PATH = BASE_DIR / "ViT_PreProcessing-ops11-preprocessing-int-dynam_graph.onnx"
22
+ METADATA_PATH = BASE_DIR / "train_metadata.csv"
23
+ VENOM_DATA_PATH = BASE_DIR / "venomstatus_with_antivenom.csv"
24
+ # We use min-train_metadata.csv for country data lookup
25
+ COUNTRY_DATA_PATH = BASE_DIR / "min-train_metadata.csv"
26
+
27
+ try:
28
+ # 1.1 Load ONNX Model
29
+ # Convert Path object to string for onnxruntime
30
+ session = ort.InferenceSession(str(ONNX_MODEL_PATH))
31
+
32
+ # 1.2 Load Metadata and Data
33
+ metadata = pd.read_csv(METADATA_PATH)
34
+ venom_data = pd.read_csv(VENOM_DATA_PATH)
35
+ country_metadata = pd.read_csv(COUNTRY_DATA_PATH)
36
+
37
+ # Extract class names (binomial)
38
+ class_names = metadata['binomial'].unique()
39
+
40
+ except FileNotFoundError as e:
41
+ # Stop the application if essential assets are missing in the production environment
42
+ print(f"FATAL ERROR: Essential data file not found at deployment: {e.filename}")
43
+ # The Uvicorn server (run by FastAPI) will likely catch this and stop.
44
+ raise SystemExit(f"Deployment failed due to missing asset: {e.filename}. Check Dockerfile COPY commands.")
45
+
46
+ # 1.3 Initialize Gemini API Client (Securely using Environment Variable)
47
+ GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
48
+
49
+ if not GEMINI_API_KEY:
50
+ print("WARNING: GEMINI_API_KEY not found. Image generation will fail.")
51
+
52
+ genai_client = genai.Client(api_key=GEMINI_API_KEY)
53
+
54
+
55
+ # ===================== 2. IMAGE PREPROCESSING =====================
56
+
57
+ def preprocess_image(image: Image.Image) -> np.ndarray:
58
+ """
59
+ Applies the necessary transformations to a PIL Image
60
+ to prepare it for the ONNX model input.
61
+ """
62
+ transform = transforms.Compose([
63
+ transforms.Resize((224, 224)),
64
+ transforms.ToTensor(),
65
+ transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
66
+ ])
67
+
68
+ image = transform(image)
69
+
70
+ # Add a batch dimension (1, C, H, W) and convert to float32 NumPy array
71
+ input_tensor = np.expand_dims(image.numpy(), axis=0).astype(np.float32)
72
+ return input_tensor
73
+
74
+
75
+ # ===================== 3. PREDICTION FUNCTION =====================
76
+
77
+ def predict_snake(image: Image.Image) -> dict:
78
+ """
79
+ Runs the prediction pipeline and looks up all associated metadata
80
+ (venom status, antidote, country).
81
+ """
82
+ if not session:
83
+ return {"error": "Model not loaded.", "species_name": "Unknown", "venom_status": -1, "antivenom_name": "N/A", "manufacturer": "N/A", "confidence": 0.0, "countries": "N/A"}
84
+
85
+ # --- Inference Logic ---
86
+ input_tensor = preprocess_image(image)
87
+ input_name = session.get_inputs()[0].name
88
+ output_name = session.get_outputs()[0].name
89
+
90
+ # Run ONNX prediction
91
+ logits = session.run([output_name], {input_name: input_tensor})[0][0]
92
+
93
+ # Post-processing (Softmax and Argmax)
94
+ probabilities = softmax(logits)
95
+ predicted_class_id = np.argmax(probabilities)
96
+ species_name = class_names[predicted_class_id]
97
+ confidence = float(np.max(probabilities))
98
+
99
+ # --- Metadata Lookup ---
100
+ # 3.4 Venom/Antivenom Lookup
101
+ species_row = venom_data[venom_data['species'] == species_name].iloc[0]
102
+
103
+ # 3.4 Country Lookup (using min-train_metadata.csv)
104
+ # Filter the country metadata for the predicted species name
105
+ country_list = country_metadata[country_metadata['binomial'] == species_name]['country'].unique()
106
+
107
+ # Clean the list and convert to a comma-separated string
108
+ countries = [c for c in country_list if c.lower() not in ('unknown', 'unidentified', 'n/a')]
109
+ country_output = ", ".join(countries) if countries else "Distribution data unavailable"
110
+
111
+ # 3.5 Format Result
112
+ result = {
113
+ "species_name": species_name,
114
+ "venom_status": int(species_row['venom_status']),
115
+ "antivenom_name": species_row.get('antivenom Name', 'N/A'),
116
+ "manufacturer": species_row.get('manufacturer', 'N/A'),
117
+ "confidence": round(confidence, 4),
118
+ "countries": country_output
119
+ }
120
+ return result
121
+
122
+
123
+ # ===================== 4. IMAGE GENERATION FUNCTION =====================
124
+
125
+ def generate_image_from_text(prompt: str) -> tuple[bytes, Image.Image]:
126
+ """
127
+ Uses the Gemini API (Imagen 3.0) to generate an image from a text description.
128
+
129
+ Returns:
130
+ A tuple: (raw JPEG bytes of the generated image, PIL Image object)
131
+ """
132
+
133
+ if not GEMINI_API_KEY:
134
+ # Raise a specific error if the endpoint relies on the key
135
+ raise ConnectionError("Gemini API key not configured. Cannot generate image.")
136
+
137
+ # Add context to the prompt
138
+ full_prompt = f"Highly detailed, scientifically accurate photo of a snake matching this description: {prompt}"
139
+
140
+ # Call the image generation model
141
+ result = genai_client.models.generate_images(
142
+ model='imagen-3.0-generate-002',
143
+ prompt=full_prompt,
144
+ config=dict(
145
+ number_of_images=1,
146
+ output_mime_type="image/jpeg",
147
+ aspect_ratio="1:1"
148
+ )
149
+ )
150
+
151
+ if not result.generated_images:
152
+ raise RuntimeError("Gemini API returned no image.")
153
+
154
+ # Decode bytes
155
+ image_bytes = result.generated_images[0].image.image_bytes
156
+
157
+ # Create PIL Image object for the predict_snake function
158
+ gen_image_pil = Image.open(io.BytesIO(image_bytes))
159
+
160
+ return image_bytes, gen_image_pil
api/species_to_country_mapping.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:af8d2f7a4f73c943293a831332e96f3880a37d8cf22c73fb34a1fd0438dd8baf
3
+ size 1556235
download_files.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gdown # pip install gdown
3
+
4
+ # Ensure the "api" directory exists
5
+ os.makedirs("api", exist_ok=True)
6
+
7
+ # ✅ Replace these with your actual Google Drive FILE IDs
8
+ MODEL_ID = "1HFCe30fz0AGfUrvXVkyblEnJuN5nzzLH"
9
+ CSV_ID = "18Z7GlbtA-PULXYa6t9KVvhYr6Hv-T5uj"
10
+ XLSX_ID = "1aj0so1m7LV7b7Aqr1W7Q_JrmsAPSyLr1"
11
+ Train_ID = "1HnX_p18IrNZtwL0hcKz_MIOJM4KbzzP3"
12
+ # Convert them into downloadable URLs
13
+ MODEL_URL = f"https://drive.google.com/uc?id={MODEL_ID}"
14
+ CSV_URL = f"https://drive.google.com/uc?id={CSV_ID}"
15
+ XLSX_URL = f"https://drive.google.com/uc?id={XLSX_ID}"
16
+ Train_URL = f"https://drive.google.com/uc?id={Train_ID}"
17
+
18
+ # Local file paths
19
+ MODEL_PATH = "api/ViT_PreProcessing-ops11-preprocessing-int-dynam_graph.onnx"
20
+ CSV_PATH = "api/venomstatus_with_antivenom.csv"
21
+ XLSX_PATH = "api/venomstatus_with_antivenom.xlsx"
22
+ Train_Path="api/train_metadata.csv"
23
+ def download_file(url, path):
24
+ """Downloads a file from Google Drive if it doesn't already exist."""
25
+ if not os.path.exists(path):
26
+ print(f"⬇️ Downloading {os.path.basename(path)}...")
27
+ gdown.download(url, path, quiet=False)
28
+ print(f"✅ Saved to {path}")
29
+ else:
30
+ print(f"✅ {os.path.basename(path)} already exists.")
31
+
32
+ # Run downloads
33
+ download_file(MODEL_URL, MODEL_PATH)
34
+ download_file(CSV_URL, CSV_PATH)
35
+ download_file(XLSX_URL, XLSX_PATH)
36
+ download_file(Train_URL,Train_Path)
notebooks/BaseLine-EfficientNet-B0-224.ipynb ADDED
@@ -0,0 +1,1149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "metadata": {},
7
+ "outputs": [
8
+ {
9
+ "data": {
10
+ "text/plain": [
11
+ "device(type='cuda')"
12
+ ]
13
+ },
14
+ "execution_count": 1,
15
+ "metadata": {},
16
+ "output_type": "execute_result"
17
+ }
18
+ ],
19
+ "source": [
20
+ "import os\n",
21
+ "import cv2\n",
22
+ "import time\n",
23
+ "import timm\n",
24
+ "import torch\n",
25
+ "import sklearn.metrics\n",
26
+ "\n",
27
+ "from PIL import Image\n",
28
+ "\n",
29
+ "import numpy as np\n",
30
+ "import pandas as pd\n",
31
+ "import torch.nn as nn\n",
32
+ "\n",
33
+ "from torch.optim import SGD, lr_scheduler\n",
34
+ "from torch.utils.data import DataLoader, Dataset\n",
35
+ "\n",
36
+ "os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"1\"\n",
37
+ "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
38
+ "device"
39
+ ]
40
+ },
41
+ {
42
+ "cell_type": "code",
43
+ "execution_count": 2,
44
+ "metadata": {},
45
+ "outputs": [
46
+ {
47
+ "name": "stdout",
48
+ "output_type": "stream",
49
+ "text": [
50
+ "386006 70208\n"
51
+ ]
52
+ }
53
+ ],
54
+ "source": [
55
+ "metadata = pd.read_csv(\"SnakeCLEF2021_train_metadata_PROD.csv\")\n",
56
+ "min_train_metadata = pd.read_csv(\"SnakeCLEF2021_min-train_metadata_PROD.csv\")\n",
57
+ "\n",
58
+ "print(len(metadata), len(min_train_metadata))"
59
+ ]
60
+ },
61
+ {
62
+ "cell_type": "code",
63
+ "execution_count": 3,
64
+ "metadata": {},
65
+ "outputs": [
66
+ {
67
+ "data": {
68
+ "text/html": [
69
+ "<div>\n",
70
+ "<style scoped>\n",
71
+ " .dataframe tbody tr th:only-of-type {\n",
72
+ " vertical-align: middle;\n",
73
+ " }\n",
74
+ "\n",
75
+ " .dataframe tbody tr th {\n",
76
+ " vertical-align: top;\n",
77
+ " }\n",
78
+ "\n",
79
+ " .dataframe thead th {\n",
80
+ " text-align: right;\n",
81
+ " }\n",
82
+ "</style>\n",
83
+ "<table border=\"1\" class=\"dataframe\">\n",
84
+ " <thead>\n",
85
+ " <tr style=\"text-align: right;\">\n",
86
+ " <th></th>\n",
87
+ " <th>binomial</th>\n",
88
+ " <th>country</th>\n",
89
+ " <th>continent</th>\n",
90
+ " <th>genus</th>\n",
91
+ " <th>family</th>\n",
92
+ " <th>UUID</th>\n",
93
+ " <th>source</th>\n",
94
+ " <th>subset</th>\n",
95
+ " <th>class_id</th>\n",
96
+ " <th>image_path</th>\n",
97
+ " </tr>\n",
98
+ " </thead>\n",
99
+ " <tbody>\n",
100
+ " <tr>\n",
101
+ " <th>0</th>\n",
102
+ " <td>Pantherophis spiloides</td>\n",
103
+ " <td>United States of America</td>\n",
104
+ " <td>North America</td>\n",
105
+ " <td>Pantherophis</td>\n",
106
+ " <td>Colubridae</td>\n",
107
+ " <td>fbc816e9552643a2bce4f655b2f3c4e1</td>\n",
108
+ " <td>inaturalist</td>\n",
109
+ " <td>train</td>\n",
110
+ " <td>523</td>\n",
111
+ " <td>/Datasets/SnakeCLEF-2021/inaturalist/fbc816e95...</td>\n",
112
+ " </tr>\n",
113
+ " <tr>\n",
114
+ " <th>1</th>\n",
115
+ " <td>Masticophis taeniatus</td>\n",
116
+ " <td>United States of America</td>\n",
117
+ " <td>North America</td>\n",
118
+ " <td>Masticophis</td>\n",
119
+ " <td>Colubridae</td>\n",
120
+ " <td>cbc7ad7141a642f2b92ef7fe05c9d608</td>\n",
121
+ " <td>inaturalist</td>\n",
122
+ " <td>train</td>\n",
123
+ " <td>430</td>\n",
124
+ " <td>/Datasets/SnakeCLEF-2021/inaturalist/cbc7ad714...</td>\n",
125
+ " </tr>\n",
126
+ " <tr>\n",
127
+ " <th>2</th>\n",
128
+ " <td>Crotalus pyrrhus</td>\n",
129
+ " <td>United States of America</td>\n",
130
+ " <td>North America</td>\n",
131
+ " <td>Crotalus</td>\n",
132
+ " <td>Viperidae</td>\n",
133
+ " <td>fc4db72953ae4c978ac50acb33adce0c</td>\n",
134
+ " <td>inaturalist</td>\n",
135
+ " <td>train</td>\n",
136
+ " <td>183</td>\n",
137
+ " <td>/Datasets/SnakeCLEF-2021/inaturalist/fc4db7295...</td>\n",
138
+ " </tr>\n",
139
+ " <tr>\n",
140
+ " <th>3</th>\n",
141
+ " <td>Haldea striatula</td>\n",
142
+ " <td>United States of America</td>\n",
143
+ " <td>North America</td>\n",
144
+ " <td>Haldea</td>\n",
145
+ " <td>Colubridae</td>\n",
146
+ " <td>2068c79c956d43dc8a45106e0c808aed</td>\n",
147
+ " <td>inaturalist</td>\n",
148
+ " <td>train</td>\n",
149
+ " <td>305</td>\n",
150
+ " <td>/Datasets/SnakeCLEF-2021/inaturalist/2068c79c9...</td>\n",
151
+ " </tr>\n",
152
+ " <tr>\n",
153
+ " <th>4</th>\n",
154
+ " <td>Natrix natrix</td>\n",
155
+ " <td>Russia</td>\n",
156
+ " <td>Europe</td>\n",
157
+ " <td>Natrix</td>\n",
158
+ " <td>Colubridae</td>\n",
159
+ " <td>3e376aaf4f8d42e991c0c8ddc5972f95</td>\n",
160
+ " <td>inaturalist</td>\n",
161
+ " <td>train</td>\n",
162
+ " <td>471</td>\n",
163
+ " <td>/Datasets/SnakeCLEF-2021/inaturalist/3e376aaf4...</td>\n",
164
+ " </tr>\n",
165
+ " </tbody>\n",
166
+ "</table>\n",
167
+ "</div>"
168
+ ],
169
+ "text/plain": [
170
+ " binomial country continent \\\n",
171
+ "0 Pantherophis spiloides United States of America North America \n",
172
+ "1 Masticophis taeniatus United States of America North America \n",
173
+ "2 Crotalus pyrrhus United States of America North America \n",
174
+ "3 Haldea striatula United States of America North America \n",
175
+ "4 Natrix natrix Russia Europe \n",
176
+ "\n",
177
+ " genus family UUID source \\\n",
178
+ "0 Pantherophis Colubridae fbc816e9552643a2bce4f655b2f3c4e1 inaturalist \n",
179
+ "1 Masticophis Colubridae cbc7ad7141a642f2b92ef7fe05c9d608 inaturalist \n",
180
+ "2 Crotalus Viperidae fc4db72953ae4c978ac50acb33adce0c inaturalist \n",
181
+ "3 Haldea Colubridae 2068c79c956d43dc8a45106e0c808aed inaturalist \n",
182
+ "4 Natrix Colubridae 3e376aaf4f8d42e991c0c8ddc5972f95 inaturalist \n",
183
+ "\n",
184
+ " subset class_id image_path \n",
185
+ "0 train 523 /Datasets/SnakeCLEF-2021/inaturalist/fbc816e95... \n",
186
+ "1 train 430 /Datasets/SnakeCLEF-2021/inaturalist/cbc7ad714... \n",
187
+ "2 train 183 /Datasets/SnakeCLEF-2021/inaturalist/fc4db7295... \n",
188
+ "3 train 305 /Datasets/SnakeCLEF-2021/inaturalist/2068c79c9... \n",
189
+ "4 train 471 /Datasets/SnakeCLEF-2021/inaturalist/3e376aaf4... "
190
+ ]
191
+ },
192
+ "execution_count": 3,
193
+ "metadata": {},
194
+ "output_type": "execute_result"
195
+ }
196
+ ],
197
+ "source": [
198
+ "metadata.head(5)"
199
+ ]
200
+ },
201
+ {
202
+ "cell_type": "code",
203
+ "execution_count": 4,
204
+ "metadata": {},
205
+ "outputs": [
206
+ {
207
+ "name": "stdout",
208
+ "output_type": "stream",
209
+ "text": [
210
+ "70208 38601\n"
211
+ ]
212
+ },
213
+ {
214
+ "data": {
215
+ "text/plain": [
216
+ "768"
217
+ ]
218
+ },
219
+ "execution_count": 4,
220
+ "metadata": {},
221
+ "output_type": "execute_result"
222
+ }
223
+ ],
224
+ "source": [
225
+ "train_metadata = min_train_metadata\n",
226
+ "val_metadata = metadata[metadata['subset'] == 'val']\n",
227
+ "\n",
228
+ "print(len(train_metadata), len(val_metadata))\n",
229
+ "len(min_train_metadata.binomial.unique())"
230
+ ]
231
+ },
232
+ {
233
+ "cell_type": "code",
234
+ "execution_count": 5,
235
+ "metadata": {},
236
+ "outputs": [],
237
+ "source": [
238
+ "N_CLASSES = 772\n",
239
+ "\n",
240
+ "class TrainDataset(Dataset):\n",
241
+ " def __init__(self, df, transform=None):\n",
242
+ " self.df = df\n",
243
+ " self.transform = transform\n",
244
+ " \n",
245
+ " def __len__(self):\n",
246
+ " return len(self.df)\n",
247
+ "\n",
248
+ " def __getitem__(self, idx):\n",
249
+ " file_path = self.df['image_path'].values[idx]\n",
250
+ " label = self.df['class_id'].values[idx]\n",
251
+ " image = cv2.imread(file_path)\n",
252
+ " image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n",
253
+ "\n",
254
+ " if self.transform:\n",
255
+ " augmented = self.transform(image=image)\n",
256
+ " image = augmented['image']\n",
257
+ " \n",
258
+ " return image, label"
259
+ ]
260
+ },
261
+ {
262
+ "cell_type": "code",
263
+ "execution_count": 6,
264
+ "metadata": {},
265
+ "outputs": [
266
+ {
267
+ "name": "stdout",
268
+ "output_type": "stream",
269
+ "text": [
270
+ "Loaded pretrained weights for efficientnet-b0\n"
271
+ ]
272
+ }
273
+ ],
274
+ "source": [
275
+ "from efficientnet_pytorch import EfficientNet\n",
276
+ "model = EfficientNet.from_pretrained('efficientnet-b0')\n",
277
+ "\n",
278
+ "model._fc = nn.Linear(model._fc.in_features, N_CLASSES)"
279
+ ]
280
+ },
281
+ {
282
+ "cell_type": "code",
283
+ "execution_count": 7,
284
+ "metadata": {},
285
+ "outputs": [],
286
+ "source": [
287
+ "HEIGHT = 224\n",
288
+ "WIDTH = 224\n",
289
+ "\n",
290
+ "from albumentations import Compose, Normalize, Resize, HorizontalFlip, VerticalFlip\n",
291
+ "from albumentations.pytorch import ToTensorV2\n",
292
+ "from albumentations import RandomCrop, HorizontalFlip, VerticalFlip, RandomBrightnessContrast, CenterCrop, PadIfNeeded, RandomResizedCrop\n",
293
+ "\n",
294
+ "def get_transforms(*, data):\n",
295
+ " assert data in ('train', 'valid')\n",
296
+ "\n",
297
+ " if data == 'train':\n",
298
+ " return Compose([\n",
299
+ " RandomResizedCrop(WIDTH, HEIGHT, scale=(0.8, 1.0)),\n",
300
+ " HorizontalFlip(p=0.5),\n",
301
+ " VerticalFlip(p=0.5),\n",
302
+ " RandomBrightnessContrast(p=0.2),\n",
303
+ " Normalize(\n",
304
+ " mean=[0.485, 0.456, 0.406],\n",
305
+ " std=[0.229, 0.224, 0.225],\n",
306
+ " ),\n",
307
+ " ToTensorV2(),\n",
308
+ " ])\n",
309
+ "\n",
310
+ " elif data == 'valid':\n",
311
+ " return Compose([\n",
312
+ " Resize(WIDTH, HEIGHT),\n",
313
+ " Normalize(\n",
314
+ " mean=[0.485, 0.456, 0.406],\n",
315
+ " std=[0.229, 0.224, 0.225],\n",
316
+ " ),\n",
317
+ " ToTensorV2(),\n",
318
+ " ])"
319
+ ]
320
+ },
321
+ {
322
+ "cell_type": "code",
323
+ "execution_count": 8,
324
+ "metadata": {},
325
+ "outputs": [],
326
+ "source": [
327
+ "train_dataset = TrainDataset(train_metadata, transform=get_transforms(data='train'))\n",
328
+ "valid_dataset = TrainDataset(val_metadata, transform=get_transforms(data='valid'))"
329
+ ]
330
+ },
331
+ {
332
+ "cell_type": "code",
333
+ "execution_count": 9,
334
+ "metadata": {},
335
+ "outputs": [],
336
+ "source": [
337
+ "BATCH_SIZE = 64\n",
338
+ "EPOCHS = 50\n",
339
+ "WORKERS = 8\n",
340
+ "\n",
341
+ "train_loader = DataLoader(train_dataset, batch_size=BATCH_SIZE, shuffle=True, num_workers=WORKERS)\n",
342
+ "valid_loader = DataLoader(valid_dataset, batch_size=BATCH_SIZE, shuffle=False, num_workers=WORKERS)"
343
+ ]
344
+ },
345
+ {
346
+ "cell_type": "code",
347
+ "execution_count": 10,
348
+ "metadata": {},
349
+ "outputs": [
350
+ {
351
+ "name": "stderr",
352
+ "output_type": "stream",
353
+ "text": [
354
+ "1097it [03:02, 6.00it/s]\n"
355
+ ]
356
+ },
357
+ {
358
+ "name": "stdout",
359
+ "output_type": "stream",
360
+ "text": [
361
+ " Epoch 1 - avg_train_loss: 5.0426 avg_val_loss: 3.7397 F1: 0.065554 Accuracy: 0.217274 time: 255s\n"
362
+ ]
363
+ },
364
+ {
365
+ "name": "stderr",
366
+ "output_type": "stream",
367
+ "text": [
368
+ "1097it [03:21, 5.45it/s]\n"
369
+ ]
370
+ },
371
+ {
372
+ "name": "stdout",
373
+ "output_type": "stream",
374
+ "text": [
375
+ " Epoch 2 - avg_train_loss: 3.6295 avg_val_loss: 3.1958 F1: 0.131081 Accuracy: 0.283361 time: 269s\n"
376
+ ]
377
+ },
378
+ {
379
+ "name": "stderr",
380
+ "output_type": "stream",
381
+ "text": [
382
+ "1097it [03:29, 5.23it/s]\n"
383
+ ]
384
+ },
385
+ {
386
+ "name": "stdout",
387
+ "output_type": "stream",
388
+ "text": [
389
+ " Epoch 3 - avg_train_loss: 3.1122 avg_val_loss: 3.0451 F1: 0.166816 Accuracy: 0.309111 time: 278s\n"
390
+ ]
391
+ },
392
+ {
393
+ "name": "stderr",
394
+ "output_type": "stream",
395
+ "text": [
396
+ "1097it [03:36, 5.07it/s]\n"
397
+ ]
398
+ },
399
+ {
400
+ "name": "stdout",
401
+ "output_type": "stream",
402
+ "text": [
403
+ " Epoch 4 - avg_train_loss: 2.7885 avg_val_loss: 2.8895 F1: 0.198979 Accuracy: 0.338566 time: 291s\n"
404
+ ]
405
+ },
406
+ {
407
+ "name": "stderr",
408
+ "output_type": "stream",
409
+ "text": [
410
+ "550it [01:55, 4.98it/s]"
411
+ ]
412
+ },
413
+ {
414
+ "name": "stdout",
415
+ "output_type": "stream",
416
+ "text": [
417
+ " Epoch 5 - avg_train_loss: 2.5378 avg_val_loss: 2.8681 F1: 0.232379 Accuracy: 0.341546 time: 285s\n"
418
+ ]
419
+ },
420
+ {
421
+ "name": "stderr",
422
+ "output_type": "stream",
423
+ "text": [
424
+ "1097it [03:35, 5.09it/s]\n"
425
+ ]
426
+ },
427
+ {
428
+ "name": "stdout",
429
+ "output_type": "stream",
430
+ "text": [
431
+ " Epoch 6 - avg_train_loss: 2.1108 avg_val_loss: 2.4461 F1: 0.298629 Accuracy: 0.425611 time: 284s\n"
432
+ ]
433
+ },
434
+ {
435
+ "name": "stderr",
436
+ "output_type": "stream",
437
+ "text": [
438
+ "1097it [03:39, 5.01it/s]\n"
439
+ ]
440
+ },
441
+ {
442
+ "name": "stdout",
443
+ "output_type": "stream",
444
+ "text": [
445
+ " Epoch 7 - avg_train_loss: 2.0170 avg_val_loss: 2.4184 F1: 0.302618 Accuracy: 0.431077 time: 287s\n"
446
+ ]
447
+ },
448
+ {
449
+ "name": "stderr",
450
+ "output_type": "stream",
451
+ "text": [
452
+ "1097it [03:41, 4.96it/s]\n"
453
+ ]
454
+ },
455
+ {
456
+ "name": "stdout",
457
+ "output_type": "stream",
458
+ "text": [
459
+ " Epoch 8 - avg_train_loss: 1.9617 avg_val_loss: 2.4027 F1: 0.309487 Accuracy: 0.432087 time: 295s\n"
460
+ ]
461
+ },
462
+ {
463
+ "name": "stderr",
464
+ "output_type": "stream",
465
+ "text": [
466
+ "1097it [03:39, 4.99it/s]\n"
467
+ ]
468
+ },
469
+ {
470
+ "name": "stdout",
471
+ "output_type": "stream",
472
+ "text": [
473
+ " Epoch 9 - avg_train_loss: 1.9289 avg_val_loss: 2.3971 F1: 0.314581 Accuracy: 0.435792 time: 289s\n"
474
+ ]
475
+ },
476
+ {
477
+ "name": "stderr",
478
+ "output_type": "stream",
479
+ "text": [
480
+ "1097it [03:44, 4.88it/s]\n"
481
+ ]
482
+ },
483
+ {
484
+ "name": "stdout",
485
+ "output_type": "stream",
486
+ "text": [
487
+ " Epoch 10 - avg_train_loss: 1.8914 avg_val_loss: 2.3800 F1: 0.321931 Accuracy: 0.441051 time: 293s\n"
488
+ ]
489
+ },
490
+ {
491
+ "name": "stderr",
492
+ "output_type": "stream",
493
+ "text": [
494
+ "1097it [03:44, 4.89it/s]\n"
495
+ ]
496
+ },
497
+ {
498
+ "name": "stdout",
499
+ "output_type": "stream",
500
+ "text": [
501
+ " Epoch 11 - avg_train_loss: 1.8325 avg_val_loss: 2.3572 F1: 0.326008 Accuracy: 0.444237 time: 299s\n"
502
+ ]
503
+ },
504
+ {
505
+ "name": "stderr",
506
+ "output_type": "stream",
507
+ "text": [
508
+ "1097it [03:38, 5.03it/s]\n"
509
+ ]
510
+ },
511
+ {
512
+ "name": "stdout",
513
+ "output_type": "stream",
514
+ "text": [
515
+ " Epoch 12 - avg_train_loss: 1.8279 avg_val_loss: 2.3493 F1: 0.324886 Accuracy: 0.445817 time: 288s\n"
516
+ ]
517
+ },
518
+ {
519
+ "name": "stderr",
520
+ "output_type": "stream",
521
+ "text": [
522
+ "1097it [03:45, 4.87it/s]\n"
523
+ ]
524
+ },
525
+ {
526
+ "name": "stdout",
527
+ "output_type": "stream",
528
+ "text": [
529
+ " Epoch 13 - avg_train_loss: 1.8217 avg_val_loss: 2.3567 F1: 0.326244 Accuracy: 0.444678 time: 294s\n"
530
+ ]
531
+ },
532
+ {
533
+ "name": "stderr",
534
+ "output_type": "stream",
535
+ "text": [
536
+ "1097it [03:41, 4.94it/s]\n"
537
+ ]
538
+ },
539
+ {
540
+ "name": "stdout",
541
+ "output_type": "stream",
542
+ "text": [
543
+ " Epoch 14 - avg_train_loss: 1.8170 avg_val_loss: 2.3503 F1: 0.326443 Accuracy: 0.445921 time: 291s\n"
544
+ ]
545
+ },
546
+ {
547
+ "name": "stderr",
548
+ "output_type": "stream",
549
+ "text": [
550
+ "1097it [03:40, 4.99it/s]\n"
551
+ ]
552
+ },
553
+ {
554
+ "name": "stdout",
555
+ "output_type": "stream",
556
+ "text": [
557
+ " Epoch 15 - avg_train_loss: 1.8121 avg_val_loss: 2.3465 F1: 0.327316 Accuracy: 0.447165 time: 295s\n"
558
+ ]
559
+ },
560
+ {
561
+ "name": "stderr",
562
+ "output_type": "stream",
563
+ "text": [
564
+ "1097it [03:42, 4.93it/s]\n"
565
+ ]
566
+ },
567
+ {
568
+ "name": "stdout",
569
+ "output_type": "stream",
570
+ "text": [
571
+ " Epoch 16 - avg_train_loss: 1.8058 avg_val_loss: 2.3502 F1: 0.325449 Accuracy: 0.446724 time: 291s\n"
572
+ ]
573
+ },
574
+ {
575
+ "name": "stderr",
576
+ "output_type": "stream",
577
+ "text": [
578
+ "1097it [03:43, 4.91it/s]\n"
579
+ ]
580
+ },
581
+ {
582
+ "name": "stdout",
583
+ "output_type": "stream",
584
+ "text": [
585
+ " Epoch 17 - avg_train_loss: 1.8077 avg_val_loss: 2.3510 F1: 0.327032 Accuracy: 0.446465 time: 292s\n"
586
+ ]
587
+ },
588
+ {
589
+ "name": "stderr",
590
+ "output_type": "stream",
591
+ "text": [
592
+ "1097it [03:41, 4.96it/s]\n"
593
+ ]
594
+ },
595
+ {
596
+ "name": "stdout",
597
+ "output_type": "stream",
598
+ "text": [
599
+ " Epoch 18 - avg_train_loss: 1.8109 avg_val_loss: 2.3489 F1: 0.326987 Accuracy: 0.446595 time: 290s\n"
600
+ ]
601
+ },
602
+ {
603
+ "name": "stderr",
604
+ "output_type": "stream",
605
+ "text": [
606
+ "1097it [03:44, 4.89it/s]\n"
607
+ ]
608
+ },
609
+ {
610
+ "name": "stdout",
611
+ "output_type": "stream",
612
+ "text": [
613
+ " Epoch 19 - avg_train_loss: 1.8035 avg_val_loss: 2.3484 F1: 0.327835 Accuracy: 0.447009 time: 299s\n"
614
+ ]
615
+ },
616
+ {
617
+ "name": "stderr",
618
+ "output_type": "stream",
619
+ "text": [
620
+ "1097it [03:42, 4.94it/s]\n"
621
+ ]
622
+ },
623
+ {
624
+ "name": "stdout",
625
+ "output_type": "stream",
626
+ "text": [
627
+ " Epoch 20 - avg_train_loss: 1.8024 avg_val_loss: 2.3443 F1: 0.328095 Accuracy: 0.447553 time: 291s\n"
628
+ ]
629
+ },
630
+ {
631
+ "name": "stderr",
632
+ "output_type": "stream",
633
+ "text": [
634
+ "1097it [03:42, 4.94it/s]\n"
635
+ ]
636
+ },
637
+ {
638
+ "name": "stdout",
639
+ "output_type": "stream",
640
+ "text": [
641
+ " Epoch 21 - avg_train_loss: 1.8020 avg_val_loss: 2.3456 F1: 0.328408 Accuracy: 0.447812 time: 290s\n"
642
+ ]
643
+ },
644
+ {
645
+ "name": "stderr",
646
+ "output_type": "stream",
647
+ "text": [
648
+ "1097it [03:44, 4.89it/s]\n"
649
+ ]
650
+ },
651
+ {
652
+ "name": "stdout",
653
+ "output_type": "stream",
654
+ "text": [
655
+ " Epoch 22 - avg_train_loss: 1.8093 avg_val_loss: 2.3476 F1: 0.328879 Accuracy: 0.447450 time: 296s\n"
656
+ ]
657
+ },
658
+ {
659
+ "name": "stderr",
660
+ "output_type": "stream",
661
+ "text": [
662
+ "1097it [03:36, 5.06it/s]\n"
663
+ ]
664
+ },
665
+ {
666
+ "name": "stdout",
667
+ "output_type": "stream",
668
+ "text": [
669
+ " Epoch 23 - avg_train_loss: 1.8013 avg_val_loss: 2.3482 F1: 0.326461 Accuracy: 0.446517 time: 286s\n"
670
+ ]
671
+ },
672
+ {
673
+ "name": "stderr",
674
+ "output_type": "stream",
675
+ "text": [
676
+ "1097it [03:40, 4.98it/s]\n"
677
+ ]
678
+ },
679
+ {
680
+ "name": "stdout",
681
+ "output_type": "stream",
682
+ "text": [
683
+ " Epoch 24 - avg_train_loss: 1.8021 avg_val_loss: 2.3468 F1: 0.327844 Accuracy: 0.447683 time: 289s\n"
684
+ ]
685
+ },
686
+ {
687
+ "name": "stderr",
688
+ "output_type": "stream",
689
+ "text": [
690
+ "1097it [03:39, 4.99it/s]\n"
691
+ ]
692
+ },
693
+ {
694
+ "name": "stdout",
695
+ "output_type": "stream",
696
+ "text": [
697
+ " Epoch 25 - avg_train_loss: 1.8026 avg_val_loss: 2.3484 F1: 0.327776 Accuracy: 0.446983 time: 289s\n"
698
+ ]
699
+ },
700
+ {
701
+ "name": "stderr",
702
+ "output_type": "stream",
703
+ "text": [
704
+ "1097it [03:39, 4.99it/s]\n"
705
+ ]
706
+ },
707
+ {
708
+ "name": "stdout",
709
+ "output_type": "stream",
710
+ "text": [
711
+ " Epoch 26 - avg_train_loss: 1.8059 avg_val_loss: 2.3476 F1: 0.327871 Accuracy: 0.447035 time: 295s\n"
712
+ ]
713
+ },
714
+ {
715
+ "name": "stderr",
716
+ "output_type": "stream",
717
+ "text": [
718
+ "1097it [03:36, 5.07it/s]\n"
719
+ ]
720
+ },
721
+ {
722
+ "name": "stdout",
723
+ "output_type": "stream",
724
+ "text": [
725
+ " Epoch 27 - avg_train_loss: 1.8098 avg_val_loss: 2.3472 F1: 0.328543 Accuracy: 0.447709 time: 285s\n"
726
+ ]
727
+ },
728
+ {
729
+ "name": "stderr",
730
+ "output_type": "stream",
731
+ "text": [
732
+ "1097it [03:41, 4.95it/s]\n"
733
+ ]
734
+ },
735
+ {
736
+ "name": "stdout",
737
+ "output_type": "stream",
738
+ "text": [
739
+ " Epoch 28 - avg_train_loss: 1.8032 avg_val_loss: 2.3512 F1: 0.327352 Accuracy: 0.445792 time: 290s\n"
740
+ ]
741
+ },
742
+ {
743
+ "name": "stderr",
744
+ "output_type": "stream",
745
+ "text": [
746
+ "1097it [03:41, 4.95it/s]\n"
747
+ ]
748
+ },
749
+ {
750
+ "name": "stdout",
751
+ "output_type": "stream",
752
+ "text": [
753
+ " Epoch 29 - avg_train_loss: 1.8064 avg_val_loss: 2.3470 F1: 0.327592 Accuracy: 0.447035 time: 290s\n"
754
+ ]
755
+ },
756
+ {
757
+ "name": "stderr",
758
+ "output_type": "stream",
759
+ "text": [
760
+ "1097it [03:38, 5.02it/s]\n"
761
+ ]
762
+ },
763
+ {
764
+ "name": "stdout",
765
+ "output_type": "stream",
766
+ "text": [
767
+ " Epoch 30 - avg_train_loss: 1.8023 avg_val_loss: 2.3472 F1: 0.326482 Accuracy: 0.447242 time: 293s\n"
768
+ ]
769
+ },
770
+ {
771
+ "name": "stderr",
772
+ "output_type": "stream",
773
+ "text": [
774
+ "1097it [03:37, 5.05it/s]\n"
775
+ ]
776
+ },
777
+ {
778
+ "name": "stdout",
779
+ "output_type": "stream",
780
+ "text": [
781
+ " Epoch 31 - avg_train_loss: 1.8019 avg_val_loss: 2.3471 F1: 0.327138 Accuracy: 0.447268 time: 285s\n"
782
+ ]
783
+ },
784
+ {
785
+ "name": "stderr",
786
+ "output_type": "stream",
787
+ "text": [
788
+ "1097it [03:36, 5.07it/s]\n"
789
+ ]
790
+ },
791
+ {
792
+ "name": "stdout",
793
+ "output_type": "stream",
794
+ "text": [
795
+ " Epoch 32 - avg_train_loss: 1.8041 avg_val_loss: 2.3468 F1: 0.328199 Accuracy: 0.447501 time: 285s\n"
796
+ ]
797
+ },
798
+ {
799
+ "name": "stderr",
800
+ "output_type": "stream",
801
+ "text": [
802
+ "1097it [03:37, 5.05it/s]\n"
803
+ ]
804
+ },
805
+ {
806
+ "name": "stdout",
807
+ "output_type": "stream",
808
+ "text": [
809
+ " Epoch 33 - avg_train_loss: 1.8066 avg_val_loss: 2.3493 F1: 0.327517 Accuracy: 0.446595 time: 286s\n"
810
+ ]
811
+ },
812
+ {
813
+ "name": "stderr",
814
+ "output_type": "stream",
815
+ "text": [
816
+ "1097it [03:36, 5.07it/s]\n"
817
+ ]
818
+ },
819
+ {
820
+ "name": "stdout",
821
+ "output_type": "stream",
822
+ "text": [
823
+ " Epoch 34 - avg_train_loss: 1.8048 avg_val_loss: 2.3482 F1: 0.328058 Accuracy: 0.446854 time: 288s\n"
824
+ ]
825
+ },
826
+ {
827
+ "name": "stderr",
828
+ "output_type": "stream",
829
+ "text": [
830
+ "1097it [03:37, 5.05it/s]\n"
831
+ ]
832
+ },
833
+ {
834
+ "name": "stdout",
835
+ "output_type": "stream",
836
+ "text": [
837
+ " Epoch 35 - avg_train_loss: 1.8060 avg_val_loss: 2.3486 F1: 0.326996 Accuracy: 0.447294 time: 286s\n"
838
+ ]
839
+ },
840
+ {
841
+ "name": "stderr",
842
+ "output_type": "stream",
843
+ "text": [
844
+ "1097it [03:34, 5.10it/s]\n"
845
+ ]
846
+ },
847
+ {
848
+ "name": "stdout",
849
+ "output_type": "stream",
850
+ "text": [
851
+ " Epoch 36 - avg_train_loss: 1.8068 avg_val_loss: 2.3474 F1: 0.327745 Accuracy: 0.446880 time: 284s\n"
852
+ ]
853
+ },
854
+ {
855
+ "name": "stderr",
856
+ "output_type": "stream",
857
+ "text": [
858
+ "1097it [03:33, 5.14it/s]\n"
859
+ ]
860
+ },
861
+ {
862
+ "name": "stdout",
863
+ "output_type": "stream",
864
+ "text": [
865
+ " Epoch 37 - avg_train_loss: 1.8012 avg_val_loss: 2.3473 F1: 0.328329 Accuracy: 0.447165 time: 287s\n"
866
+ ]
867
+ },
868
+ {
869
+ "name": "stderr",
870
+ "output_type": "stream",
871
+ "text": [
872
+ "1097it [03:29, 5.23it/s]\n"
873
+ ]
874
+ },
875
+ {
876
+ "name": "stdout",
877
+ "output_type": "stream",
878
+ "text": [
879
+ " Epoch 38 - avg_train_loss: 1.8051 avg_val_loss: 2.3523 F1: 0.327051 Accuracy: 0.445999 time: 279s\n"
880
+ ]
881
+ },
882
+ {
883
+ "name": "stderr",
884
+ "output_type": "stream",
885
+ "text": [
886
+ "1097it [03:38, 5.03it/s]\n"
887
+ ]
888
+ },
889
+ {
890
+ "name": "stdout",
891
+ "output_type": "stream",
892
+ "text": [
893
+ " Epoch 39 - avg_train_loss: 1.8071 avg_val_loss: 2.3478 F1: 0.327381 Accuracy: 0.446569 time: 287s\n"
894
+ ]
895
+ },
896
+ {
897
+ "name": "stderr",
898
+ "output_type": "stream",
899
+ "text": [
900
+ "1097it [03:38, 5.02it/s]\n"
901
+ ]
902
+ },
903
+ {
904
+ "name": "stdout",
905
+ "output_type": "stream",
906
+ "text": [
907
+ " Epoch 40 - avg_train_loss: 1.8015 avg_val_loss: 2.3475 F1: 0.328095 Accuracy: 0.447501 time: 287s\n"
908
+ ]
909
+ },
910
+ {
911
+ "name": "stderr",
912
+ "output_type": "stream",
913
+ "text": [
914
+ "1097it [03:37, 5.04it/s]\n"
915
+ ]
916
+ },
917
+ {
918
+ "name": "stdout",
919
+ "output_type": "stream",
920
+ "text": [
921
+ " Epoch 41 - avg_train_loss: 1.8068 avg_val_loss: 2.3468 F1: 0.328143 Accuracy: 0.447165 time: 293s\n"
922
+ ]
923
+ },
924
+ {
925
+ "name": "stderr",
926
+ "output_type": "stream",
927
+ "text": [
928
+ "1097it [03:36, 5.06it/s]\n"
929
+ ]
930
+ },
931
+ {
932
+ "name": "stdout",
933
+ "output_type": "stream",
934
+ "text": [
935
+ " Epoch 42 - avg_train_loss: 1.8002 avg_val_loss: 2.3453 F1: 0.328042 Accuracy: 0.447709 time: 285s\n"
936
+ ]
937
+ },
938
+ {
939
+ "name": "stderr",
940
+ "output_type": "stream",
941
+ "text": [
942
+ "1097it [03:32, 5.17it/s]\n"
943
+ ]
944
+ },
945
+ {
946
+ "name": "stdout",
947
+ "output_type": "stream",
948
+ "text": [
949
+ " Epoch 43 - avg_train_loss: 1.8055 avg_val_loss: 2.3464 F1: 0.327669 Accuracy: 0.446906 time: 281s\n"
950
+ ]
951
+ },
952
+ {
953
+ "name": "stderr",
954
+ "output_type": "stream",
955
+ "text": [
956
+ "1097it [03:32, 5.15it/s]\n"
957
+ ]
958
+ },
959
+ {
960
+ "name": "stdout",
961
+ "output_type": "stream",
962
+ "text": [
963
+ " Epoch 44 - avg_train_loss: 1.8077 avg_val_loss: 2.3452 F1: 0.328458 Accuracy: 0.447683 time: 281s\n"
964
+ ]
965
+ },
966
+ {
967
+ "name": "stderr",
968
+ "output_type": "stream",
969
+ "text": [
970
+ "1097it [03:37, 5.05it/s]\n"
971
+ ]
972
+ },
973
+ {
974
+ "name": "stdout",
975
+ "output_type": "stream",
976
+ "text": [
977
+ " Epoch 45 - avg_train_loss: 1.8027 avg_val_loss: 2.3459 F1: 0.326877 Accuracy: 0.447113 time: 292s\n"
978
+ ]
979
+ },
980
+ {
981
+ "name": "stderr",
982
+ "output_type": "stream",
983
+ "text": [
984
+ "1097it [03:27, 5.28it/s]\n"
985
+ ]
986
+ },
987
+ {
988
+ "name": "stdout",
989
+ "output_type": "stream",
990
+ "text": [
991
+ " Epoch 46 - avg_train_loss: 1.8028 avg_val_loss: 2.3508 F1: 0.326720 Accuracy: 0.446880 time: 276s\n"
992
+ ]
993
+ },
994
+ {
995
+ "name": "stderr",
996
+ "output_type": "stream",
997
+ "text": [
998
+ "1097it [03:32, 5.15it/s]\n"
999
+ ]
1000
+ },
1001
+ {
1002
+ "name": "stdout",
1003
+ "output_type": "stream",
1004
+ "text": [
1005
+ " Epoch 47 - avg_train_loss: 1.8058 avg_val_loss: 2.3500 F1: 0.326431 Accuracy: 0.447139 time: 281s\n"
1006
+ ]
1007
+ },
1008
+ {
1009
+ "name": "stderr",
1010
+ "output_type": "stream",
1011
+ "text": [
1012
+ "1097it [03:36, 5.06it/s]\n"
1013
+ ]
1014
+ },
1015
+ {
1016
+ "name": "stdout",
1017
+ "output_type": "stream",
1018
+ "text": [
1019
+ " Epoch 48 - avg_train_loss: 1.8010 avg_val_loss: 2.3456 F1: 0.327518 Accuracy: 0.447294 time: 285s\n"
1020
+ ]
1021
+ },
1022
+ {
1023
+ "name": "stderr",
1024
+ "output_type": "stream",
1025
+ "text": [
1026
+ "1097it [03:35, 5.10it/s]\n"
1027
+ ]
1028
+ },
1029
+ {
1030
+ "name": "stdout",
1031
+ "output_type": "stream",
1032
+ "text": [
1033
+ " Epoch 49 - avg_train_loss: 1.8064 avg_val_loss: 2.3496 F1: 0.327641 Accuracy: 0.446310 time: 290s\n"
1034
+ ]
1035
+ },
1036
+ {
1037
+ "name": "stderr",
1038
+ "output_type": "stream",
1039
+ "text": [
1040
+ "1097it [03:36, 5.07it/s]\n"
1041
+ ]
1042
+ },
1043
+ {
1044
+ "name": "stdout",
1045
+ "output_type": "stream",
1046
+ "text": [
1047
+ " Epoch 50 - avg_train_loss: 1.8090 avg_val_loss: 2.3463 F1: 0.327178 Accuracy: 0.446543 time: 284s\n"
1048
+ ]
1049
+ }
1050
+ ],
1051
+ "source": [
1052
+ "from sklearn.metrics import f1_score, accuracy_score\n",
1053
+ "import tqdm\n",
1054
+ "\n",
1055
+ "\n",
1056
+ "n_epochs = EPOCHS\n",
1057
+ "lr = 0.01\n",
1058
+ "\n",
1059
+ "optimizer = SGD(model.parameters(), lr=lr, momentum=0.9)\n",
1060
+ "scheduler = lr_scheduler.StepLR(optimizer, step_size=5)\n",
1061
+ "criterion = nn.CrossEntropyLoss()\n",
1062
+ "\n",
1063
+ "model.to(device)\n",
1064
+ "\n",
1065
+ "for epoch in range(n_epochs):\n",
1066
+ " start_time = time.time()\n",
1067
+ "\n",
1068
+ " model.train()\n",
1069
+ " avg_loss = 0.\n",
1070
+ "\n",
1071
+ " optimizer.zero_grad()\n",
1072
+ "\n",
1073
+ " for i, (images, labels) in tqdm.tqdm(enumerate(train_loader)):\n",
1074
+ "\n",
1075
+ " images = images.to(device)\n",
1076
+ " labels = labels.to(device)\n",
1077
+ "\n",
1078
+ " y_preds = model(images)\n",
1079
+ " loss = criterion(y_preds, labels)\n",
1080
+ " avg_loss += loss.item() / len(train_loader)\n",
1081
+ " \n",
1082
+ " loss.backward()\n",
1083
+ " optimizer.step()\n",
1084
+ " optimizer.zero_grad()\n",
1085
+ "\n",
1086
+ " model.eval()\n",
1087
+ " avg_val_loss = 0.\n",
1088
+ " preds = np.zeros((len(valid_dataset)))\n",
1089
+ "\n",
1090
+ " for i, (images, labels) in enumerate(valid_loader):\n",
1091
+ "\n",
1092
+ " images = images.to(device)\n",
1093
+ " labels = labels.to(device)\n",
1094
+ "\n",
1095
+ " with torch.no_grad():\n",
1096
+ " y_preds = model(images)\n",
1097
+ "\n",
1098
+ " preds[i * BATCH_SIZE: (i+1) * BATCH_SIZE] = y_preds.argmax(1).to('cpu').numpy()\n",
1099
+ " loss = criterion(y_preds, labels)\n",
1100
+ " avg_val_loss += loss.item() / len(valid_loader)\n",
1101
+ " \n",
1102
+ " scheduler.step()\n",
1103
+ "\n",
1104
+ " score = f1_score(val_metadata['class_id'], preds, average='macro')\n",
1105
+ " accuracy = accuracy_score(val_metadata['class_id'], preds)\n",
1106
+ "\n",
1107
+ " elapsed = time.time() - start_time\n",
1108
+ " print(f' Epoch {epoch+1} - avg_train_loss: {avg_loss:.4f} avg_val_loss: {avg_val_loss:.4f} F1: {score:.6f} Accuracy: {accuracy:.6f} time: {elapsed:.0f}s')\n"
1109
+ ]
1110
+ },
1111
+ {
1112
+ "cell_type": "code",
1113
+ "execution_count": 11,
1114
+ "metadata": {},
1115
+ "outputs": [],
1116
+ "source": [
1117
+ "torch.save(model.state_dict(), f'SnakeCLEF2021-EfficientNet-B0_224-50E.pth')"
1118
+ ]
1119
+ },
1120
+ {
1121
+ "cell_type": "code",
1122
+ "execution_count": null,
1123
+ "metadata": {},
1124
+ "outputs": [],
1125
+ "source": []
1126
+ }
1127
+ ],
1128
+ "metadata": {
1129
+ "kernelspec": {
1130
+ "display_name": "Python 3 (ipykernel)",
1131
+ "language": "python",
1132
+ "name": "python3"
1133
+ },
1134
+ "language_info": {
1135
+ "codemirror_mode": {
1136
+ "name": "ipython",
1137
+ "version": 3
1138
+ },
1139
+ "file_extension": ".py",
1140
+ "mimetype": "text/x-python",
1141
+ "name": "python",
1142
+ "nbconvert_exporter": "python",
1143
+ "pygments_lexer": "ipython3",
1144
+ "version": "3.13.5"
1145
+ }
1146
+ },
1147
+ "nbformat": 4,
1148
+ "nbformat_minor": 4
1149
+ }
notebooks/SnakeCLEF2021-TestingWithMetadata.ipynb ADDED
@@ -0,0 +1,1072 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "metadata": {},
7
+ "outputs": [
8
+ {
9
+ "data": {
10
+ "text/plain": [
11
+ "device(type='cpu')"
12
+ ]
13
+ },
14
+ "execution_count": 1,
15
+ "metadata": {},
16
+ "output_type": "execute_result"
17
+ }
18
+ ],
19
+ "source": [
20
+ "import gc\n",
21
+ "import os\n",
22
+ "import cv2\n",
23
+ "import sys\n",
24
+ "import json\n",
25
+ "import time\n",
26
+ "import timm\n",
27
+ "import torch\n",
28
+ "import tqdm\n",
29
+ "import random\n",
30
+ "import sklearn.metrics\n",
31
+ "\n",
32
+ "from PIL import Image\n",
33
+ "from pathlib import Path\n",
34
+ "from functools import partial\n",
35
+ "from contextlib import contextmanager\n",
36
+ "from scipy.special import softmax\n",
37
+ "\n",
38
+ "import numpy as np\n",
39
+ "import pandas as pd\n",
40
+ "import torch.nn as nn\n",
41
+ "\n",
42
+ "from torch.optim import Adam, SGD\n",
43
+ "from torch.optim.lr_scheduler import CosineAnnealingLR\n",
44
+ "from torch.utils.data import DataLoader, Dataset\n",
45
+ "from albumentations import Compose, Normalize, Resize\n",
46
+ "from albumentations.pytorch import ToTensorV2\n",
47
+ "from sklearn.preprocessing import LabelBinarizer\n",
48
+ "\n",
49
+ "os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"1\"\n",
50
+ "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
51
+ "device"
52
+ ]
53
+ },
54
+ {
55
+ "cell_type": "code",
56
+ "execution_count": 2,
57
+ "metadata": {},
58
+ "outputs": [
59
+ {
60
+ "name": "stdout",
61
+ "output_type": "stream",
62
+ "text": [
63
+ "Collecting timm\n",
64
+ " Downloading timm-1.0.20-py3-none-any.whl.metadata (61 kB)\n",
65
+ "Requirement already satisfied: torch in c:\\users\\general\\anaconda3\\lib\\site-packages (from timm) (2.9.0)\n",
66
+ "Requirement already satisfied: torchvision in c:\\users\\general\\anaconda3\\lib\\site-packages (from timm) (0.24.0)\n",
67
+ "Requirement already satisfied: pyyaml in c:\\users\\general\\anaconda3\\lib\\site-packages (from timm) (6.0.2)\n",
68
+ "Collecting huggingface_hub (from timm)\n",
69
+ " Downloading huggingface_hub-0.35.3-py3-none-any.whl.metadata (14 kB)\n",
70
+ "Collecting safetensors (from timm)\n",
71
+ " Downloading safetensors-0.6.2-cp38-abi3-win_amd64.whl.metadata (4.1 kB)\n",
72
+ "Requirement already satisfied: filelock in c:\\users\\general\\anaconda3\\lib\\site-packages (from huggingface_hub->timm) (3.17.0)\n",
73
+ "Requirement already satisfied: fsspec>=2023.5.0 in c:\\users\\general\\anaconda3\\lib\\site-packages (from huggingface_hub->timm) (2025.3.2)\n",
74
+ "Requirement already satisfied: packaging>=20.9 in c:\\users\\general\\anaconda3\\lib\\site-packages (from huggingface_hub->timm) (24.2)\n",
75
+ "Requirement already satisfied: requests in c:\\users\\general\\anaconda3\\lib\\site-packages (from huggingface_hub->timm) (2.32.3)\n",
76
+ "Requirement already satisfied: tqdm>=4.42.1 in c:\\users\\general\\anaconda3\\lib\\site-packages (from huggingface_hub->timm) (4.67.1)\n",
77
+ "Requirement already satisfied: typing-extensions>=3.7.4.3 in c:\\users\\general\\anaconda3\\lib\\site-packages (from huggingface_hub->timm) (4.12.2)\n",
78
+ "Requirement already satisfied: colorama in c:\\users\\general\\anaconda3\\lib\\site-packages (from tqdm>=4.42.1->huggingface_hub->timm) (0.4.6)\n",
79
+ "Requirement already satisfied: charset-normalizer<4,>=2 in c:\\users\\general\\anaconda3\\lib\\site-packages (from requests->huggingface_hub->timm) (3.3.2)\n",
80
+ "Requirement already satisfied: idna<4,>=2.5 in c:\\users\\general\\anaconda3\\lib\\site-packages (from requests->huggingface_hub->timm) (3.7)\n",
81
+ "Requirement already satisfied: urllib3<3,>=1.21.1 in c:\\users\\general\\anaconda3\\lib\\site-packages (from requests->huggingface_hub->timm) (2.3.0)\n",
82
+ "Requirement already satisfied: certifi>=2017.4.17 in c:\\users\\general\\anaconda3\\lib\\site-packages (from requests->huggingface_hub->timm) (2025.4.26)\n",
83
+ "Requirement already satisfied: sympy>=1.13.3 in c:\\users\\general\\anaconda3\\lib\\site-packages (from torch->timm) (1.13.3)\n",
84
+ "Requirement already satisfied: networkx>=2.5.1 in c:\\users\\general\\anaconda3\\lib\\site-packages (from torch->timm) (3.4.2)\n",
85
+ "Requirement already satisfied: jinja2 in c:\\users\\general\\anaconda3\\lib\\site-packages (from torch->timm) (3.1.6)\n",
86
+ "Requirement already satisfied: setuptools in c:\\users\\general\\anaconda3\\lib\\site-packages (from torch->timm) (72.1.0)\n",
87
+ "Requirement already satisfied: mpmath<1.4,>=1.1.0 in c:\\users\\general\\anaconda3\\lib\\site-packages (from sympy>=1.13.3->torch->timm) (1.3.0)\n",
88
+ "Requirement already satisfied: MarkupSafe>=2.0 in c:\\users\\general\\anaconda3\\lib\\site-packages (from jinja2->torch->timm) (3.0.2)\n",
89
+ "Requirement already satisfied: numpy in c:\\users\\general\\anaconda3\\lib\\site-packages (from torchvision->timm) (2.1.3)\n",
90
+ "Requirement already satisfied: pillow!=8.3.*,>=5.3.0 in c:\\users\\general\\anaconda3\\lib\\site-packages (from torchvision->timm) (11.1.0)\n",
91
+ "Downloading timm-1.0.20-py3-none-any.whl (2.5 MB)\n",
92
+ " ---------------------------------------- 0.0/2.5 MB ? eta -:--:--\n",
93
+ " ---------------------------------------- 0.0/2.5 MB ? eta -:--:--\n",
94
+ " ---------------------------------------- 0.0/2.5 MB ? eta -:--:--\n",
95
+ " ---------------------------------------- 0.0/2.5 MB ? eta -:--:--\n",
96
+ " ---- ----------------------------------- 0.3/2.5 MB ? eta -:--:--\n",
97
+ " -------- ------------------------------- 0.5/2.5 MB 980.0 kB/s eta 0:00:03\n",
98
+ " -------- ------------------------------- 0.5/2.5 MB 980.0 kB/s eta 0:00:03\n",
99
+ " -------- ------------------------------- 0.5/2.5 MB 980.0 kB/s eta 0:00:03\n",
100
+ " ------------ --------------------------- 0.8/2.5 MB 542.1 kB/s eta 0:00:04\n",
101
+ " ------------ --------------------------- 0.8/2.5 MB 542.1 kB/s eta 0:00:04\n",
102
+ " ---------------- ----------------------- 1.0/2.5 MB 566.9 kB/s eta 0:00:03\n",
103
+ " ---------------- ----------------------- 1.0/2.5 MB 566.9 kB/s eta 0:00:03\n",
104
+ " -------------------- ------------------- 1.3/2.5 MB 630.6 kB/s eta 0:00:02\n",
105
+ " -------------------- ------------------- 1.3/2.5 MB 630.6 kB/s eta 0:00:02\n",
106
+ " -------------------- ------------------- 1.3/2.5 MB 630.6 kB/s eta 0:00:02\n",
107
+ " ----------------------------- ---------- 1.8/2.5 MB 641.9 kB/s eta 0:00:02\n",
108
+ " ----------------------------- ---------- 1.8/2.5 MB 641.9 kB/s eta 0:00:02\n",
109
+ " ----------------------------- ---------- 1.8/2.5 MB 641.9 kB/s eta 0:00:02\n",
110
+ " --------------------------------- ------ 2.1/2.5 MB 634.3 kB/s eta 0:00:01\n",
111
+ " --------------------------------- ------ 2.1/2.5 MB 634.3 kB/s eta 0:00:01\n",
112
+ " ------------------------------------- -- 2.4/2.5 MB 613.0 kB/s eta 0:00:01\n",
113
+ " ------------------------------------- -- 2.4/2.5 MB 613.0 kB/s eta 0:00:01\n",
114
+ " ---------------------------------------- 2.5/2.5 MB 587.5 kB/s eta 0:00:00\n",
115
+ "Downloading huggingface_hub-0.35.3-py3-none-any.whl (564 kB)\n",
116
+ " ---------------------------------------- 0.0/564.3 kB ? eta -:--:--\n",
117
+ " ---------------------------------------- 0.0/564.3 kB ? eta -:--:--\n",
118
+ " ---------------------------------------- 0.0/564.3 kB ? eta -:--:--\n",
119
+ " ---------------------------------------- 0.0/564.3 kB ? eta -:--:--\n",
120
+ " ------------------ --------------------- 262.1/564.3 kB ? eta -:--:--\n",
121
+ " ---------------------------------------- 564.3/564.3 kB 1.1 MB/s eta 0:00:00\n",
122
+ "Downloading safetensors-0.6.2-cp38-abi3-win_amd64.whl (320 kB)\n",
123
+ "Installing collected packages: safetensors, huggingface_hub, timm\n",
124
+ "\n",
125
+ " ------------- -------------------------- 1/3 [huggingface_hub]\n",
126
+ " ------------- -------------------------- 1/3 [huggingface_hub]\n",
127
+ " ------------- -------------------------- 1/3 [huggingface_hub]\n",
128
+ " ------------- -------------------------- 1/3 [huggingface_hub]\n",
129
+ " ------------- -------------------------- 1/3 [huggingface_hub]\n",
130
+ " -------------------------- ------------- 2/3 [timm]\n",
131
+ " -------------------------- ------------- 2/3 [timm]\n",
132
+ " -------------------------- ------------- 2/3 [timm]\n",
133
+ " -------------------------- ------------- 2/3 [timm]\n",
134
+ " -------------------------- ------------- 2/3 [timm]\n",
135
+ " -------------------------- ------------- 2/3 [timm]\n",
136
+ " -------------------------- ------------- 2/3 [timm]\n",
137
+ " -------------------------- ------------- 2/3 [timm]\n",
138
+ " -------------------------- ------------- 2/3 [timm]\n",
139
+ " -------------------------- ------------- 2/3 [timm]\n",
140
+ " ---------------------------------------- 3/3 [timm]\n",
141
+ "\n",
142
+ "Successfully installed huggingface_hub-0.35.3 safetensors-0.6.2 timm-1.0.20\n",
143
+ "Note: you may need to restart the kernel to use updated packages.\n"
144
+ ]
145
+ }
146
+ ],
147
+ "source": [
148
+ "pip install timm\n"
149
+ ]
150
+ },
151
+ {
152
+ "cell_type": "markdown",
153
+ "metadata": {},
154
+ "source": [
155
+ "# Loading Metadata"
156
+ ]
157
+ },
158
+ {
159
+ "cell_type": "code",
160
+ "execution_count": 2,
161
+ "metadata": {},
162
+ "outputs": [
163
+ {
164
+ "name": "stdout",
165
+ "output_type": "stream",
166
+ "text": [
167
+ "386006 772\n"
168
+ ]
169
+ }
170
+ ],
171
+ "source": [
172
+ "metadata = pd.read_csv(\"train_metadata.csv\")\n",
173
+ "labels_species = metadata['binomial']\n",
174
+ "lb_species = LabelBinarizer()\n",
175
+ "lb_species.fit(np.asarray(labels_species))\n",
176
+ "\n",
177
+ "print(len(metadata), len(metadata['binomial'].unique()))"
178
+ ]
179
+ },
180
+ {
181
+ "cell_type": "code",
182
+ "execution_count": null,
183
+ "metadata": {},
184
+ "outputs": [],
185
+ "source": [
186
+ "test_metadata = pd.read_csv(\"../metadata/SnakeCLEF2021_TEST_METADATA-PRIVATE.csv\")\n",
187
+ "test_metadata[\"image_path\"] = test_metadata['file_path'].apply(lambda x: \"/local/nahouby/Datasets/SnakeCLEF2021-test/test-inat-post-4.2/\" + x)\n",
188
+ "test_metadata.fillna('unknown', inplace=True)\n",
189
+ "\n",
190
+ "test_metadata.head(5)"
191
+ ]
192
+ },
193
+ {
194
+ "cell_type": "code",
195
+ "execution_count": null,
196
+ "metadata": {},
197
+ "outputs": [],
198
+ "source": [
199
+ "country_relevance = pd.read_csv(\"../metadata/Species_Relevance.csv\", sep=';')\n",
200
+ "country_relevance = country_relevance.rename(columns={'Unnamed: 0': 'binomial'})\n",
201
+ "KO_species = set(country_relevance['binomial']) - set(metadata['binomial'])\n",
202
+ "country_relevance = country_relevance[~country_relevance.binomial.isin(KO_species)]\n",
203
+ "country_relevance = country_relevance.reset_index().drop(columns=['index'])\n",
204
+ "country_relevance['class_id'] = country_relevance.apply(lambda row: np.where(lb_species.classes_ == row['binomial'])[0][0], axis=1)\n",
205
+ "country_relevance = country_relevance.sort_values(by=['class_id'])"
206
+ ]
207
+ },
208
+ {
209
+ "cell_type": "markdown",
210
+ "metadata": {},
211
+ "source": [
212
+ "# Loading Model"
213
+ ]
214
+ },
215
+ {
216
+ "cell_type": "code",
217
+ "execution_count": 5,
218
+ "metadata": {},
219
+ "outputs": [],
220
+ "source": [
221
+ "def getModel(architecture_name, target_size, pretrained = False):\n",
222
+ " net = timm.create_model(architecture_name, pretrained=pretrained)\n",
223
+ " net_cfg = net.default_cfg\n",
224
+ " last_layer = net_cfg['classifier']\n",
225
+ " num_ftrs = getattr(net, last_layer).in_features\n",
226
+ " setattr(net, last_layer, nn.Linear(num_ftrs, target_size))\n",
227
+ " return net"
228
+ ]
229
+ },
230
+ {
231
+ "cell_type": "code",
232
+ "execution_count": 7,
233
+ "metadata": {},
234
+ "outputs": [
235
+ {
236
+ "name": "stdout",
237
+ "output_type": "stream",
238
+ "text": [
239
+ "Done.\n"
240
+ ]
241
+ }
242
+ ],
243
+ "source": [
244
+ "# %%\n",
245
+ "N_CLASSES = 772\n",
246
+ "MODEL_NAME = 'vit_large_patch16_384'\n",
247
+ "model = getModel(MODEL_NAME, N_CLASSES, pretrained=True)\n",
248
+ "model_mean = list(model.default_cfg['mean'])\n",
249
+ "model_std = list(model.default_cfg['std'])\n",
250
+ "\n",
251
+ "model.load_state_dict(torch.load('../../SnakeCLEF2021/CKPTS/SnakeCLEF2021-ViT_large_patch16-384-FT-FL-OCLR-20E.pth'))\n",
252
+ "\n",
253
+ "model.to(device)\n",
254
+ "model.eval()\n",
255
+ "print('Done.')"
256
+ ]
257
+ },
258
+ {
259
+ "cell_type": "markdown",
260
+ "metadata": {},
261
+ "source": [
262
+ "# Load Data etc."
263
+ ]
264
+ },
265
+ {
266
+ "cell_type": "code",
267
+ "execution_count": 10,
268
+ "metadata": {},
269
+ "outputs": [],
270
+ "source": [
271
+ "def seed_torch(seed=777):\n",
272
+ " random.seed(seed)\n",
273
+ " os.environ['PYTHONHASHSEED'] = str(seed)\n",
274
+ " np.random.seed(seed)\n",
275
+ " torch.manual_seed(seed)\n",
276
+ " torch.cuda.manual_seed(seed)\n",
277
+ " torch.backends.cudnn.deterministic = True\n",
278
+ "\n",
279
+ " \n",
280
+ "class CustomDataset(Dataset):\n",
281
+ " def __init__(self, df, transform=None):\n",
282
+ " self.df = df\n",
283
+ " self.transform = transform\n",
284
+ " \n",
285
+ " def __len__(self):\n",
286
+ " return len(self.df)\n",
287
+ "\n",
288
+ " def __getitem__(self, idx):\n",
289
+ " file_path = self.df['image_path'].values[idx]\n",
290
+ " continent = self.df['continent'].values[idx]\n",
291
+ " country = self.df['country'].values[idx]\n",
292
+ " class_id = self.df['class_id'].values[idx]\n",
293
+ " image = cv2.imread(file_path)\n",
294
+ " try:\n",
295
+ " image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n",
296
+ " except:\n",
297
+ " print(file_path)\n",
298
+ " \n",
299
+ " if self.transform:\n",
300
+ " augmented = self.transform(image=image)\n",
301
+ " image = augmented['image']\n",
302
+ " \n",
303
+ " return image, file_path, class_id, country, continent\n",
304
+ " \n",
305
+ "SEED = 777\n",
306
+ "seed_torch(SEED)"
307
+ ]
308
+ },
309
+ {
310
+ "cell_type": "code",
311
+ "execution_count": 11,
312
+ "metadata": {},
313
+ "outputs": [],
314
+ "source": [
315
+ "HEIGHT = 384\n",
316
+ "WIDTH = 384\n",
317
+ "\n",
318
+ "from albumentations import RandomGridShuffle, CenterCrop, HueSaturationValue, RandomCrop, HorizontalFlip, VerticalFlip, RandomBrightnessContrast, CenterCrop, PadIfNeeded, RandomResizedCrop, ShiftScaleRotate, Blur, JpegCompression, RandomShadow\n",
319
+ "\n",
320
+ "def get_transforms(*, data):\n",
321
+ " assert data in ('train', 'test1', 'test2', 'test3')\n",
322
+ "\n",
323
+ " if data == 'train':\n",
324
+ " return Compose([\n",
325
+ " RandomResizedCrop(WIDTH, HEIGHT, scale=(0.7, 1.0)),\n",
326
+ " HorizontalFlip(p=0.5),\n",
327
+ " VerticalFlip(p=0.5),\n",
328
+ " ShiftScaleRotate(shift_limit=0.0625, scale_limit=0.25, rotate_limit=45, p=.75),\n",
329
+ " JpegCompression(quality_lower=50, quality_upper=100),\n",
330
+ " #RandomShadow(),\n",
331
+ " Blur(blur_limit=2),\n",
332
+ " RandomBrightnessContrast(p=0.3),\n",
333
+ " HueSaturationValue(p=0.2),\n",
334
+ " Normalize(\n",
335
+ " mean=model_mean,\n",
336
+ " std=model_std,\n",
337
+ " ),\n",
338
+ " ToTensorV2(),\n",
339
+ " ])\n",
340
+ "\n",
341
+ " elif data == 'test1':\n",
342
+ " return Compose([\n",
343
+ " Resize(WIDTH, HEIGHT),\n",
344
+ " Normalize(mean = model_mean, std = model_std),\n",
345
+ " ToTensorV2(),\n",
346
+ " ])\n",
347
+ " elif data == 'test2':\n",
348
+ " return Compose([\n",
349
+ " PadIfNeeded(WIDTH, HEIGHT),\n",
350
+ " Resize(int(WIDTH*1.2), int(HEIGHT*1.2)),\n",
351
+ " CenterCrop(WIDTH, HEIGHT),\n",
352
+ " Normalize(mean = model_mean, std = model_std),\n",
353
+ " ToTensorV2(),\n",
354
+ " ])\n",
355
+ " elif data == 'test3':\n",
356
+ " return Compose([\n",
357
+ " PadIfNeeded(WIDTH, HEIGHT),\n",
358
+ " Resize(int(WIDTH*1.5), int(HEIGHT*1.5)),\n",
359
+ " CenterCrop(WIDTH, HEIGHT),\n",
360
+ " Normalize(mean = model_mean, std = model_std),\n",
361
+ " ToTensorV2(),\n",
362
+ " ])"
363
+ ]
364
+ },
365
+ {
366
+ "cell_type": "markdown",
367
+ "metadata": {},
368
+ "source": [
369
+ "# Testing"
370
+ ]
371
+ },
372
+ {
373
+ "cell_type": "code",
374
+ "execution_count": 12,
375
+ "metadata": {},
376
+ "outputs": [],
377
+ "source": [
378
+ "BATCH_SIZE = 16\n",
379
+ "WORKERS = 8\n",
380
+ "\n",
381
+ "test_dataset_1 = CustomDataset(test_metadata, transform=get_transforms(data='test1'))\n",
382
+ "test_loader_1 = DataLoader(test_dataset_1, batch_size=BATCH_SIZE, shuffle=False, num_workers=WORKERS)\n",
383
+ "\n",
384
+ "test_dataset_2 = CustomDataset(test_metadata, transform=get_transforms(data='test2'))\n",
385
+ "test_loader_2 = DataLoader(test_dataset_2, batch_size=BATCH_SIZE, shuffle=False, num_workers=WORKERS)\n",
386
+ "\n",
387
+ "test_dataset_3 = CustomDataset(test_metadata, transform=get_transforms(data='test3'))\n",
388
+ "test_loader_3 = DataLoader(test_dataset_3, batch_size=BATCH_SIZE, shuffle=False, num_workers=WORKERS)"
389
+ ]
390
+ },
391
+ {
392
+ "cell_type": "markdown",
393
+ "metadata": {},
394
+ "source": [
395
+ "### Test with Augmentations v1"
396
+ ]
397
+ },
398
+ {
399
+ "cell_type": "code",
400
+ "execution_count": null,
401
+ "metadata": {},
402
+ "outputs": [],
403
+ "source": [
404
+ "preds = np.zeros((len(test_metadata)), dtype=np.int64)\n",
405
+ "GT_lbls = []\n",
406
+ "image_paths = []\n",
407
+ "preds_raw = []\n",
408
+ "countries = []\n",
409
+ "continents = []\n",
410
+ "\n",
411
+ "for i, (images, paths, labels, counts, conts) in enumerate(tqdm.tqdm(test_loader_1, total=len(test_loader_1))):\n",
412
+ "\n",
413
+ " images = images.to(device)\n",
414
+ " labels = labels.to(device)\n",
415
+ " \n",
416
+ " with torch.no_grad():\n",
417
+ " y_preds = model(images)\n",
418
+ " \n",
419
+ " preds[i * BATCH_SIZE: (i+1) * BATCH_SIZE] = y_preds.argmax(1).to('cpu').numpy()\n",
420
+ " GT_lbls.extend(labels.to('cpu').numpy())\n",
421
+ " preds_raw.extend(y_preds.to('cpu').numpy())\n",
422
+ " image_paths.extend(paths)\n",
423
+ " countries.extend(counts)\n",
424
+ " continents.extend(conts)"
425
+ ]
426
+ },
427
+ {
428
+ "cell_type": "code",
429
+ "execution_count": 15,
430
+ "metadata": {},
431
+ "outputs": [],
432
+ "source": [
433
+ "test_metadata['logits_t1'] = preds_raw\n",
434
+ "test_metadata['preds_t1'] = [np.argmax(p) for p in preds_raw]"
435
+ ]
436
+ },
437
+ {
438
+ "cell_type": "code",
439
+ "execution_count": 17,
440
+ "metadata": {},
441
+ "outputs": [
442
+ {
443
+ "name": "stdout",
444
+ "output_type": "stream",
445
+ "text": [
446
+ "Test Augmentation 1: 88.77 94.13\n"
447
+ ]
448
+ }
449
+ ],
450
+ "source": [
451
+ "from sklearn.metrics import f1_score, accuracy_score, top_k_accuracy_score, classification_report\n",
452
+ "\n",
453
+ "vanilla_f1 = f1_score(test_metadata['class_id'], test_metadata['preds_t1'], average='macro')\n",
454
+ "vanilla_accuracy = accuracy_score(test_metadata['class_id'], test_metadata['preds_t1'])\n",
455
+ "\n",
456
+ "print('Test Augmentation 1:', np.round(vanilla_f1 * 100, 2), np.round(vanilla_accuracy * 100, 2))"
457
+ ]
458
+ },
459
+ {
460
+ "cell_type": "code",
461
+ "execution_count": 18,
462
+ "metadata": {},
463
+ "outputs": [],
464
+ "source": [
465
+ "output = pd.DataFrame(zip(test_metadata.UUID, preds), columns =['UUID', 'prediction'])\n",
466
+ "output.to_csv('vanilla.csv', index=False)"
467
+ ]
468
+ },
469
+ {
470
+ "cell_type": "markdown",
471
+ "metadata": {},
472
+ "source": [
473
+ "### Test with Augmentations v2"
474
+ ]
475
+ },
476
+ {
477
+ "cell_type": "code",
478
+ "execution_count": null,
479
+ "metadata": {},
480
+ "outputs": [],
481
+ "source": [
482
+ "preds = np.zeros((len(test_metadata)))\n",
483
+ "GT_lbls = []\n",
484
+ "image_paths = []\n",
485
+ "preds_raw = []\n",
486
+ "countries = []\n",
487
+ "continents = []\n",
488
+ "\n",
489
+ "for i, (images, paths, labels, counts, conts) in enumerate(tqdm.tqdm(test_loader_2, total=len(test_loader_2))):\n",
490
+ "\n",
491
+ " images = images.to(device)\n",
492
+ " labels = labels.to(device)\n",
493
+ " \n",
494
+ " with torch.no_grad():\n",
495
+ " y_preds = model(images)\n",
496
+ " \n",
497
+ " preds[i * BATCH_SIZE: (i+1) * BATCH_SIZE] = y_preds.argmax(1).to('cpu').numpy()\n",
498
+ " GT_lbls.extend(labels.to('cpu').numpy())\n",
499
+ " preds_raw.extend(y_preds.to('cpu').numpy())\n",
500
+ " image_paths.extend(paths)\n",
501
+ " countries.extend(counts)\n",
502
+ " continents.extend(conts)"
503
+ ]
504
+ },
505
+ {
506
+ "cell_type": "code",
507
+ "execution_count": 21,
508
+ "metadata": {},
509
+ "outputs": [],
510
+ "source": [
511
+ "test_metadata['logits_t2'] = preds_raw\n",
512
+ "test_metadata['preds_t2'] = [np.argmax(p) for p in preds_raw]"
513
+ ]
514
+ },
515
+ {
516
+ "cell_type": "code",
517
+ "execution_count": 22,
518
+ "metadata": {},
519
+ "outputs": [
520
+ {
521
+ "name": "stdout",
522
+ "output_type": "stream",
523
+ "text": [
524
+ "Test Augmentation 2: 88.68 94.55\n"
525
+ ]
526
+ }
527
+ ],
528
+ "source": [
529
+ "from sklearn.metrics import f1_score, accuracy_score, top_k_accuracy_score, classification_report\n",
530
+ "\n",
531
+ "vanilla_f1 = f1_score(test_metadata['class_id'], test_metadata['preds_t2'], average='macro')\n",
532
+ "vanilla_accuracy = accuracy_score(test_metadata['class_id'], test_metadata['preds_t2'])\n",
533
+ "\n",
534
+ "print('Test Augmentation 2:', np.round(vanilla_f1 * 100, 2), np.round(vanilla_accuracy * 100, 2))"
535
+ ]
536
+ },
537
+ {
538
+ "cell_type": "markdown",
539
+ "metadata": {},
540
+ "source": [
541
+ "### Test with Augmentations v3"
542
+ ]
543
+ },
544
+ {
545
+ "cell_type": "code",
546
+ "execution_count": null,
547
+ "metadata": {},
548
+ "outputs": [],
549
+ "source": [
550
+ "preds = np.zeros((len(test_metadata)))\n",
551
+ "GT_lbls = []\n",
552
+ "image_paths = []\n",
553
+ "preds_raw = []\n",
554
+ "countries = []\n",
555
+ "continents = []\n",
556
+ "\n",
557
+ "for i, (images, paths, labels, counts, conts) in enumerate(tqdm.tqdm(test_loader_3, total=len(test_loader_3))):\n",
558
+ "\n",
559
+ " images = images.to(device)\n",
560
+ " labels = labels.to(device)\n",
561
+ " \n",
562
+ " with torch.no_grad():\n",
563
+ " y_preds = model(images)\n",
564
+ " \n",
565
+ " preds[i * BATCH_SIZE: (i+1) * BATCH_SIZE] = y_preds.argmax(1).to('cpu').numpy()\n",
566
+ " GT_lbls.extend(labels.to('cpu').numpy())\n",
567
+ " preds_raw.extend(y_preds.to('cpu').numpy())\n",
568
+ " image_paths.extend(paths)\n",
569
+ " countries.extend(counts)\n",
570
+ " continents.extend(conts)"
571
+ ]
572
+ },
573
+ {
574
+ "cell_type": "code",
575
+ "execution_count": 24,
576
+ "metadata": {},
577
+ "outputs": [],
578
+ "source": [
579
+ "test_metadata['logits_t3'] = preds_raw\n",
580
+ "test_metadata['preds_t3'] = [np.argmax(p) for p in preds_raw]"
581
+ ]
582
+ },
583
+ {
584
+ "cell_type": "code",
585
+ "execution_count": 25,
586
+ "metadata": {},
587
+ "outputs": [
588
+ {
589
+ "name": "stdout",
590
+ "output_type": "stream",
591
+ "text": [
592
+ "Test Augmentation 3: 88.58 93.92\n"
593
+ ]
594
+ }
595
+ ],
596
+ "source": [
597
+ "from sklearn.metrics import f1_score, accuracy_score, top_k_accuracy_score, classification_report\n",
598
+ "\n",
599
+ "vanilla_f1 = f1_score(test_metadata['class_id'], test_metadata['preds_t3'], average='macro')\n",
600
+ "vanilla_accuracy = accuracy_score(test_metadata['class_id'], test_metadata['preds_t3'])\n",
601
+ "\n",
602
+ "print('Test Augmentation 3:', np.round(vanilla_f1 * 100, 2), np.round(vanilla_accuracy * 100, 2))"
603
+ ]
604
+ },
605
+ {
606
+ "cell_type": "markdown",
607
+ "metadata": {},
608
+ "source": [
609
+ "### Prediction Mean"
610
+ ]
611
+ },
612
+ {
613
+ "cell_type": "code",
614
+ "execution_count": null,
615
+ "metadata": {},
616
+ "outputs": [],
617
+ "source": [
618
+ "test_metadata['mean_softmax'] = 0\n",
619
+ "\n",
620
+ "for index, row in tqdm.tqdm(test_metadata.iterrows(), total=len(test_metadata)):\n",
621
+ " max_index = np.argmax(sum((softmax(row.logits_t1), softmax(row.logits_t2), softmax(row.logits_t3))))\n",
622
+ " test_metadata.at[index, 'mean_softmax'] = max_index"
623
+ ]
624
+ },
625
+ {
626
+ "cell_type": "code",
627
+ "execution_count": 28,
628
+ "metadata": {},
629
+ "outputs": [
630
+ {
631
+ "name": "stdout",
632
+ "output_type": "stream",
633
+ "text": [
634
+ "Mean softmax: 89.13 95.15\n"
635
+ ]
636
+ }
637
+ ],
638
+ "source": [
639
+ "vanilla_f1 = f1_score(test_metadata['class_id'], test_metadata['mean_softmax'], average='macro')\n",
640
+ "vanilla_accuracy = accuracy_score(test_metadata['class_id'], test_metadata['mean_softmax'])\n",
641
+ "\n",
642
+ "print('Mean softmax:', np.round(vanilla_f1 * 100, 2), np.round(vanilla_accuracy * 100, 2))"
643
+ ]
644
+ },
645
+ {
646
+ "cell_type": "code",
647
+ "execution_count": 29,
648
+ "metadata": {},
649
+ "outputs": [],
650
+ "source": [
651
+ "output = pd.DataFrame(zip(test_metadata.UUID, test_metadata.mean_softmax), columns =['UUID', 'prediction'])\n",
652
+ "output.to_csv('mean_softmax.csv', index=False)"
653
+ ]
654
+ },
655
+ {
656
+ "cell_type": "markdown",
657
+ "metadata": {},
658
+ "source": [
659
+ "# Metadata extraction"
660
+ ]
661
+ },
662
+ {
663
+ "cell_type": "markdown",
664
+ "metadata": {},
665
+ "source": [
666
+ "### Extracting Species distribution"
667
+ ]
668
+ },
669
+ {
670
+ "cell_type": "code",
671
+ "execution_count": 30,
672
+ "metadata": {},
673
+ "outputs": [],
674
+ "source": [
675
+ "class_priors = np.ones(len(metadata['class_id'].unique()))\n",
676
+ "for species in metadata['class_id'].unique():\n",
677
+ " class_priors[species] = len(metadata[metadata['class_id'] == species])\n",
678
+ "\n",
679
+ "class_priors = class_priors / sum(class_priors)"
680
+ ]
681
+ },
682
+ {
683
+ "cell_type": "code",
684
+ "execution_count": null,
685
+ "metadata": {},
686
+ "outputs": [],
687
+ "source": [
688
+ "class_2_genus = {}\n",
689
+ "for _, row in tqdm.tqdm(metadata.iterrows(), total=len(metadata)):\n",
690
+ " if row.class_id not in class_2_genus:\n",
691
+ " class_2_genus[row.class_id] = row.genus\n",
692
+ " \n",
693
+ "class_2_family = {}\n",
694
+ "for _, row in tqdm.tqdm(metadata.iterrows(), total=len(metadata)):\n",
695
+ " if row.class_id not in class_2_family:\n",
696
+ " class_2_family[row.class_id] = row.family"
697
+ ]
698
+ },
699
+ {
700
+ "cell_type": "markdown",
701
+ "metadata": {},
702
+ "source": [
703
+ "### Country Distribution"
704
+ ]
705
+ },
706
+ {
707
+ "cell_type": "code",
708
+ "execution_count": null,
709
+ "metadata": {},
710
+ "outputs": [],
711
+ "source": [
712
+ "country_distributions = {}\n",
713
+ "\n",
714
+ "for _, observation in tqdm.tqdm(metadata.iterrows(), total=len(metadata)):\n",
715
+ " country = str(observation.country)\n",
716
+ " class_id = observation.class_id\n",
717
+ " if country not in country_distributions: \n",
718
+ " country_distributions[country] = np.ones(len(metadata['class_id'].unique()))\n",
719
+ " else:\n",
720
+ " country_distributions[country][class_id] += 1\n",
721
+ "\n",
722
+ "for key, value in country_distributions.items():\n",
723
+ " country_distributions[key] = value / sum(value)"
724
+ ]
725
+ },
726
+ {
727
+ "cell_type": "markdown",
728
+ "metadata": {},
729
+ "source": [
730
+ "### Continent Distribution"
731
+ ]
732
+ },
733
+ {
734
+ "cell_type": "code",
735
+ "execution_count": null,
736
+ "metadata": {},
737
+ "outputs": [],
738
+ "source": [
739
+ "continent_distributions = {}\n",
740
+ "\n",
741
+ "for _, observation in tqdm.tqdm(metadata.iterrows(), total=len(metadata)):\n",
742
+ " continent = str(observation.continent)\n",
743
+ " class_id = observation.class_id\n",
744
+ " if continent not in continent_distributions: \n",
745
+ " continent_distributions[continent] = np.ones(len(metadata['class_id'].unique()))\n",
746
+ " else:\n",
747
+ " continent_distributions[continent][class_id] += 1\n",
748
+ "\n",
749
+ "for key, value in continent_distributions.items():\n",
750
+ " continent_distributions[key] = value / sum(value)"
751
+ ]
752
+ },
753
+ {
754
+ "cell_type": "markdown",
755
+ "metadata": {},
756
+ "source": [
757
+ "# Prior Weighting"
758
+ ]
759
+ },
760
+ {
761
+ "cell_type": "markdown",
762
+ "metadata": {},
763
+ "source": [
764
+ "## Binary filtration"
765
+ ]
766
+ },
767
+ {
768
+ "cell_type": "code",
769
+ "execution_count": 35,
770
+ "metadata": {},
771
+ "outputs": [
772
+ {
773
+ "name": "stderr",
774
+ "output_type": "stream",
775
+ "text": [
776
+ "100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 23673/23673 [00:04<00:00, 4931.83it/s]\n"
777
+ ]
778
+ },
779
+ {
780
+ "name": "stdout",
781
+ "output_type": "stream",
782
+ "text": [
783
+ "Binary Masking:\n",
784
+ "F1: 92.24 Acc: 96.0\n",
785
+ "F1 dif: 3.11 Acc dif: 0.84\n"
786
+ ]
787
+ }
788
+ ],
789
+ "source": [
790
+ "test_metadata['binary_filtration'] = 0\n",
791
+ "\n",
792
+ "for index, row in tqdm.tqdm(test_metadata.iterrows(), total=len(test_metadata)):\n",
793
+ "\n",
794
+ " country = row.country\n",
795
+ " \n",
796
+ " preds = sum((softmax(row.logits_t1), softmax(row.logits_t2), softmax(row.logits_t3))) / 3\n",
797
+ "\n",
798
+ " if country == 'Republic of Congo':\n",
799
+ " country = 'republic of the congo'\n",
800
+ "\n",
801
+ " if country in ['unknown', 'West Bank', 'Macau S.A.R', 'US Naval Base Guantanamo Bay', 'United States Virgin Islands', 'Guam', 'Turks and Caicos Islands', 'Cyprus No Mans Area']:\n",
802
+ " preds = preds\n",
803
+ " else:\n",
804
+ " preds = preds * np.array(country_relevance[country.lower()], dtype=np.int32)\n",
805
+ "\n",
806
+ " max_index = np.argmax(preds) \n",
807
+ " \n",
808
+ " test_metadata.at[index, 'binary_filtration'] = max_index\n",
809
+ "\n",
810
+ "f1 = f1_score(test_metadata['class_id'], test_metadata['binary_filtration'], average='macro')\n",
811
+ "accuracy = accuracy_score(test_metadata['class_id'], test_metadata['binary_filtration'])\n",
812
+ "print('Binary Masking:')\n",
813
+ "print('F1:', np.round(f1 * 100, 2), 'Acc:', np.round(accuracy * 100, 2))\n",
814
+ "print('F1 dif:', np.round((f1-vanilla_f1) * 100, 2), 'Acc dif:', np.round((accuracy-vanilla_accuracy) * 100, 2)) "
815
+ ]
816
+ },
817
+ {
818
+ "cell_type": "code",
819
+ "execution_count": 36,
820
+ "metadata": {},
821
+ "outputs": [],
822
+ "source": [
823
+ "output = pd.DataFrame(zip(test_metadata.UUID, test_metadata.binary_filtration), columns =['UUID', 'prediction'])\n",
824
+ "output.to_csv('masking.csv', index=False)"
825
+ ]
826
+ },
827
+ {
828
+ "cell_type": "markdown",
829
+ "metadata": {},
830
+ "source": [
831
+ "## Country Weighting"
832
+ ]
833
+ },
834
+ {
835
+ "cell_type": "code",
836
+ "execution_count": 37,
837
+ "metadata": {},
838
+ "outputs": [
839
+ {
840
+ "name": "stderr",
841
+ "output_type": "stream",
842
+ "text": [
843
+ "100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 23673/23673 [00:06<00:00, 3553.41it/s]"
844
+ ]
845
+ },
846
+ {
847
+ "name": "stdout",
848
+ "output_type": "stream",
849
+ "text": [
850
+ "Binary Masking:\n",
851
+ "F1: 92.27 Acc: 95.92\n",
852
+ "F1 dif: 3.14 Acc dif: 0.77\n"
853
+ ]
854
+ },
855
+ {
856
+ "name": "stderr",
857
+ "output_type": "stream",
858
+ "text": [
859
+ "\n"
860
+ ]
861
+ }
862
+ ],
863
+ "source": [
864
+ "test_metadata['country_weighting'] = 0\n",
865
+ "\n",
866
+ "\n",
867
+ "for index, row in tqdm.tqdm(test_metadata.iterrows(), total=len(test_metadata)):\n",
868
+ "\n",
869
+ " country = row.country\n",
870
+ " preds = sum((softmax(row.logits_t1), softmax(row.logits_t2), softmax(row.logits_t3))) / 3\n",
871
+ " \n",
872
+ " if country not in country_distributions:\n",
873
+ " country = 'unknown'\n",
874
+ " country_dist = country_distributions[country]\n",
875
+ " \n",
876
+ " p_countries = (preds * country_dist) / sum(preds * country_dist)\n",
877
+ " prior_ratio = p_countries / class_priors\n",
878
+ " max_index = np.argmax(prior_ratio * preds) \n",
879
+ " \n",
880
+ " test_metadata.at[index, 'country_weighting'] = max_index\n",
881
+ " \n",
882
+ "f1 = f1_score(test_metadata['class_id'], test_metadata['country_weighting'], average='macro')\n",
883
+ "accuracy = accuracy_score(test_metadata['class_id'], test_metadata['country_weighting'])\n",
884
+ "print('Binary Masking:')\n",
885
+ "print('F1:', np.round(f1 * 100, 2), 'Acc:', np.round(accuracy * 100, 2))\n",
886
+ "print('F1 dif:', np.round((f1-vanilla_f1) * 100, 2), 'Acc dif:', np.round((accuracy-vanilla_accuracy) * 100, 2)) "
887
+ ]
888
+ },
889
+ {
890
+ "cell_type": "code",
891
+ "execution_count": null,
892
+ "metadata": {},
893
+ "outputs": [],
894
+ "source": [
895
+ "output = pd.DataFrame(zip(test_metadata.UUID, test_metadata.country_weighting), columns =['UUID', 'prediction'])\n",
896
+ "output.to_csv('country_weighting.csv', index=False)"
897
+ ]
898
+ },
899
+ {
900
+ "cell_type": "markdown",
901
+ "metadata": {},
902
+ "source": [
903
+ "## Continent Weighting"
904
+ ]
905
+ },
906
+ {
907
+ "cell_type": "code",
908
+ "execution_count": 38,
909
+ "metadata": {},
910
+ "outputs": [
911
+ {
912
+ "name": "stderr",
913
+ "output_type": "stream",
914
+ "text": [
915
+ "100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████���█████████████████████████████████████████████████████████| 23673/23673 [00:06<00:00, 3609.67it/s]"
916
+ ]
917
+ },
918
+ {
919
+ "name": "stdout",
920
+ "output_type": "stream",
921
+ "text": [
922
+ "Binary Masking:\n",
923
+ "F1: 91.16 Acc: 95.15\n",
924
+ "F1 dif: 2.03 Acc dif: 0.0\n"
925
+ ]
926
+ },
927
+ {
928
+ "name": "stderr",
929
+ "output_type": "stream",
930
+ "text": [
931
+ "\n"
932
+ ]
933
+ }
934
+ ],
935
+ "source": [
936
+ "test_metadata['continent_weighting'] = 0\n",
937
+ "\n",
938
+ "\n",
939
+ "for index, row in tqdm.tqdm(test_metadata.iterrows(), total=len(test_metadata)):\n",
940
+ "\n",
941
+ " continent = row.continent\n",
942
+ " preds = sum((softmax(row.logits_t1), softmax(row.logits_t2), softmax(row.logits_t3))) / 3\n",
943
+ " \n",
944
+ " continent_dist = continent_distributions[continent]\n",
945
+ " \n",
946
+ " p_continent = (preds * continent_dist) / sum(preds * continent_dist)\n",
947
+ " prior_ratio = p_continent / class_priors\n",
948
+ " max_index = np.argmax(prior_ratio * preds) \n",
949
+ " \n",
950
+ " test_metadata.at[index, 'continent_weighting'] = max_index\n",
951
+ " \n",
952
+ "f1 = f1_score(test_metadata['class_id'], test_metadata['continent_weighting'], average='macro')\n",
953
+ "accuracy = accuracy_score(test_metadata['class_id'], test_metadata['continent_weighting'])\n",
954
+ "print('Binary Masking:')\n",
955
+ "print('F1:', np.round(f1 * 100, 2), 'Acc:', np.round(accuracy * 100, 2))\n",
956
+ "print('F1 dif:', np.round((f1-vanilla_f1) * 100, 2), 'Acc dif:', np.round((accuracy-vanilla_accuracy) * 100, 2)) "
957
+ ]
958
+ },
959
+ {
960
+ "cell_type": "code",
961
+ "execution_count": 39,
962
+ "metadata": {},
963
+ "outputs": [],
964
+ "source": [
965
+ "output = pd.DataFrame(zip(test_metadata.UUID, test_metadata.continent_weighting), columns =['UUID', 'prediction'])\n",
966
+ "output.to_csv('continent_weighting.csv', index=False)"
967
+ ]
968
+ },
969
+ {
970
+ "cell_type": "markdown",
971
+ "metadata": {},
972
+ "source": [
973
+ "## Continent Weighting + Binary Masking"
974
+ ]
975
+ },
976
+ {
977
+ "cell_type": "code",
978
+ "execution_count": 40,
979
+ "metadata": {},
980
+ "outputs": [
981
+ {
982
+ "name": "stderr",
983
+ "output_type": "stream",
984
+ "text": [
985
+ "100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 23673/23673 [00:07<00:00, 3374.14it/s]\n"
986
+ ]
987
+ },
988
+ {
989
+ "name": "stdout",
990
+ "output_type": "stream",
991
+ "text": [
992
+ "Binary Masking + Continent:\n",
993
+ "F1: 92.08 Acc: 95.18\n",
994
+ "F1 dif: 2.95 Acc dif: 0.03\n"
995
+ ]
996
+ }
997
+ ],
998
+ "source": [
999
+ "test_metadata['continent_binary'] = 0\n",
1000
+ "\n",
1001
+ "\n",
1002
+ "for index, row in tqdm.tqdm(test_metadata.iterrows(), total=len(test_metadata)):\n",
1003
+ " country = row.country\n",
1004
+ " continent = row.continent\n",
1005
+ " preds = sum((softmax(row.logits_t1), softmax(row.logits_t2), softmax(row.logits_t3))) / 3\n",
1006
+ " \n",
1007
+ " \n",
1008
+ " if country == 'Republic of Congo':\n",
1009
+ " country = 'republic of the congo'\n",
1010
+ "\n",
1011
+ " if country in ['unknown', 'West Bank', 'Macau S.A.R', 'US Naval Base Guantanamo Bay', 'United States Virgin Islands', 'Guam', 'Turks and Caicos Islands', 'Cyprus No Mans Area']:\n",
1012
+ " preds = preds\n",
1013
+ " else:\n",
1014
+ " preds = preds * np.array(country_relevance[country.lower()], dtype=np.int32)\n",
1015
+ "\n",
1016
+ "\n",
1017
+ " continent_dist = continent_distributions[continent]\n",
1018
+ " \n",
1019
+ " p_continent = (preds * continent_dist) / sum(preds * continent_dist)\n",
1020
+ " prior_ratio = p_continent / class_priors\n",
1021
+ " max_index = np.argmax(prior_ratio * preds) \n",
1022
+ " \n",
1023
+ " test_metadata.at[index, 'continent_binary'] = max_index\n",
1024
+ " \n",
1025
+ "f1 = f1_score(test_metadata['class_id'], test_metadata['continent_binary'], average='macro')\n",
1026
+ "accuracy = accuracy_score(test_metadata['class_id'], test_metadata['continent_binary'])\n",
1027
+ "\n",
1028
+ "print('Binary Masking + Continent:')\n",
1029
+ "print('F1:', np.round(f1 * 100, 2), 'Acc:', np.round(accuracy * 100, 2))\n",
1030
+ "print('F1 dif:', np.round((f1-vanilla_f1) * 100, 2), 'Acc dif:', np.round((accuracy-vanilla_accuracy) * 100, 2)) "
1031
+ ]
1032
+ },
1033
+ {
1034
+ "cell_type": "code",
1035
+ "execution_count": 41,
1036
+ "metadata": {},
1037
+ "outputs": [],
1038
+ "source": [
1039
+ "output = pd.DataFrame(zip(test_metadata.UUID, test_metadata.continent_binary), columns =['UUID', 'prediction'])\n",
1040
+ "output.to_csv('continent_binary.csv', index=False)"
1041
+ ]
1042
+ },
1043
+ {
1044
+ "cell_type": "code",
1045
+ "execution_count": null,
1046
+ "metadata": {},
1047
+ "outputs": [],
1048
+ "source": []
1049
+ }
1050
+ ],
1051
+ "metadata": {
1052
+ "kernelspec": {
1053
+ "display_name": "Python 3 (ipykernel)",
1054
+ "language": "python",
1055
+ "name": "python3"
1056
+ },
1057
+ "language_info": {
1058
+ "codemirror_mode": {
1059
+ "name": "ipython",
1060
+ "version": 3
1061
+ },
1062
+ "file_extension": ".py",
1063
+ "mimetype": "text/x-python",
1064
+ "name": "python",
1065
+ "nbconvert_exporter": "python",
1066
+ "pygments_lexer": "ipython3",
1067
+ "version": "3.13.5"
1068
+ }
1069
+ },
1070
+ "nbformat": 4,
1071
+ "nbformat_minor": 4
1072
+ }
notebooks/snake identification.ipynb ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "ea626626-3ef4-47a0-b171-d600b965f6e0",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "import onnxruntime as ort\n",
11
+ "import cv2\n",
12
+ "import numpy as np\n",
13
+ "from scipy.special import softmax\n",
14
+ "import pandas as pd\n",
15
+ "from sklearn.preprocessing import LabelBinarizer\n",
16
+ "\n",
17
+ "# Load training metadata and LabelBinarizer\n",
18
+ "metadata_path = r\"C:\\Users\\General\\OneDrive\\Desktop\\SNAD\\train_metadata.csv\"\n",
19
+ "metadata = pd.read_csv(metadata_path)\n",
20
+ "\n",
21
+ "labels_species = metadata['binomial']\n",
22
+ "lb_species = LabelBinarizer()\n",
23
+ "lb_species.fit(np.asarray(labels_species))\n",
24
+ "\n",
25
+ "# Load ONNX model\n",
26
+ "model_path = r\"C:\\Users\\General\\OneDrive\\Desktop\\SNAD\\ViT_PreProcessing-ops11-preprocessing-int-dynam_graph.onnx\"\n",
27
+ "ort_session = ort.InferenceSession(model_path)\n"
28
+ ]
29
+ },
30
+ {
31
+ "cell_type": "code",
32
+ "execution_count": 2,
33
+ "id": "fe22d4c8-e484-4e41-90f9-cc0d99f3f30b",
34
+ "metadata": {},
35
+ "outputs": [
36
+ {
37
+ "name": "stdout",
38
+ "output_type": "stream",
39
+ "text": [
40
+ "Predicted class ID: 475\n",
41
+ "Predicted species name: Nerodia erythrogaster\n"
42
+ ]
43
+ }
44
+ ],
45
+ "source": [
46
+ "# Prediction function\n",
47
+ "def predict_image_int32(image_path, ort_session, lb_species, height=384, width=384):\n",
48
+ " \"\"\"\n",
49
+ " Predict species from a single image using ONNX ViT that expects int32 input.\n",
50
+ " \"\"\"\n",
51
+ " # Load image\n",
52
+ " image = cv2.imread(image_path)\n",
53
+ " if image is None:\n",
54
+ " raise FileNotFoundError(f\"Image not found: {image_path}\")\n",
55
+ " \n",
56
+ " # Convert BGR to RGB\n",
57
+ " image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n",
58
+ " \n",
59
+ " # Resize\n",
60
+ " image = cv2.resize(image, (width, height))\n",
61
+ " \n",
62
+ " # Convert to int32 (required by your model)\n",
63
+ " image = image.astype(np.int32)\n",
64
+ " \n",
65
+ " # Run ONNX inference\n",
66
+ " outputs = ort_session.run(None, {ort_session.get_inputs()[0].name: image})\n",
67
+ " # print(outputs)\n",
68
+ " logits = outputs[0] # shape: (772,)\n",
69
+ " \n",
70
+ " # Softmax to get probabilities\n",
71
+ " probs = softmax(logits)\n",
72
+ " pred_class = np.argmax(probs)\n",
73
+ " species_name = lb_species.classes_[pred_class]\n",
74
+ " \n",
75
+ " return pred_class, species_name\n",
76
+ "\n",
77
+ "# Test single image\n",
78
+ "image_path = r\"C:\\Users\\General\\OneDrive\\Desktop\\SNAD\\test_image.png\"\n",
79
+ "pred_class, species_name = predict_image_int32(image_path, ort_session, lb_species)\n",
80
+ "\n",
81
+ "print(\"Predicted class ID:\", pred_class)\n",
82
+ "print(\"Predicted species name:\", species_name)\n"
83
+ ]
84
+ },
85
+ {
86
+ "cell_type": "code",
87
+ "execution_count": 5,
88
+ "id": "76decffb-1fc3-49cd-ab11-d18c6ec1ea8e",
89
+ "metadata": {},
90
+ "outputs": [
91
+ {
92
+ "name": "stdout",
93
+ "output_type": "stream",
94
+ "text": [
95
+ "2904\n"
96
+ ]
97
+ }
98
+ ],
99
+ "source": [
100
+ "count = metadata[metadata['country'] == 'India'].shape[0]\n",
101
+ "print(count)"
102
+ ]
103
+ },
104
+ {
105
+ "cell_type": "code",
106
+ "execution_count": null,
107
+ "id": "a191e34c-b4fb-49d1-b774-aa19421abdc5",
108
+ "metadata": {},
109
+ "outputs": [],
110
+ "source": []
111
+ }
112
+ ],
113
+ "metadata": {
114
+ "kernelspec": {
115
+ "display_name": "Python 3 (ipykernel)",
116
+ "language": "python",
117
+ "name": "python3"
118
+ },
119
+ "language_info": {
120
+ "codemirror_mode": {
121
+ "name": "ipython",
122
+ "version": 3
123
+ },
124
+ "file_extension": ".py",
125
+ "mimetype": "text/x-python",
126
+ "name": "python",
127
+ "nbconvert_exporter": "python",
128
+ "pygments_lexer": "ipython3",
129
+ "version": "3.13.5"
130
+ }
131
+ },
132
+ "nbformat": 4,
133
+ "nbformat_minor": 5
134
+ }
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /snake-ai-api/requirements.txt
2
+ fastapi
3
+ uvicorn[standard]
4
+ onnxruntime
5
+ Pillow
6
+ pandas
7
+ numpy
8
+ scipy
9
+ torch
10
+ torchvision
11
+ google-genai
snake identification.ipynb ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "ea626626-3ef4-47a0-b171-d600b965f6e0",
7
+ "metadata": {},
8
+ "outputs": [
9
+ {
10
+ "ename": "ModuleNotFoundError",
11
+ "evalue": "No module named 'onnxruntime'",
12
+ "output_type": "error",
13
+ "traceback": [
14
+ "\u001b[31m---------------------------------------------------------------------------\u001b[39m",
15
+ "\u001b[31mModuleNotFoundError\u001b[39m Traceback (most recent call last)",
16
+ "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[1]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m \u001b[38;5;28;01mimport\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34;01monnxruntime\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;28;01mas\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34;01mort\u001b[39;00m\n\u001b[32m 2\u001b[39m \u001b[38;5;28;01mimport\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34;01mcv2\u001b[39;00m\n\u001b[32m 3\u001b[39m \u001b[38;5;28;01mimport\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34;01mnumpy\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;28;01mas\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34;01mnp\u001b[39;00m\n",
17
+ "\u001b[31mModuleNotFoundError\u001b[39m: No module named 'onnxruntime'"
18
+ ]
19
+ }
20
+ ],
21
+ "source": [
22
+ "import onnxruntime as ort\n",
23
+ "import cv2\n",
24
+ "import numpy as np\n",
25
+ "from scipy.special import softmax\n",
26
+ "import pandas as pd\n",
27
+ "from sklearn.preprocessing import LabelBinarizer\n",
28
+ "\n",
29
+ "# Load training metadata and LabelBinarizer\n",
30
+ "metadata_path = r\"C:\\Users\\General\\OneDrive\\Desktop\\SNAD\\train_metadata.csv\"\n",
31
+ "metadata = pd.read_csv(metadata_path)\n",
32
+ "\n",
33
+ "labels_species = metadata['binomial']\n",
34
+ "lb_species = LabelBinarizer()\n",
35
+ "lb_species.fit(np.asarray(labels_species))\n",
36
+ "\n",
37
+ "# Load ONNX model\n",
38
+ "model_path = r\"C:\\Users\\General\\OneDrive\\Desktop\\SNAD\\ViT_PreProcessing-ops11-preprocessing-int-dynam_graph.onnx\"\n",
39
+ "ort_session = ort.InferenceSession(model_path)\n"
40
+ ]
41
+ },
42
+ {
43
+ "cell_type": "code",
44
+ "execution_count": null,
45
+ "id": "fe22d4c8-e484-4e41-90f9-cc0d99f3f30b",
46
+ "metadata": {},
47
+ "outputs": [
48
+ {
49
+ "name": "stdout",
50
+ "output_type": "stream",
51
+ "text": [
52
+ "Predicted class ID: 475\n",
53
+ "Predicted species name: Nerodia erythrogaster\n"
54
+ ]
55
+ }
56
+ ],
57
+ "source": [
58
+ "# Prediction function\n",
59
+ "def predict_image_int32(image_path, ort_session, lb_species, height=384, width=384):\n",
60
+ " \"\"\"\n",
61
+ " Predict species from a single image using ONNX ViT that expects int32 input.\n",
62
+ " \"\"\"\n",
63
+ " # Load image\n",
64
+ " image = cv2.imread(image_path)\n",
65
+ " if image is None:\n",
66
+ " raise FileNotFoundError(f\"Image not found: {image_path}\")\n",
67
+ " \n",
68
+ " # Convert BGR to RGB\n",
69
+ " image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n",
70
+ " \n",
71
+ " # Resize\n",
72
+ " image = cv2.resize(image, (width, height))\n",
73
+ " \n",
74
+ " # Convert to int32 (required by your model)\n",
75
+ " image = image.astype(np.int32)\n",
76
+ " \n",
77
+ " # Run ONNX inference\n",
78
+ " outputs = ort_session.run(None, {ort_session.get_inputs()[0].name: image})\n",
79
+ " # print(outputs)\n",
80
+ " logits = outputs[0] # shape: (772,)\n",
81
+ " \n",
82
+ " # Softmax to get probabilities\n",
83
+ " probs = softmax(logits)\n",
84
+ " pred_class = np.argmax(probs)\n",
85
+ " species_name = lb_species.classes_[pred_class]\n",
86
+ " \n",
87
+ " return pred_class, species_name\n",
88
+ "\n",
89
+ "# Test single image\n",
90
+ "image_path = r\"C:\\Users\\General\\OneDrive\\Desktop\\SNAD\\test_image.png\"\n",
91
+ "pred_class, species_name = predict_image_int32(image_path, ort_session, lb_species)\n",
92
+ "\n",
93
+ "print(\"Predicted class ID:\", pred_class)\n",
94
+ "print(\"Predicted species name:\", species_name)\n"
95
+ ]
96
+ },
97
+ {
98
+ "cell_type": "code",
99
+ "execution_count": null,
100
+ "id": "76decffb-1fc3-49cd-ab11-d18c6ec1ea8e",
101
+ "metadata": {},
102
+ "outputs": [
103
+ {
104
+ "name": "stdout",
105
+ "output_type": "stream",
106
+ "text": [
107
+ "2904\n"
108
+ ]
109
+ }
110
+ ],
111
+ "source": [
112
+ "count = metadata[metadata['country'] == 'India'].shape[0]\n",
113
+ "print(count)"
114
+ ]
115
+ },
116
+ {
117
+ "cell_type": "code",
118
+ "execution_count": null,
119
+ "id": "a191e34c-b4fb-49d1-b774-aa19421abdc5",
120
+ "metadata": {},
121
+ "outputs": [],
122
+ "source": []
123
+ }
124
+ ],
125
+ "metadata": {
126
+ "kernelspec": {
127
+ "display_name": "Python 3",
128
+ "language": "python",
129
+ "name": "python3"
130
+ },
131
+ "language_info": {
132
+ "codemirror_mode": {
133
+ "name": "ipython",
134
+ "version": 3
135
+ },
136
+ "file_extension": ".py",
137
+ "mimetype": "text/x-python",
138
+ "name": "python",
139
+ "nbconvert_exporter": "python",
140
+ "pygments_lexer": "ipython3",
141
+ "version": "3.12.10"
142
+ }
143
+ },
144
+ "nbformat": 4,
145
+ "nbformat_minor": 5
146
+ }