{"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":30919,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"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\nimport pandas as pd","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-28T09:01:26.415499Z","iopub.execute_input":"2025-03-28T09:01:26.415931Z","iopub.status.idle":"2025-03-28T09:01:26.420441Z","shell.execute_reply.started":"2025-03-28T09:01:26.415902Z","shell.execute_reply":"2025-03-28T09:01:26.419544Z"}},"outputs":[],"execution_count":null},{"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-28T09:01:26.421491Z","iopub.execute_input":"2025-03-28T09:01:26.421712Z","iopub.status.idle":"2025-03-28T09:01:26.477847Z","shell.execute_reply.started":"2025-03-28T09:01:26.421693Z","shell.execute_reply":"2025-03-28T09:01:26.477138Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"data_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-28T09:01:26.479759Z","iopub.execute_input":"2025-03-28T09:01:26.479983Z","iopub.status.idle":"2025-03-28T09:01:26.483615Z","shell.execute_reply.started":"2025-03-28T09:01:26.479964Z","shell.execute_reply":"2025-03-28T09:01:26.482820Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport cv2\nimport matplotlib.pyplot as plt\n\n# Define your data directories (Update with actual paths)\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\n# Check if directories exist\nfor label, path in data_dirs.items():\n    if not os.path.exists(path):\n        print(f\"⚠ Warning: Directory {path} does not exist for {label}.\")\n    else:\n        print(f\"✅ Directory found: {path} ({label})\")\n\ndef show_sample_images():\n    valid_formats = ('.jpg', '.jpeg', '.png', '.bmp', '.tiff')  # Add more formats if needed\n\n    for label, dir_path in data_dirs.items():\n        if not os.path.exists(dir_path):\n            print(f\"⚠ Skipping {label}: Directory does not exist.\")\n            continue\n\n        # Load images\n        sample_images = []\n        for root, _, files in os.walk(dir_path):\n            for img_name in files:\n                img_path = os.path.join(root, img_name)\n                if img_path.lower().endswith(valid_formats):\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:  # Stop after 5 images\n                        break\n            if len(sample_images) == 5:\n                break\n\n        # Plot images\n        if sample_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        else:\n            print(f\"⚠ No valid images found in {dir_path} for {label}.\")\n\n# Call the function to display images\nshow_sample_images()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-28T09:01:26.484682Z","iopub.execute_input":"2025-03-28T09:01:26.484923Z","iopub.status.idle":"2025-03-28T09:01:46.137011Z","shell.execute_reply.started":"2025-03-28T09:01:26.484903Z","shell.execute_reply":"2025-03-28T09:01:46.136106Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 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-28T09:01:46.137962Z","iopub.execute_input":"2025-03-28T09:01:46.138246Z","iopub.status.idle":"2025-03-28T09:01:46.151813Z","shell.execute_reply.started":"2025-03-28T09:01:46.138220Z","shell.execute_reply":"2025-03-28T09:01:46.150933Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 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-28T09:01:46.152519Z","iopub.execute_input":"2025-03-28T09:01:46.152818Z","iopub.status.idle":"2025-03-28T09:01:46.169085Z","shell.execute_reply.started":"2025-03-28T09:01:46.152796Z","shell.execute_reply":"2025-03-28T09:01:46.168391Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport numpy as np\nimport cv2\nfrom sklearn.utils import shuffle\nfrom sklearn.model_selection import train_test_split\n\n# Define your data directories (Update with actual paths)\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\n# Function to load images\ndef load_images():\n    X = []  # Image data\n    Y = []  # Labels\n\n    valid_formats = ('.jpg', '.jpeg', '.png', '.bmp', '.tiff')  # Supported formats\n\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 for {label}. Skipping...\")\n            continue\n\n        # Read images from the directory\n        for img_name in os.listdir(dir_path):\n            img_path = os.path.join(dir_path, img_name)\n            if img_path.lower().endswith(valid_formats):\n                img = cv2.imread(img_path)\n                if img is not None:\n                    img = cv2.resize(img, (150, 150))  # Resize for consistency\n                    X.append(img)\n                    Y.append(label)  # Store label\n    \n    return X, Y\n\n# Load the dataset\nX, Y = load_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')  # Convert labels to indices\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)}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-28T09:01:46.170626Z","iopub.execute_input":"2025-03-28T09:01:46.170848Z","iopub.status.idle":"2025-03-28T09:02:52.862998Z","shell.execute_reply.started":"2025-03-28T09:01:46.170830Z","shell.execute_reply":"2025-03-28T09:02:52.862049Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\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-28T09:02:52.864235Z","iopub.execute_input":"2025-03-28T09:02:52.864594Z","iopub.status.idle":"2025-03-28T09:02:52.920649Z","shell.execute_reply.started":"2025-03-28T09:02:52.864545Z","shell.execute_reply":"2025-03-28T09:02:52.919941Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\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-28T09:02:52.921365Z","iopub.execute_input":"2025-03-28T09:02:52.921611Z","iopub.status.idle":"2025-03-28T09:03:06.640368Z","shell.execute_reply.started":"2025-03-28T09:02:52.921550Z","shell.execute_reply":"2025-03-28T09:03:06.639495Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\n\n# Make predictions on the test dataset\npredictions = model.predict(X_test)\npredicted_labels = np.argmax(predictions, axis=1)\n\n# Convert numerical labels back to species names\nlabel_mapping = {idx: species for idx, species in enumerate(data_dirs.keys())}\npredicted_species = [label_mapping[label] for label in predicted_labels]\n\n# Create a DataFrame to save results\noutput_df = pd.DataFrame({\n    \"Image_Index\": range(len(X_test)),\n    \"Predicted_Label\": predicted_labels,\n    \"Predicted_Species\": predicted_species\n})\n\n# Save the output file\noutput_file = \"animal_predictions.csv\"\noutput_df.to_csv(output_file, index=False)\n\nprint(f\"✅ Predictions saved to {output_file}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-28T09:03:06.641258Z","iopub.execute_input":"2025-03-28T09:03:06.641546Z","iopub.status.idle":"2025-03-28T09:03:08.228762Z","shell.execute_reply.started":"2025-03-28T09:03:06.641511Z","shell.execute_reply":"2025-03-28T09:03:08.227879Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}