{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "fqNIt28_pKnS"
   },
   "source": [
    "1. Persiapan Lingkungan"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "id": "n6mBf6uO1VS6"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Requirement already satisfied: tensorflow==2.19.0 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from -r requirements.txt (line 1)) (2.19.0)\n",
      "Requirement already satisfied: tensorflowjs==4.22.0 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from -r requirements.txt (line 2)) (4.22.0)\n",
      "Requirement already satisfied: numpy in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from -r requirements.txt (line 3)) (2.1.3)\n",
      "Collecting matplotlib (from -r requirements.txt (line 4))\n",
      "  Using cached matplotlib-3.10.9-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl.metadata (52 kB)\n",
      "Collecting seaborn (from -r requirements.txt (line 5))\n",
      "  Using cached seaborn-0.13.2-py3-none-any.whl.metadata (5.4 kB)\n",
      "Collecting pillow (from -r requirements.txt (line 6))\n",
      "  Using cached pillow-12.2.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl.metadata (8.8 kB)\n",
      "Collecting split-folders (from -r requirements.txt (line 7))\n",
      "  Using cached split_folders-0.6.1-py3-none-any.whl.metadata (11 kB)\n",
      "Collecting scikit-learn (from -r requirements.txt (line 8))\n",
      "  Using cached scikit_learn-1.9.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl.metadata (11 kB)\n",
      "Requirement already satisfied: tf2onnx in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from -r requirements.txt (line 9)) (1.17.0)\n",
      "Requirement already satisfied: onnxruntime in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from -r requirements.txt (line 10)) (1.26.0)\n",
      "Requirement already satisfied: absl-py>=1.0.0 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from tensorflow==2.19.0->-r requirements.txt (line 1)) (2.4.0)\n",
      "Requirement already satisfied: astunparse>=1.6.0 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from tensorflow==2.19.0->-r requirements.txt (line 1)) (1.6.3)\n",
      "Requirement already satisfied: flatbuffers>=24.3.25 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from tensorflow==2.19.0->-r requirements.txt (line 1)) (25.12.19)\n",
      "Requirement already satisfied: gast!=0.5.0,!=0.5.1,!=0.5.2,>=0.2.1 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from tensorflow==2.19.0->-r requirements.txt (line 1)) (0.7.0)\n",
      "Requirement already satisfied: google-pasta>=0.1.1 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from tensorflow==2.19.0->-r requirements.txt (line 1)) (0.2.0)\n",
      "Requirement already satisfied: libclang>=13.0.0 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from tensorflow==2.19.0->-r requirements.txt (line 1)) (18.1.1)\n",
      "Requirement already satisfied: opt-einsum>=2.3.2 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from tensorflow==2.19.0->-r requirements.txt (line 1)) (3.4.0)\n",
      "Requirement already satisfied: packaging in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from tensorflow==2.19.0->-r requirements.txt (line 1)) (23.2)\n",
      "Requirement already satisfied: protobuf!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5,<6.0.0dev,>=3.20.3 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from tensorflow==2.19.0->-r requirements.txt (line 1)) (5.29.6)\n",
      "Requirement already satisfied: requests<3,>=2.21.0 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from tensorflow==2.19.0->-r requirements.txt (line 1)) (2.34.2)\n",
      "Requirement already satisfied: setuptools in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from tensorflow==2.19.0->-r requirements.txt (line 1)) (82.0.1)\n",
      "Requirement already satisfied: six>=1.12.0 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from tensorflow==2.19.0->-r requirements.txt (line 1)) (1.17.0)\n",
      "Requirement already satisfied: termcolor>=1.1.0 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from tensorflow==2.19.0->-r requirements.txt (line 1)) (3.3.0)\n",
      "Requirement already satisfied: typing-extensions>=3.6.6 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from tensorflow==2.19.0->-r requirements.txt (line 1)) (4.15.0)\n",
      "Requirement already satisfied: wrapt>=1.11.0 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from tensorflow==2.19.0->-r requirements.txt (line 1)) (2.2.1)\n",
      "Requirement already satisfied: grpcio<2.0,>=1.24.3 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from tensorflow==2.19.0->-r requirements.txt (line 1)) (1.81.1)\n",
      "Requirement already satisfied: tensorboard~=2.19.0 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from tensorflow==2.19.0->-r requirements.txt (line 1)) (2.19.0)\n",
      "Requirement already satisfied: keras>=3.5.0 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from tensorflow==2.19.0->-r requirements.txt (line 1)) (3.14.1)\n",
      "Requirement already satisfied: h5py>=3.11.0 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from tensorflow==2.19.0->-r requirements.txt (line 1)) (3.14.0)\n",
      "Requirement already satisfied: ml-dtypes<1.0.0,>=0.5.1 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from tensorflow==2.19.0->-r requirements.txt (line 1)) (0.5.4)\n",
      "Requirement already satisfied: flax>=0.7.2 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from tensorflowjs==4.22.0->-r requirements.txt (line 2)) (0.12.7)\n",
      "Requirement already satisfied: importlib_resources>=5.9.0 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from tensorflowjs==4.22.0->-r requirements.txt (line 2)) (7.1.0)\n",
      "Requirement already satisfied: jax>=0.4.13 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from tensorflowjs==4.22.0->-r requirements.txt (line 2)) (0.10.1)\n",
      "Requirement already satisfied: jaxlib>=0.4.13 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from tensorflowjs==4.22.0->-r requirements.txt (line 2)) (0.10.1)\n",
      "Requirement already satisfied: tf-keras>=2.13.0 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from tensorflowjs==4.22.0->-r requirements.txt (line 2)) (2.19.0)\n",
      "Requirement already satisfied: tensorflow-decision-forests>=1.5.0 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from tensorflowjs==4.22.0->-r requirements.txt (line 2)) (1.12.0)\n",
      "Requirement already satisfied: tensorflow-hub>=0.16.1 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from tensorflowjs==4.22.0->-r requirements.txt (line 2)) (0.16.1)\n",
      "Requirement already satisfied: charset_normalizer<4,>=2 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from requests<3,>=2.21.0->tensorflow==2.19.0->-r requirements.txt (line 1)) (3.4.7)\n",
      "Requirement already satisfied: idna<4,>=2.5 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from requests<3,>=2.21.0->tensorflow==2.19.0->-r requirements.txt (line 1)) (3.18)\n",
      "Requirement already satisfied: urllib3<3,>=1.26 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from requests<3,>=2.21.0->tensorflow==2.19.0->-r requirements.txt (line 1)) (2.7.0)\n",
      "Requirement already satisfied: certifi>=2023.5.7 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from requests<3,>=2.21.0->tensorflow==2.19.0->-r requirements.txt (line 1)) (2026.5.20)\n",
      "Requirement already satisfied: markdown>=2.6.8 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from tensorboard~=2.19.0->tensorflow==2.19.0->-r requirements.txt (line 1)) (3.10.2)\n",
      "Requirement already satisfied: tensorboard-data-server<0.8.0,>=0.7.0 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from tensorboard~=2.19.0->tensorflow==2.19.0->-r requirements.txt (line 1)) (0.7.2)\n",
      "Requirement already satisfied: werkzeug>=1.0.1 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from tensorboard~=2.19.0->tensorflow==2.19.0->-r requirements.txt (line 1)) (3.1.8)\n",
      "Collecting contourpy>=1.0.1 (from matplotlib->-r requirements.txt (line 4))\n",
      "  Using cached contourpy-1.3.3-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl.metadata (5.5 kB)\n",
      "Collecting cycler>=0.10 (from matplotlib->-r requirements.txt (line 4))\n",
      "  Using cached cycler-0.12.1-py3-none-any.whl.metadata (3.8 kB)\n",
      "Collecting fonttools>=4.22.0 (from matplotlib->-r requirements.txt (line 4))\n",
      "  Using cached fonttools-4.63.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl.metadata (118 kB)\n",
      "Collecting kiwisolver>=1.3.1 (from matplotlib->-r requirements.txt (line 4))\n",
      "  Using cached kiwisolver-1.5.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl.metadata (5.1 kB)\n",
      "Collecting pyparsing>=3 (from matplotlib->-r requirements.txt (line 4))\n",
      "  Using cached pyparsing-3.3.2-py3-none-any.whl.metadata (5.8 kB)\n",
      "Requirement already satisfied: python-dateutil>=2.7 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from matplotlib->-r requirements.txt (line 4)) (2.9.0.post0)\n",
      "Requirement already satisfied: pandas>=1.2 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from seaborn->-r requirements.txt (line 5)) (3.0.3)\n",
      "Requirement already satisfied: scipy>=1.10.0 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from scikit-learn->-r requirements.txt (line 8)) (1.17.1)\n",
      "Collecting joblib>=1.4.0 (from scikit-learn->-r requirements.txt (line 8))\n",
      "  Using cached joblib-1.5.3-py3-none-any.whl.metadata (5.5 kB)\n",
      "Collecting narwhals>=2.0.1 (from scikit-learn->-r requirements.txt (line 8))\n",
      "  Using cached narwhals-2.22.1-py3-none-any.whl.metadata (15 kB)\n",
      "Collecting threadpoolctl>=3.5.0 (from scikit-learn->-r requirements.txt (line 8))\n",
      "  Using cached threadpoolctl-3.6.0-py3-none-any.whl.metadata (13 kB)\n",
      "Requirement already satisfied: onnx>=1.14.0 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from tf2onnx->-r requirements.txt (line 9)) (1.21.0)\n",
      "Requirement already satisfied: wheel<1.0,>=0.23.0 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from astunparse>=1.6.0->tensorflow==2.19.0->-r requirements.txt (line 1)) (0.45.1)\n",
      "Requirement already satisfied: msgpack in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from flax>=0.7.2->tensorflowjs==4.22.0->-r requirements.txt (line 2)) (1.2.0)\n",
      "Requirement already satisfied: optax in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from flax>=0.7.2->tensorflowjs==4.22.0->-r requirements.txt (line 2)) (0.2.8)\n",
      "Requirement already satisfied: orbax-checkpoint in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from flax>=0.7.2->tensorflowjs==4.22.0->-r requirements.txt (line 2)) (0.12.0)\n",
      "Requirement already satisfied: tensorstore in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from flax>=0.7.2->tensorflowjs==4.22.0->-r requirements.txt (line 2)) (0.1.84)\n",
      "Requirement already satisfied: rich>=11.1 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from flax>=0.7.2->tensorflowjs==4.22.0->-r requirements.txt (line 2)) (15.0.0)\n",
      "Requirement already satisfied: PyYAML>=5.4.1 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from flax>=0.7.2->tensorflowjs==4.22.0->-r requirements.txt (line 2)) (6.0.3)\n",
      "Requirement already satisfied: treescope>=0.1.7 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from flax>=0.7.2->tensorflowjs==4.22.0->-r requirements.txt (line 2)) (0.1.10)\n",
      "Requirement already satisfied: namex in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from keras>=3.5.0->tensorflow==2.19.0->-r requirements.txt (line 1)) (0.1.0)\n",
      "Requirement already satisfied: optree in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from keras>=3.5.0->tensorflow==2.19.0->-r requirements.txt (line 1)) (0.19.1)\n",
      "Requirement already satisfied: markdown-it-py>=2.2.0 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from rich>=11.1->flax>=0.7.2->tensorflowjs==4.22.0->-r requirements.txt (line 2)) (4.2.0)\n",
      "Requirement already satisfied: pygments<3.0.0,>=2.13.0 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from rich>=11.1->flax>=0.7.2->tensorflowjs==4.22.0->-r requirements.txt (line 2)) (2.20.0)\n",
      "Requirement already satisfied: mdurl~=0.1 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from markdown-it-py>=2.2.0->rich>=11.1->flax>=0.7.2->tensorflowjs==4.22.0->-r requirements.txt (line 2)) (0.1.2)\n",
      "Requirement already satisfied: wurlitzer in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from tensorflow-decision-forests>=1.5.0->tensorflowjs==4.22.0->-r requirements.txt (line 2)) (3.1.1)\n",
      "Requirement already satisfied: ydf>=0.11.0 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from tensorflow-decision-forests>=1.5.0->tensorflowjs==4.22.0->-r requirements.txt (line 2)) (0.16.0)\n",
      "Requirement already satisfied: markupsafe>=2.1.1 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from werkzeug>=1.0.1->tensorboard~=2.19.0->tensorflow==2.19.0->-r requirements.txt (line 1)) (3.0.3)\n",
      "Requirement already satisfied: etils[epath,epy] in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from orbax-checkpoint->flax>=0.7.2->tensorflowjs==4.22.0->-r requirements.txt (line 2)) (1.14.0)\n",
      "Requirement already satisfied: prometheus-client>=0.20.0 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from orbax-checkpoint->flax>=0.7.2->tensorflowjs==4.22.0->-r requirements.txt (line 2)) (0.25.0)\n",
      "Requirement already satisfied: aiofiles in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from orbax-checkpoint->flax>=0.7.2->tensorflowjs==4.22.0->-r requirements.txt (line 2)) (25.1.0)\n",
      "Requirement already satisfied: humanize in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from orbax-checkpoint->flax>=0.7.2->tensorflowjs==4.22.0->-r requirements.txt (line 2)) (4.15.0)\n",
      "Requirement already satisfied: simplejson>=3.16.0 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from orbax-checkpoint->flax>=0.7.2->tensorflowjs==4.22.0->-r requirements.txt (line 2)) (4.1.1)\n",
      "Requirement already satisfied: psutil in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from orbax-checkpoint->flax>=0.7.2->tensorflowjs==4.22.0->-r requirements.txt (line 2)) (7.2.2)\n",
      "Requirement already satisfied: uvloop in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from orbax-checkpoint->flax>=0.7.2->tensorflowjs==4.22.0->-r requirements.txt (line 2)) (0.22.1)\n",
      "Requirement already satisfied: fsspec in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from etils[epath,epy]->orbax-checkpoint->flax>=0.7.2->tensorflowjs==4.22.0->-r requirements.txt (line 2)) (2026.4.0)\n",
      "Requirement already satisfied: zipp in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from etils[epath,epy]->orbax-checkpoint->flax>=0.7.2->tensorflowjs==4.22.0->-r requirements.txt (line 2)) (4.1.0)\n",
      "Using cached matplotlib-3.10.9-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl (8.8 MB)\n",
      "Using cached seaborn-0.13.2-py3-none-any.whl (294 kB)\n",
      "Using cached pillow-12.2.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl (7.1 MB)\n",
      "Using cached split_folders-0.6.1-py3-none-any.whl (13 kB)\n",
      "Using cached scikit_learn-1.9.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl (9.1 MB)\n",
      "Using cached contourpy-1.3.3-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl (362 kB)\n",
      "Using cached cycler-0.12.1-py3-none-any.whl (8.3 kB)\n",
      "Using cached fonttools-4.63.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl (5.0 MB)\n",
      "Using cached joblib-1.5.3-py3-none-any.whl (309 kB)\n",
      "Using cached kiwisolver-1.5.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl (1.5 MB)\n",
      "Using cached narwhals-2.22.1-py3-none-any.whl (454 kB)\n",
      "Using cached pyparsing-3.3.2-py3-none-any.whl (122 kB)\n",
      "Using cached threadpoolctl-3.6.0-py3-none-any.whl (18 kB)\n",
      "Installing collected packages: threadpoolctl, split-folders, pyparsing, pillow, narwhals, kiwisolver, joblib, fonttools, cycler, contourpy, scikit-learn, matplotlib, seaborn\n",
      "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m13/13\u001b[0m [seaborn]2/13\u001b[0m [seaborn]ib]n]\n",
      "\u001b[1A\u001b[2KSuccessfully installed contourpy-1.3.3 cycler-0.12.1 fonttools-4.63.0 joblib-1.5.3 kiwisolver-1.5.0 matplotlib-3.10.9 narwhals-2.22.1 pillow-12.2.0 pyparsing-3.3.2 scikit-learn-1.9.0 seaborn-0.13.2 split-folders-0.6.1 threadpoolctl-3.6.0\n"
     ]
    }
   ],
   "source": [
    "!pip install -r requirements.txt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "dNC9QMXh1mWq",
    "outputId": "132f1b20-f2b3-4acc-a0f5-7464e74ca613"
   },
   "outputs": [],
   "source": "import os\nimport shutil\nimport zipfile\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport splitfolders\nfrom PIL import Image\n\nimport tensorflow as tf\nfrom tensorflow.keras import layers, models, callbacks\nfrom tensorflow.keras.applications import EfficientNetV2B0\nfrom sklearn.metrics import classification_report, confusion_matrix, multilabel_confusion_matrix\n\n# Detect environment: Colab or local\ntry:\n    from google.colab import drive\n    IS_COLAB = True\n    print(\"✅ Running on Google Colab\")\nexcept ModuleNotFoundError:\n    IS_COLAB = False\n    print(f\"✅ Running locally (TF {tf.__version__}, GPU: {tf.config.list_physical_devices('GPU')})\")\n\nprint(f\"TensorFlow Version: {tf.__version__}\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "A6j2Vv8ypnrd"
   },
   "source": [
    "2. Download dan Ekstraksi Dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "bsGJEEFs7Flg",
    "outputId": "30228ce8-1b64-47f5-93f7-30632b2af1c5"
   },
   "outputs": [],
   "source": "if IS_COLAB:\n    drive.mount('/content/drive')\n    archive_path = '/content/drive/MyDrive/jagung/dataset_jagung.zip'\n    destination_path = '/content/dataset_jagung.zip'\n    extract_path = '/content/dataset'\nelse:\n    import gdown\n    base = os.getcwd()\n    archive_path = os.path.join(base, 'dataset_jagung.zip')\n    destination_path = archive_path\n    extract_path = os.path.join(base, 'dataset')\n    # If dataset doesn't exist locally, download from Google Drive\n    DRIVE_FILE_ID = \"1s0H2lDOQVCixywk5eZXJz2i9jj4JihxJ\"\n    if not os.path.exists(archive_path):\n        print(\"Dataset not found locally. Downloading from Google Drive...\")\n        try:\n            gdown.download(f\"https://drive.google.com/uc?id={DRIVE_FILE_ID}\", archive_path, quiet=False)\n        except Exception as e:\n            print(f\"Download failed: {e}\")\n\nif os.path.exists(destination_path):\n    if not os.path.exists(extract_path) or len(os.listdir(extract_path)) == 0:\n        os.makedirs(extract_path, exist_ok=True)\n        print(\"Extracting dataset...\")\n        try:\n            with zipfile.ZipFile(destination_path, 'r') as zip_ref:\n                zip_ref.extractall(path=extract_path)\n            print(\"Extraction completed!\")\n        except Exception as e:\n            print(f\"Extraction failed: {e}\")\n    else:\n        print(\"Dataset is already extracted and ready for use.\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "148LNQ7Ips01"
   },
   "source": [
    "4. Data Cleaning dan Validasi Gambat (RGB)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "bIPb9DIX1spd",
    "outputId": "422957b6-c1e7-4f65-8834-14673b50a70e"
   },
   "outputs": [],
   "source": "if IS_COLAB:\n    dataset_path = \"/content/dataset/dataset_jagung_v1\"\nelse:\n    dataset_path = os.path.join(extract_path, \"dataset_jagung_v1\")\n\ndef clean_image_data(directory):\n    removed_count = 0\n    for root, dirs, files in os.walk(directory):\n        for file in files:\n            file_path = os.path.join(root, file)\n            try:\n                img = Image.open(file_path)\n                img.verify()\n\n                img = Image.open(file_path)\n                if img.mode != 'RGB':\n                    img = img.convert('RGB')\n                    img.save(file_path)\n            except Exception as e:\n                print(f\"Removing corrupt/invalid file: {file_path}\")\n                os.remove(file_path)\n                removed_count += 1\n    return removed_count\n\nprint(\"Starting data cleanup process...\")\nremoved = clean_image_data(dataset_path)\nprint(f\"Cleanup completed. Total of {removed} problematic files removed.\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "YSQX48hTp3vW"
   },
   "source": [
    "5. Data Spliting (70/15/15/)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "8Zg2hJw4a3RJ",
    "outputId": "3daeef44-6e99-48d4-da8e-53f7f431a550"
   },
   "outputs": [],
   "source": "if IS_COLAB:\n    output_dir = \"/content/dataset_split\"\nelse:\n    output_dir = os.path.join(os.getcwd(), \"dataset_split\")\n\nif os.path.exists(output_dir):\n    shutil.rmtree(output_dir)\n\nprint(\"Splitting dataset into Train, Validation, and Test...\")\nsplitfolders.ratio(dataset_path, output=output_dir,\n                   seed=42, ratio=(0.7, 0.15, 0.15),\n                   group_prefix=None, move=False)\nprint(\"Dataset splitting completed.\")\n\ntrain_dir = os.path.join(output_dir, 'train')\nval_dir = os.path.join(output_dir, 'val')\ntest_dir = os.path.join(output_dir, 'test')"
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "F0q8ELD5qPAY"
   },
   "source": [
    "6. Data Loader dan Augmentasi"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "rNU4YGv61wFX",
    "outputId": "beda9f63-d52a-46dd-a28c-6d1ac17e7169"
   },
   "outputs": [],
   "source": [
    "BATCH_SIZE = 32\n",
    "IMG_SIZE = (224, 224)\n",
    "\n",
    "train_ds = tf.keras.utils.image_dataset_from_directory(\n",
    "    train_dir, shuffle=True, batch_size=BATCH_SIZE, image_size=IMG_SIZE)\n",
    "\n",
    "val_ds = tf.keras.utils.image_dataset_from_directory(\n",
    "    val_dir, shuffle=True, batch_size=BATCH_SIZE, image_size=IMG_SIZE)\n",
    "\n",
    "test_ds = tf.keras.utils.image_dataset_from_directory(\n",
    "    test_dir, shuffle=False, batch_size=BATCH_SIZE, image_size=IMG_SIZE)\n",
    "\n",
    "class_names = train_ds.class_names\n",
    "NUM_CLASSES = len(class_names)\n",
    "print(f\"Number of classes: {NUM_CLASSES}\")\n",
    "print(f\"Class names: {class_names}\")\n",
    "\n",
    "def to_one_hot(image, label):\n",
    "    return image, tf.one_hot(label, NUM_CLASSES)\n",
    "\n",
    "train_ds = train_ds.map(to_one_hot, num_parallel_calls=tf.data.AUTOTUNE)\n",
    "val_ds = val_ds.map(to_one_hot, num_parallel_calls=tf.data.AUTOTUNE)\n",
    "test_ds = test_ds.map(to_one_hot, num_parallel_calls=tf.data.AUTOTUNE)\n",
    "\n",
    "AUTOTUNE = tf.data.AUTOTUNE\n",
    "train_ds = train_ds.prefetch(buffer_size=AUTOTUNE)\n",
    "val_ds = val_ds.prefetch(buffer_size=AUTOTUNE)\n",
    "test_ds = test_ds.prefetch(buffer_size=AUTOTUNE)\n",
    "\n",
    "data_augmentation = tf.keras.Sequential([\n",
    "    layers.RandomFlip(\"horizontal_and_vertical\"),\n",
    "    layers.RandomRotation(0.2),\n",
    "    layers.RandomZoom(0.2),\n",
    "    layers.RandomTranslation(0.1, 0.1),\n",
    "    layers.RandomContrast(0.2),\n",
    "    layers.RandomBrightness(0.2)\n",
    "], name=\"data_augmentation\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "BwSHXm-WqXeE"
   },
   "source": [
    "7. Visualisasi Sample dan Hasil Augmentasi"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 610
    },
    "id": "tc8SYmZH3lGS",
    "outputId": "44f07316-12d9-41a7-8069-5b108a335a18"
   },
   "outputs": [],
   "source": [
    "plt.figure(figsize=(12, 6))\n",
    "for images, labels in train_ds.take(1):\n",
    "    for i in range(4):\n",
    "        ax = plt.subplot(2, 4, i + 1)\n",
    "        plt.imshow(images[i].numpy().astype(\"uint8\"))\n",
    "        orig_class_idx = np.argmax(labels[i].numpy())\n",
    "\n",
    "        plt.title(f\"Ori: {class_names[orig_class_idx]}\")\n",
    "        plt.axis(\"off\")\n",
    "\n",
    "    augmented_images = data_augmentation(images, training=True)\n",
    "    for i in range(4):\n",
    "        ax = plt.subplot(2, 4, i + 5)\n",
    "        plt.imshow(augmented_images[i].numpy().astype(\"uint8\"))\n",
    "        orig_class_idx = np.argmax(labels[i].numpy())\n",
    "\n",
    "        plt.title(f\"Aug: {class_names[orig_class_idx]}\")\n",
    "        plt.axis(\"off\")\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "vQefwIFlqhU0"
   },
   "source": [
    "8. Arsitektur Model CNN (EfficientNetv2B0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 737
    },
    "id": "iswHWuZb3pZj",
    "outputId": "a83c5bc3-e512-4e01-c359-0766daaa608c"
   },
   "outputs": [],
   "source": "if IS_COLAB:\n    checkpoint_path = '/content/best_model/best_model.keras'\nelse:\n    checkpoint_path = os.path.join(os.getcwd(), 'best_model', 'best_model.keras')\n\nif os.path.exists(checkpoint_path):\n    print(f\"Loading weights from model checkpoint: {checkpoint_path}...\")\n    try:\n        model = models.load_model(checkpoint_path)\n    except Exception as e:\n        print(f\"Failed to load checkpoint model: {e}.\")\n        model, base_model = build_model(NUM_CLASSES)\nelse:\n    print(\"No checkpoint found.\")\n    model, base_model = build_model(NUM_CLASSES)\n\nmodel.summary()"
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "yik1l5ngqt_1"
   },
   "source": [
    "9. Implementasi Callbacks"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "s4Trlvno3wny"
   },
   "outputs": [],
   "source": [
    "checkpoint_cb = callbacks.ModelCheckpoint(\n",
    "    \"best_model/best_model.keras\",\n",
    "    save_best_only=True,\n",
    "    monitor=\"val_loss\",\n",
    "    mode=\"min\"\n",
    ")\n",
    "\n",
    "early_stopping_cb = callbacks.EarlyStopping(\n",
    "    monitor=\"val_loss\",\n",
    "    patience=7,\n",
    "    restore_best_weights=True,\n",
    "    mode=\"min\"\n",
    ")\n",
    "\n",
    "reduce_lr_cb = callbacks.ReduceLROnPlateau(\n",
    "    monitor='val_loss',\n",
    "    factor=0.2,\n",
    "    patience=3,\n",
    "    min_lr=1e-6,\n",
    "    verbose=1,\n",
    "    mode=\"min\"\n",
    ")\n",
    "\n",
    "callbacks_list = [checkpoint_cb, early_stopping_cb, reduce_lr_cb]\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "UKyFNmVvqyHx"
   },
   "source": [
    "10. Training Model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "cq5rllO63zXA",
    "outputId": "0d3c03c8-d354-4b8b-befb-ecbb68b18735"
   },
   "outputs": [],
   "source": [
    "model.compile(\n",
    "    optimizer=tf.keras.optimizers.Adam(learning_rate=1e-3),\n",
    "    loss=tf.keras.losses.BinaryCrossentropy(),\n",
    "    metrics=[tf.keras.metrics.BinaryAccuracy(name='accuracy')]\n",
    ")\n",
    "\n",
    "print(\"Training...\")\n",
    "EPOCHS_PHASE_1 = 15\n",
    "\n",
    "history_1 = model.fit(\n",
    "    train_ds,\n",
    "    validation_data=val_ds,\n",
    "    epochs=EPOCHS_PHASE_1,\n",
    "    callbacks=callbacks_list\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "Fq0qppJ_rGDE"
   },
   "source": [
    "11. Plot History"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 545
    },
    "id": "wOW7f13UD4wy",
    "outputId": "eff4a3d7-9ddc-4992-da43-0ab09631e47d"
   },
   "outputs": [],
   "source": [
    "def plot_history(history_1, initial_epochs):\n",
    "    acc = history_1.history['accuracy']\n",
    "    val_acc = history_1.history['val_accuracy']\n",
    "    loss = history_1.history['loss']\n",
    "    val_loss = history_1.history['val_loss']\n",
    "\n",
    "    plt.figure(figsize=(16, 6))\n",
    "\n",
    "    plt.subplot(1, 2, 1)\n",
    "    plt.plot(acc, label='Training Accuracy')\n",
    "    plt.plot(val_acc, label='Validation Accuracy')\n",
    "    plt.legend(loc='lower right')\n",
    "    plt.title('Training and Validation Accuracy')\n",
    "\n",
    "    plt.subplot(1, 2, 2)\n",
    "    plt.plot(loss, label='Training Loss')\n",
    "    plt.plot(val_loss, label='Validation Loss')\n",
    "    plt.legend(loc='upper right')\n",
    "    plt.title('Training and Validation Loss')\n",
    "    plt.show()\n",
    "\n",
    "plot_history(history_1, EPOCHS_PHASE_1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "TxXzQ8ZrrmiS"
   },
   "source": [
    "12. Test Time Augmentation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "5vnDCrqLD5hT",
    "outputId": "b4e04c95-c570-4817-cf1f-37321560c89c"
   },
   "outputs": [],
   "source": [
    "print(\"Evaluating model using TTA (Test-Time Augmentation) for Multi-Label...\")\n",
    "\n",
    "test_images = []\n",
    "test_labels_true = []\n",
    "\n",
    "for images, labels in test_ds.unbatch():\n",
    "    test_images.append(images.numpy())\n",
    "    test_labels_true.append(labels.numpy())\n",
    "\n",
    "test_images = np.array(test_images)\n",
    "test_labels_true = np.array(test_labels_true)\n",
    "\n",
    "TTA_STEPS = 5\n",
    "tta_predictions = []\n",
    "\n",
    "for i in range(TTA_STEPS):\n",
    "    print(f\"TTA Step {i+1}/{TTA_STEPS}\")\n",
    "    aug_images = data_augmentation(test_images, training=True)\n",
    "    preds = model.predict(aug_images, batch_size=BATCH_SIZE, verbose=0)\n",
    "    tta_predictions.append(preds)\n",
    "\n",
    "mean_tta_preds = np.mean(tta_predictions, axis=0)\n",
    "\n",
    "THRESHOLD = 0.5\n",
    "test_preds_binary = (mean_tta_preds > THRESHOLD).astype(int)\n",
    "\n",
    "correct_predictions = np.equal(test_preds_binary, test_labels_true.astype(int))\n",
    "tta_accuracy = np.mean(correct_predictions)\n",
    "\n",
    "print(f\"\\nSubset Accuracy (Exact Match) on Test Set (with TTA): {np.mean(np.all(correct_predictions, axis=1)) * 100:.2f}%\")\n",
    "print(f\"Binary Accuracy (Per-Class Average) on Test Set (with TTA): {tta_accuracy * 100:.2f}%\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "y-ADQvPIr1Wo"
   },
   "source": [
    "13. Metrik Evaluasi"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 1000
    },
    "id": "4ea9-S50EtQ6",
    "outputId": "f1632cab-a233-4072-d0ec-70f141f83757"
   },
   "outputs": [],
   "source": "print(\"\\nClassification Report (Multi-Label):\\n\")\nprint(classification_report(test_labels_true, test_preds_binary, target_names=class_names))\n\nmcm = multilabel_confusion_matrix(test_labels_true, test_preds_binary)\n\nfig, axes = plt.subplots(2, 2, figsize=(12, 10))\naxes = axes.ravel()\n\nfor i, class_name in enumerate(class_names):\n    sns.heatmap(mcm[i], annot=True, fmt='d', cmap='Blues', ax=axes[i], cbar=False,\n                xticklabels=['Negative', 'Positive'], yticklabels=['Negative', 'Positive'])\n    axes[i].set_title(f'Confusion Matrix: {class_name}')\n    axes[i].set_xlabel('Predicted')\n    axes[i].set_ylabel('True')\n\nplt.tight_layout()\nplt.show()"
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "gpuType": "T4",
   "provenance": []
  },
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}