{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceType":"competition","sourceId":127282,"databundleVersionId":15520105},{"sourceType":"kernelVersion","sourceId":315062333}],"dockerImageVersionId":31328,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# ==================================================\n# DISPLAY 15 TEST IMAGES IN A GRID (no predictions needed)\n# ==================================================\nimport matplotlib.pyplot as plt\nfrom pathlib import Path\nfrom PIL import Image\nimport random\n\n# Path to images directory\nimage_dir = Path(\"/kaggle/input/competitions/animal-clef-2026/images\")\n\n# Find all test images (inside any 'test' subfolder)\ntest_images = [p for p in image_dir.rglob(\"*\") if p.is_file() and \"/test/\" in str(p).lower()]\ntest_images = sorted(set(test_images))   # ensure unique\n\nprint(f\"Total test images found: {len(test_images)} (should be 2409)\")\n\n# Randomly select 15 images (or use first 15 if you prefer)\nif len(test_images) >= 15:\n    selected = random.sample(test_images, 15)   # random sample\nelse:\n    selected = test_images   # if less than 15, take all\n\n# Display in a 3x5 grid\nrows, cols = 3, 5\nfig, axes = plt.subplots(rows, cols, figsize=(15, 9))\n\nfor i, img_path in enumerate(selected):\n    row, col = i // cols, i % cols\n    try:\n        img = Image.open(img_path)\n        axes[row, col].imshow(img)\n        # Show the relative path or just filename as title\n        title = img_path.relative_to(image_dir).name[:20]   # just filename\n        axes[row, col].set_title(title, fontsize=8)\n    except Exception as e:\n        axes[row, col].text(0.5, 0.5, f\"Error\\n{img_path.name}\", ha='center', va='center')\n    axes[row, col].axis('off')\n\n# Hide any unused subplots (if less than 15)\nfor i in range(len(selected), rows*cols):\n    axes[i // cols, i % cols].axis('off')\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-29T15:26:44.757066Z","iopub.execute_input":"2026-04-29T15:26:44.757339Z","iopub.status.idle":"2026-04-29T15:27:09.639048Z","shell.execute_reply.started":"2026-04-29T15:26:44.757306Z","shell.execute_reply":"2026-04-29T15:27:09.638215Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ==================================================\n# CREATE SUBMISSION FILE (dummy predictions)\n# ==================================================\nimport pandas as pd\nfrom pathlib import Path\n\n# Path to images directory\nimage_dir = Path(\"/kaggle/input/competitions/animal-clef-2026/images\")\n\n# Find all test images (inside any 'test' subfolder)\ntest_images = [p for p in image_dir.rglob(\"*\") if p.is_file() and \"/test/\" in str(p).lower()]\ntest_images = sorted(set(test_images))\n\nprint(f\"Test images found: {len(test_images)} (expected 2409)\")\n\n# Create image_id as relative path from 'images/'\nimage_ids = [str(p.relative_to(image_dir)) for p in test_images]\n\n# Dummy predictions: all zeros (replace with your model's output)\ndummy_clusters = [0] * len(test_images)\n\n# Create DataFrame\nsubmission_df = pd.DataFrame({\n    'image_id': image_ids,\n    'cluster': dummy_clusters\n})\n\n# Save to CSV\nsubmission_df.to_csv(\"submission.csv\", index=False)\nprint(f\"\\n✅ submission.csv created with {len(submission_df)} rows.\")\nprint(submission_df.head())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-29T15:28:18.997143Z","iopub.execute_input":"2026-04-29T15:28:18.997922Z","iopub.status.idle":"2026-04-29T15:28:30.086894Z","shell.execute_reply.started":"2026-04-29T15:28:18.997887Z","shell.execute_reply":"2026-04-29T15:28:30.086138Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom pathlib import Path\nfrom PIL import Image\nimport math\n\n# ------------------------------\n# 1. Recursively find all images\n# ------------------------------\nimage_dir = Path(\"/kaggle/input/competitions/animal-clef-2026/images\")\nimage_paths = sorted(image_dir.rglob(\"*.[jJ][pP][gG]\")) + \\\n               sorted(image_dir.rglob(\"*.[jJ][pP][eE][gG]\")) + \\\n               sorted(image_dir.rglob(\"*.png\"))\n# Remove duplicates (if any) and keep only files\nimage_paths = [p for p in image_paths if p.is_file()]\n\nprint(f\"✅ Found {len(image_paths)} images\")\n\n# ------------------------------\n# 2. Display images in a grid\n# ------------------------------\ndef show_image_grid(image_paths, rows=3, cols=3, figsize=(12,12)):\n    n = rows * cols\n    plt.figure(figsize=figsize)\n    for i, img_path in enumerate(image_paths[:n]):\n        ax = plt.subplot(rows, cols, i+1)\n        try:\n            img = Image.open(img_path)\n            ax.imshow(img)\n            ax.set_title(img_path.stem[:20], fontsize=8)\n        except Exception as e:\n            ax.text(0.5, 0.5, f\"Error\\n{img_path.name}\", ha='center', va='center')\n        ax.axis('off')\n    plt.tight_layout()\n    plt.show()\n\n# Show first 9 images as a grid\nshow_image_grid(image_paths, rows=3, cols=3)\n\n# ------------------------------\n# 3. Create submission‑ready file\n# ------------------------------\n# Read the sample submission to get the expected column names and rows\nsample_sub = pd.read_csv(\"/kaggle/input/competitions/animal-clef-2026/sample_submission.csv\")\n\n# Extract image IDs from the image file names (adjust if your IDs are different)\n# Usually the 'image_id' column contains file names without extension.\n# We'll assume the submission expects one row per test image.\n# If you have a model, replace the placeholder with real predictions.\nimage_ids = [p.stem for p in image_paths]   # stem = filename without extension\n\n# Create a dummy prediction (e.g., \"Class_0\" or a constant)\n# You must change this to your actual model's output.\ndummy_predictions = [\"placeholder_class\"] * len(image_ids)\n\n# Create submission DataFrame\nsubmission = pd.DataFrame({\n    sample_sub.columns[0]: image_ids,      # assume first column is image ID\n    sample_sub.columns[1]: dummy_predictions\n})\n\n# Save to working directory\nsubmission.to_csv(\"submission.csv\", index=False)\nprint(\"✅ submission.csv created in working directory\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-28T13:30:32.782467Z","iopub.execute_input":"2026-04-28T13:30:32.782932Z","iopub.status.idle":"2026-04-28T13:31:48.135150Z","shell.execute_reply.started":"2026-04-28T13:30:32.782886Z","shell.execute_reply":"2026-04-28T13:31:48.133983Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom pathlib import Path\nfrom PIL import Image\nimport numpy as np\n\n# ------------------------------------------------------------\n# 1. Recursively find ALL images (train + test, any format)\n# ------------------------------------------------------------\nimage_dir = Path(\"/kaggle/input/competitions/animal-clef-2026/images\")\nimage_paths = list(image_dir.rglob(\"*.[jJ][pP][gG]\")) + \\\n              list(image_dir.rglob(\"*.[jJ][pP][eE][gG]\")) + \\\n              list(image_dir.rglob(\"*.png\")) + \\\n              list(image_dir.rglob(\"*.[jJ][pP][eE][gG]\"))  # redundant but safe\nimage_paths = list(set(image_paths))  # remove duplicates\nimage_paths.sort()                    # deterministic order\n\nprint(f\"✅ Total images found: {len(image_paths)}\")\n\n# ------------------------------------------------------------\n# 2. Display a grid of the first few images (up to 9)\n# ------------------------------------------------------------\ndef show_image_grid(img_paths, max_rows=3, max_cols=3, figsize=(12,12)):\n    n = min(len(img_paths), max_rows * max_cols)\n    if n == 0:\n        print(\"⚠️ No images to display.\")\n        return\n    rows = (n + max_cols - 1) // max_cols\n    cols = min(n, max_cols)\n    plt.figure(figsize=figsize)\n    for i, p in enumerate(img_paths[:n]):\n        ax = plt.subplot(rows, cols, i+1)\n        try:\n            img = Image.open(p)\n            ax.imshow(img)\n            ax.set_title(p.stem[:20], fontsize=8)\n        except Exception as e:\n            ax.text(0.5, 0.5, f\"Error\\n{p.name}\", ha='center', va='center')\n        ax.axis('off')\n    plt.tight_layout()\n    plt.show()\n\n# Show up to 9 images (will work even if fewer than 9)\nshow_image_grid(image_paths)\n\n# ------------------------------------------------------------\n# 3. Create submission CSV (only test images)\n# ------------------------------------------------------------\n# Load sample submission to get the exact column names and expected IDs\nsample_sub = pd.read_csv(\"/kaggle/input/competitions/animal-clef-2026/sample_submission.csv\")\nid_col = sample_sub.columns[0]        # usually 'id' or 'image_id'\npred_col = sample_sub.columns[1]      # usually 'class' or 'prediction'\n\n# Build a dictionary mapping image stem (filename without extension) to full path\nstem_to_path = {p.stem: p for p in image_paths}\n\n# Collect test images: use IDs from sample_sub that exist in our image set\ntest_ids = []\ntest_paths = []\nmissing_ids = []\nfor img_id in sample_sub[id_col]:\n    if img_id in stem_to_path:\n        test_ids.append(img_id)\n        test_paths.append(stem_to_path[img_id])\n    else:\n        missing_ids.append(img_id)\n\n# Warn about any missing test images (should not happen for a valid competition)\nif missing_ids:\n    print(f\"⚠️ Warning: {len(missing_ids)} image IDs from sample_submission not found in the image directory.\")\n    # Optionally, print first few missing IDs:\n    # print(\"Missing sample IDs:\", missing_ids[:5])\nelse:\n    print(\"✅ All sample submission IDs matched to image files.\")\n\n# ------------------------------------------------------------\n# 4. Generate dummy predictions (replace with your model!)\n# ------------------------------------------------------------\n# For a real submission, you would run inference on test_paths and get real class labels.\n# Here we use the first class name from the sample submission (or a constant '0').\n# If the sample submission has string class names, we take the first unique value.\ndummy_class = sample_sub[pred_col].iloc[0] if len(sample_sub) > 0 else \"placeholder\"\ndummy_predictions = [dummy_class] * len(test_ids)\n\n# ------------------------------------------------------------\n# 5. Save submission CSV\n# ------------------------------------------------------------\nsubmission_df = pd.DataFrame({\n    id_col: test_ids,\n    pred_col: dummy_predictions\n})\nsubmission_df.to_csv(\"submission.csv\", index=False)\nprint(\"✅ submission.csv successfully created in the working directory.\")\nprint(f\"   → Contains {len(submission_df)} rows (one per test image).\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-28T13:35:12.868733Z","iopub.execute_input":"2026-04-28T13:35:12.869256Z","iopub.status.idle":"2026-04-28T13:35:25.491042Z","shell.execute_reply.started":"2026-04-28T13:35:12.869222Z","shell.execute_reply":"2026-04-28T13:35:25.489818Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\nimport matplotlib.pyplot as plt\nfrom pathlib import Path\nfrom PIL import Image\n\n# ------------------------------------------------------------\n# 1. Find all test images (any file inside a 'test' folder)\n# ------------------------------------------------------------\nimage_dir = Path(\"/kaggle/input/competitions/animal-clef-2026/images\")\ntest_images = [p for p in image_dir.rglob(\"*\") if p.is_file() and \"/test/\" in str(p).lower()]\ntest_images = sorted(set(test_images))   # unique, sorted\n\nprint(f\"✅ Test images found: {len(test_images)}\")\n\n# ------------------------------------------------------------\n# 2. Display a grid of the first few test images (up to 9)\n# ------------------------------------------------------------\ndef show_grid(paths, max_images=9, cols=3, figsize=(12,12)):\n    n = min(len(paths), max_images)\n    if n == 0:\n        print(\"⚠️ No test images to display.\")\n        return\n    rows = (n + cols - 1) // cols\n    plt.figure(figsize=figsize)\n    for i, p in enumerate(paths[:n]):\n        ax = plt.subplot(rows, cols, i+1)\n        try:\n            img = Image.open(p)\n            ax.imshow(img)\n            rel_path = str(p.relative_to(image_dir))\n            ax.set_title(rel_path[:30], fontsize=8)\n        except Exception:\n            ax.text(0.5, 0.5, f\"Error\\n{p.name}\", ha='center', va='center')\n        ax.axis('off')\n    plt.tight_layout()\n    plt.show()\n\nshow_grid(test_images)\n\n# ------------------------------------------------------------\n# 3. Create submission DataFrame\n# ------------------------------------------------------------\n# Use the relative path from 'images/' as the image_id (e.g., \"LynxID2025/test/hash.jpg\")\nimage_ids = [str(p.relative_to(image_dir)) for p in test_images]\n\n# Dummy predictions: integer 0 for all rows (replace with your model output)\ndummy_clusters = [0] * len(test_images)\n\nsubmission_df = pd.DataFrame({\n    'image_id': image_ids,\n    'cluster': dummy_clusters\n})\n\n# ------------------------------------------------------------\n# 4. Save submission CSV\n# ------------------------------------------------------------\nsubmission_df.to_csv(\"submission.csv\", index=False)\nprint(f\"\\n✅ submission.csv created with {len(submission_df)} rows.\")\nprint(f\"📁 First 3 image_ids:\\n{submission_df['image_id'].head(3).tolist()}\")\nprint(\"\\n⚠️  Dummy predictions are all 0 – replace with your model's output before final submission.\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-28T13:40:53.209372Z","iopub.execute_input":"2026-04-28T13:40:53.209744Z","iopub.status.idle":"2026-04-28T13:40:57.339995Z","shell.execute_reply.started":"2026-04-28T13:40:53.209709Z","shell.execute_reply":"2026-04-28T13:40:57.338781Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\nimport matplotlib.pyplot as plt\nfrom pathlib import Path\nfrom PIL import Image\n\n# ------------------------------------------------------------\n# 1. Find all test images (inside any 'test' subfolder)\n# ------------------------------------------------------------\nimage_dir = Path(\"/kaggle/input/competitions/animal-clef-2026/images\")\ntest_images = [p for p in image_dir.rglob(\"*\") if p.is_file() and \"/test/\" in str(p).lower()]\ntest_images = sorted(set(test_images))   # unique, sorted\n\nprint(f\"✅ Test images found: {len(test_images)}\")\n\n# ------------------------------------------------------------\n# 2. Display a grid of the first few test images\n# ------------------------------------------------------------\ndef show_grid(paths, max_images=9, cols=3, figsize=(12,12)):\n    n = min(len(paths), max_images)\n    if n == 0:\n        print(\"⚠️ No test images to display.\")\n        return\n    rows = (n + cols - 1) // cols\n    plt.figure(figsize=figsize)\n    for i, p in enumerate(paths[:n]):\n        ax = plt.subplot(rows, cols, i+1)\n        try:\n            img = Image.open(p)\n            ax.imshow(img)\n            # Show the image ID (relative path from 'images/')\n            rel_path = str(p.relative_to(image_dir))\n            ax.set_title(rel_path[:30], fontsize=8)\n        except Exception:\n            ax.text(0.5, 0.5, f\"Error\\n{p.name}\", ha='center', va='center')\n        ax.axis('off')\n    plt.tight_layout()\n    plt.show()\n\nshow_grid(test_images)\n\n# ------------------------------------------------------------\n# 3. Create submission DataFrame\n# ------------------------------------------------------------\n# Use the relative path from 'images/' as the image_id (matching the competition's expected format)\nimage_ids = [str(p.relative_to(image_dir)) for p in test_images]\n\n# Dummy predictions: integer 0 for all rows (replace with your model output)\ndummy_predictions = [0] * len(test_images)\n\nsubmission_df = pd.DataFrame({\n    'image_id': image_ids,\n    'cluster': dummy_predictions\n})\n\n# ------------------------------------------------------------\n# 4. Save submission CSV\n# ------------------------------------------------------------\nsubmission_df.to_csv(\"submission.csv\", index=False)\nprint(f\"\\n✅ submission.csv created with {len(submission_df)} rows.\")\nprint(f\"📁 First few image_ids:\\n{submission_df['image_id'].head(3).tolist()}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-28T13:38:31.336899Z","iopub.execute_input":"2026-04-28T13:38:31.337266Z","iopub.status.idle":"2026-04-28T13:38:46.757606Z","shell.execute_reply.started":"2026-04-28T13:38:31.337238Z","shell.execute_reply":"2026-04-28T13:38:46.756737Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2026-04-28T11:59:03.214390Z","iopub.execute_input":"2026-04-28T11:59:03.214793Z","execution_failed":"2026-04-28T13:27:04.543Z"}},"outputs":[],"execution_count":null}]}