{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":91451,"databundleVersionId":11223220,"sourceType":"competition"}],"dockerImageVersionId":30918,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"Published on March 07, 2025. By Prata, Marília (mpwolke)","metadata":{}},{"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\nimport cv2\nimport matplotlib.pyplot as plt\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":"2025-03-08T00:57:19.818726Z","iopub.execute_input":"2025-03-08T00:57:19.819381Z","iopub.status.idle":"2025-03-08T00:57:27.579340Z","shell.execute_reply.started":"2025-03-08T00:57:19.819347Z","shell.execute_reply":"2025-03-08T00:57:27.577794Z"},"collapsed":true,"jupyter":{"outputs_hidden":true},"_kg_hide-input":true,"_kg_hide-output":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"![](https://kaggle.com/competitions/91451/images/header)","metadata":{}},{"cell_type":"markdown","source":"### Dataset Description\n\n\"The objective of this competition is to develop a model capable of identifying individual animals from images. For pre-training, we provide a new large-scale dataset WildlifeReID-10k with 10k identities and around 140k images.\"\n\n\"For testing, we have curated a dataset consisting of never-seen data of three species: (i)🐢 loggerhead sea turtles (Zakynthos, Greece), (ii) 🦎 salamanders (Czech Republic), and (iii) 🐆 Eurasian lynxes (Czech Republic).\"\n\nhttps://www.kaggle.com/competitions/animal-clef-2025/data","metadata":{}},{"cell_type":"markdown","source":"## Competition Citation:\n\n@misc{animal-clef-2025,\n\n    author = {@inproceedings{vcermak2024wildlifedatasets,\n    \n  title={WildlifeDatasets: An open-source toolkit for animal re-identification},\n  \n  author={{\\v{C}}erm{\\'a}k, Vojt{\\v{e}}ch and Picek, Lukas and Adam, Luk{\\'a}{\\v{s}} and Papafitsoros, Kostas},","metadata":{}},{"cell_type":"code","source":"import tensorflow as tf\nfrom tqdm import tqdm\nfrom sklearn.utils import shuffle\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense\nfrom tensorflow.keras.optimizers import Adam","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-08T01:06:20.187066Z","iopub.execute_input":"2025-03-08T01:06:20.187498Z","iopub.status.idle":"2025-03-08T01:06:39.608947Z","shell.execute_reply.started":"2025-03-08T01:06:20.187467Z","shell.execute_reply":"2025-03-08T01:06:39.607728Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Load metadata csv file","metadata":{}},{"cell_type":"code","source":"df = pd.read_csv('../input/animal-clef-2025/metadata.csv')\ndf.tail()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-08T01:07:57.050273Z","iopub.execute_input":"2025-03-08T01:07:57.051110Z","iopub.status.idle":"2025-03-08T01:07:57.181056Z","shell.execute_reply.started":"2025-03-08T01:07:57.051070Z","shell.execute_reply":"2025-03-08T01:07:57.179820Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Directories \n\nSeaTurtle Directories range are t001-t610. So I wrote only t001 below.","metadata":{}},{"cell_type":"code","source":"#By Jocelyn Dumlao\n\n# Directories for each animal category\ndata_dirs = {    \n    \"SeaTurtlesD\": \"/kaggle/input/animal-clef-2025/images/SeaTurtleID2022/database/turtles-data/data/images/t001\",\n    \"SeaTurtlesQ\": \"/kaggle/input/animal-clef-2025/images/SeaTurtleID2022/query/images\",\n    \"LynxsD\": \"/kaggle/input/animal-clef-2025/images/LynxID2025/database\",\n    \"LynxsQ\": \"/kaggle/input/animal-clef-2025/images/LynxID2025/query\",\n    \"SalamandersD\": \"/kaggle/input/animal-clef-2025/images/SalamanderID2025/database/images\",\n    \"SalamandersQ\": \"/kaggle/input/animal-clef-2025/images/SalamanderID2025/query/images\"\n        \n}","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-08T01:42:09.006975Z","iopub.execute_input":"2025-03-08T01:42:09.007432Z","iopub.status.idle":"2025-03-08T01:42:09.013441Z","shell.execute_reply.started":"2025-03-08T01:42:09.007397Z","shell.execute_reply":"2025-03-08T01:42:09.011955Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#By Jocelyn Dumlao\n\n# Function to load and display images from each directory\ndef show_sample_images():\n    for label, dir_path in data_dirs.items():\n        if not os.path.exists(dir_path):\n            print(f\"Warning: Directory {dir_path} does not exist.\")\n            continue\n\n        # Load the first few images from the directory\n        sample_images = []\n        for root, _, files in os.walk(dir_path):\n            for img_name in files[:5]:  # Load 5 images for display\n                img_path = os.path.join(root, img_name)\n                if img_path.lower().endswith(('.JPG', '.jpg', '.jpeg')):\n                    img = cv2.imread(img_path)\n                    if img is not None:\n                        img = cv2.resize(img, (150, 150))\n                        sample_images.append(img)\n                    if len(sample_images) == 5:\n                        break\n            if len(sample_images) == 5:\n                break\n                \n        # Plot the images\n        plt.figure(figsize=(10, 10))\n        for i, img in enumerate(sample_images):\n            plt.subplot(1, 5, i + 1)\n            plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))\n            plt.axis('off')\n            plt.title(f\"{label}\")\n        plt.show()\n\n# Call the function to display images\nshow_sample_images()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-08T01:42:27.022171Z","iopub.execute_input":"2025-03-08T01:42:27.022657Z","iopub.status.idle":"2025-03-08T01:42:35.687822Z","shell.execute_reply.started":"2025-03-08T01:42:27.022598Z","shell.execute_reply":"2025-03-08T01:42:35.686547Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#By Jocelyn Dumlao\n\n# Set random seed for reproducibility\ntf.random.set_seed(42)\n\n# Directories for each bird category\ndata_dirs = {\n    \"SeaTurtlesD\": \"/kaggle/input/animal-clef-2025/images/SeaTurtleID2022/database/turtles-data/data/images/t001\",\n    \"SeaTurtlesQ\": \"/kaggle/input/animal-clef-2025/images/SeaTurtleID2022/query/images\",\n    \"LynxsD\": \"/kaggle/input/animal-clef-2025/images/LynxID2025/database\",\n    \"LynxsQ\": \"/kaggle/input/animal-clef-2025/images/LynxID2025/query\",\n    \"SalamandersD\": \"/kaggle/input/animal-clef-2025/images/SalamanderID2025/database/images\",\n    \"SalamandersQ\": \"/kaggle/input/animal-clef-2025/images/SalamanderID2025/query/images\"    \n}\n\nIMG_SIZE = 150\nX, Y = [], []","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-08T01:42:44.752470Z","iopub.execute_input":"2025-03-08T01:42:44.752892Z","iopub.status.idle":"2025-03-08T01:42:44.759280Z","shell.execute_reply.started":"2025-03-08T01:42:44.752860Z","shell.execute_reply":"2025-03-08T01:42:44.757697Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Images endswith different. ","metadata":{}},{"cell_type":"code","source":"#By Jocelyn Dumlao\n# Function to load images and labels\ndef load_images():\n    for label, dir_path in data_dirs.items():\n        if not os.path.exists(dir_path):\n            print(f\"Warning: Directory {dir_path} does not exist.\")\n            continue\n\n        for root, _, files in os.walk(dir_path):  # Walk through all subdirectories\n            for img_name in tqdm(files):\n                img_path = os.path.join(root, img_name)\n\n                # Ensure it's a valid image file\n                if not img_path.lower().endswith(('.JPG', '.jpg', '.jpeg')):\n                    print(f\"Skipping {img_path}, not a valid image file.\")\n                    continue\n\n                img = cv2.imread(img_path)\n                if img is None:\n                    print(f\"Warning: Could not read {img_path}. Skipping.\")\n                    continue  # Skip unreadable images\n\n                try:\n                    img = cv2.resize(img, (IMG_SIZE, IMG_SIZE))\n                    X.append(img)\n                    Y.append(label)\n                except Exception as e:\n                    print(f\"Error processing {img_path}: {e}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-08T01:43:09.554471Z","iopub.execute_input":"2025-03-08T01:43:09.554893Z","iopub.status.idle":"2025-03-08T01:43:09.562571Z","shell.execute_reply.started":"2025-03-08T01:43:09.554863Z","shell.execute_reply":"2025-03-08T01:43:09.561212Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Load images. train_test_split.","metadata":{}},{"cell_type":"code","source":"#By Jocelyn Dumlao\n\n# Load the dataset\nload_images()\n\n# Convert to numpy arrays\nif len(X) == 0 or len(Y) == 0 or len(X) != len(Y):\n    raise ValueError(f\"Mismatch in dataset sizes: X={len(X)}, Y={len(Y)}\")\n\nX = np.array(X, dtype='float32') / 255.0  # Normalize images\nY = np.array([list(data_dirs.keys()).index(y) for y in Y], dtype='int32')\n\n# Shuffle and split dataset\nX, Y = shuffle(X, Y, random_state=42)\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=42)\n\nprint(f\"Dataset successfully loaded: Train={len(X_train)}, Test={len(X_test)}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-08T01:43:18.765759Z","iopub.execute_input":"2025-03-08T01:43:18.766138Z","iopub.status.idle":"2025-03-08T01:45:47.022903Z","shell.execute_reply.started":"2025-03-08T01:43:18.766110Z","shell.execute_reply":"2025-03-08T01:45:47.021601Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Model","metadata":{}},{"cell_type":"code","source":"#By Jocelyn Dumlao\n\n# Model building\nmodel = Sequential([\n    Conv2D(32, (3, 3), activation='relu', input_shape=(IMG_SIZE, IMG_SIZE, 3)),\n    MaxPooling2D(2, 2),\n    Conv2D(64, (3, 3), activation='relu'),\n    MaxPooling2D(2, 2),\n    Flatten(),\n    Dense(128, activation='relu'),\n    Dense(len(data_dirs), activation='softmax')\n])\n\n# Compile the model\nmodel.compile(optimizer=Adam(), loss='sparse_categorical_crossentropy', metrics=['accuracy'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-08T01:46:50.089963Z","iopub.execute_input":"2025-03-08T01:46:50.090443Z","iopub.status.idle":"2025-03-08T01:46:50.305147Z","shell.execute_reply.started":"2025-03-08T01:46:50.090406Z","shell.execute_reply":"2025-03-08T01:46:50.303776Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Model history - Epochs","metadata":{}},{"cell_type":"code","source":"#By Jocelyn Dumlao\n\n# Train the model\nhistory = model.fit(X_train, Y_train, batch_size=32, epochs=2, validation_split=0.2) #Epochs=10\n\n# Plot training history\nplt.plot(history.history['accuracy'], label='train accuracy')\nplt.plot(history.history['val_accuracy'], label='val accuracy')\nplt.legend()\nplt.title(\"Model Accuracy\")\nplt.show()\n\n# Evaluate on test data\nloss, acc = model.evaluate(X_test, Y_test)\nprint(f\"Test Accuracy: {acc * 100:.2f}%\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-08T01:47:18.547384Z","iopub.execute_input":"2025-03-08T01:47:18.547823Z","execution_failed":"2025-03-08T01:48:06.224Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"#Acknowledgements:\n\nJocelyn Dumlao","metadata":{}}]}