2026-05-22 14:23:45 +08:00
{
2026-06-11 15:17:32 +00:00
"cells": [
{
"cell_type": "markdown",
2026-06-11 16:31:38 +00:00
"metadata": {},
2026-06-11 15:17:32 +00:00
"source": [
2026-06-11 16:31:38 +00:00
"# ZeaVis Edu — Corn Leaf Disease Classifier\n",
"\n",
"Mengklasifikasikan penyakit daun jagung (Bercak Daun, Hawar Daun, Karat Daun, Daun Sehat) menggunakan EfficientNetV2B0 dengan transfer learning.\n",
"---"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1. Persiapan Lingkungan\n",
"\n",
"Mengimpor pustaka, mengatur seed, dan mengoptimalkan konfigurasi.\n",
"**Presisi float32** digunakan untuk komputasi.\n",
"Resolusi gambar: **224x224** (EfficientNetV2B0)."
2026-06-11 15:17:32 +00:00
]
2026-05-22 14:23:45 +08:00
},
2026-06-11 15:17:32 +00:00
{
"cell_type": "code",
2026-06-11 16:49:37 +00:00
"execution_count": 6,
2026-06-11 16:39:04 +00:00
"id": "94627f52",
2026-06-11 16:31:38 +00:00
"metadata": {},
2026-06-11 16:49:37 +00:00
"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: gdown in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from -r requirements.txt (line 3)) (6.1.0)\n",
"Requirement already satisfied: numpy in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from -r requirements.txt (line 4)) (2.1.3)\n",
"Requirement already satisfied: matplotlib in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from -r requirements.txt (line 5)) (3.10.9)\n",
"Requirement already satisfied: seaborn in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from -r requirements.txt (line 6)) (0.13.2)\n",
"Requirement already satisfied: pillow in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from -r requirements.txt (line 7)) (12.2.0)\n",
"Requirement already satisfied: split-folders in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from -r requirements.txt (line 8)) (0.6.1)\n",
"Requirement already satisfied: scikit-learn in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from -r requirements.txt (line 9)) (1.9.0)\n",
"Requirement already satisfied: tf2onnx in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from -r requirements.txt (line 10)) (1.17.0)\n",
"Requirement already satisfied: onnxruntime in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from -r requirements.txt (line 11)) (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",
"Requirement already satisfied: beautifulsoup4 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from gdown->-r requirements.txt (line 3)) (4.15.0)\n",
"Requirement already satisfied: filelock in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from gdown->-r requirements.txt (line 3)) (3.29.3)\n",
"Requirement already satisfied: tqdm in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from gdown->-r requirements.txt (line 3)) (4.68.2)\n",
"Requirement already satisfied: contourpy>=1.0.1 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from matplotlib->-r requirements.txt (line 5)) (1.3.3)\n",
"Requirement already satisfied: cycler>=0.10 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from matplotlib->-r requirements.txt (line 5)) (0.12.1)\n",
"Requirement already satisfied: fonttools>=4.22.0 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from matplotlib->-r requirements.txt (line 5)) (4.63.0)\n",
"Requirement already satisfied: kiwisolver>=1.3.1 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from matplotlib->-r requirements.txt (line 5)) (1.5.0)\n",
"Requirement already satisfied: pyparsing>=3 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from matplotlib->-r requirements.txt (line 5)) (3.3.2)\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 5)) (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 6)) (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 9)) (1.17.1)\n",
"Requirement already satisfied: joblib>=1.4.0 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from scikit-learn->-r requirements.txt (line 9)) (1.5.3)\n",
"Requirement already satisfied: narwhals>=2.0.1 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from scikit-learn->-r requirements.txt (line 9)) (2.22.1)\n",
"Requirement already satisfied: threadpoolctl>=3.5.0 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from scikit-learn->-r requirements.txt (line 9)) (3.6.0)\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 10)) (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: soupsieve>=1.6.1 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from beautifulsoup4->gdown->-r requirements.txt (line 3)) (2.8.4)\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",
"Requirement already satisfied: PySocks!=1.5.7,>=1.5.6 in /home/asephs/ZeaVis-Edu/.venv/lib/python3.12/site-packages (from requests[socks]->gdown->-r requirements.txt (line 3)) (1.7.1)\n"
]
}
],
2026-06-11 15:17:32 +00:00
"source": [
"!pip install -r requirements.txt"
]
},
{
"cell_type": "code",
2026-06-11 16:49:37 +00:00
"execution_count": 7,
2026-06-11 16:39:04 +00:00
"id": "bad56dcc",
2026-06-11 16:31:38 +00:00
"metadata": {},
2026-06-11 16:49:37 +00:00
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Running locally (TF 2.19.0, GPU: [PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')])\n",
"Setup OK. IMG=(224, 224), BATCH=32\n"
]
}
],
2026-06-11 15:17:32 +00:00
"source": [
2026-06-11 16:31:38 +00:00
"import os\n",
"import shutil\n",
"import zipfile\n",
"import random\n",
"from collections import Counter\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"import seaborn as sns\n",
"import splitfolders\n",
"from PIL import Image\n",
2026-06-11 15:17:32 +00:00
"\n",
2026-06-11 16:31:38 +00:00
"import tensorflow as tf\n",
"from tensorflow.keras import layers, models, callbacks\n",
"from tensorflow.keras.applications import EfficientNetV2B0\n",
"from tensorflow.keras.applications.efficientnet_v2 import preprocess_input\n",
"from tensorflow.keras.optimizers import AdamW\n",
"from sklearn.metrics import classification_report, confusion_matrix\n",
"from sklearn.utils.class_weight import compute_class_weight\n",
"\n",
"# Detect environment\n",
"try:\n",
" from google.colab import drive\n",
" IS_COLAB = True\n",
" print(\"Running on Google Colab\")\n",
"except ModuleNotFoundError:\n",
" IS_COLAB = False\n",
" print(f\"Running locally (TF {tf.__version__}, GPU: {tf.config.list_physical_devices('GPU')})\")\n",
"\n",
"tf.keras.mixed_precision.set_global_policy('float32')\n",
"\n",
"# Hyperparams\n",
"IMG_SIZE = (224, 224)\n",
"BATCH_SIZE = 32\n",
"SEED = 42\n",
"random.seed(SEED)\n",
"np.random.seed(SEED)\n",
"tf.random.set_seed(SEED)\n",
"\n",
"AUTOTUNE = tf.data.AUTOTUNE\n",
"print(f\"Setup OK. IMG={IMG_SIZE}, BATCH={BATCH_SIZE}\")"
]
},
{
"cell_type": "markdown",
2026-06-11 16:39:04 +00:00
"id": "83235964",
2026-06-11 16:31:38 +00:00
"metadata": {},
"source": [
"## 2. Download dan Ekstraksi Dataset"
]
},
{
"cell_type": "code",
2026-06-11 16:49:37 +00:00
"execution_count": 8,
2026-06-11 16:39:04 +00:00
"id": "c18354b4",
2026-06-11 16:31:38 +00:00
"metadata": {},
2026-06-11 16:49:37 +00:00
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Dataset ready.\n"
]
}
],
2026-06-11 16:31:38 +00:00
"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'\n",
"else:\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",
" DRIVE_FILE_ID = \"1s0H2lDOQVCixywk5eZXJz2i9jj4JihxJ\"\n",
" if not os.path.exists(archive_path):\n",
" print(\"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",
"\n",
"if 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 ready.\")"
]
},
{
"cell_type": "markdown",
2026-06-11 16:39:04 +00:00
"id": "5e19a255",
2026-06-11 16:31:38 +00:00
"metadata": {},
"source": [
"## 3. Data Cleaning dan Validasi Gambar (RGB)"
]
},
{
"cell_type": "code",
2026-06-11 16:49:37 +00:00
"execution_count": 9,
2026-06-11 16:39:04 +00:00
"id": "63ee82cc",
2026-06-11 16:31:38 +00:00
"metadata": {},
2026-06-11 16:49:37 +00:00
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Dataset path: /home/asephs/ZeaVis-Edu/Machine_Learning/dataset\n",
"Cleaning data...\n",
"Done. 0 problematic files removed.\n"
]
}
],
2026-06-11 16:31:38 +00:00
"source": [
2026-06-11 16:39:04 +00:00
"# --- Determine dataset path ---\n",
"# Colab: zip extracts to dataset/ with dataset_jagung_v1/ subfolder\n",
"# Local: zip extracts classes directly to dataset/\n",
2026-06-11 16:31:38 +00:00
"if IS_COLAB:\n",
" dataset_path = \"/content/dataset/dataset_jagung_v1\"\n",
"else:\n",
2026-06-11 16:39:04 +00:00
" candidate = os.path.join(extract_path, \"dataset_jagung_v1\")\n",
" if os.path.isdir(candidate):\n",
" dataset_path = candidate\n",
" else:\n",
" dataset_path = extract_path # classes are directly in dataset/\n",
"\n",
"print(f\"Dataset path: {dataset_path}\")\n",
2026-06-11 16:31:38 +00:00
"\n",
"def 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",
" img = Image.open(file_path)\n",
" if img.mode != 'RGB':\n",
" img = img.convert('RGB')\n",
" img.save(file_path)\n",
" except Exception:\n",
" print(f\"Removing: {file_path}\")\n",
" os.remove(file_path)\n",
" removed_count += 1\n",
" return removed_count\n",
"\n",
"print(\"Cleaning data...\")\n",
"removed = clean_image_data(dataset_path)\n",
"print(f\"Done. {removed} problematic files removed.\")"
]
},
{
"cell_type": "markdown",
2026-06-11 16:39:04 +00:00
"id": "c93f0a16",
2026-06-11 16:31:38 +00:00
"metadata": {},
"source": [
"## 4. Data Splitting (Train:Validation:Test = 70:15:15)"
]
},
{
"cell_type": "code",
2026-06-11 16:49:37 +00:00
"execution_count": 10,
2026-06-11 16:31:38 +00:00
"id": "35d34ff6",
"metadata": {},
2026-06-11 16:49:37 +00:00
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Splitting dataset 70:15:15...\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"Copying files: 6988 files [00:08, 826.32 files/s] "
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Done.\n",
"Train: 4890 | Val: 1046 | Test: 1052\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"\n"
]
}
],
2026-06-11 16:31:38 +00:00
"source": [
"if IS_COLAB:\n",
" output_dir = \"/content/dataset_split\"\n",
"else:\n",
" output_dir = os.path.join(os.getcwd(), \"dataset_split\")\n",
"\n",
"if os.path.exists(output_dir):\n",
" shutil.rmtree(output_dir)\n",
"\n",
"print(\"Splitting dataset 70:15:15...\")\n",
"splitfolders.ratio(dataset_path, output=output_dir,\n",
" seed=SEED, ratio=(0.7, 0.15, 0.15),\n",
" group_prefix=None, move=False)\n",
"print(\"Done.\")\n",
"\n",
"train_dir = os.path.join(output_dir, 'train')\n",
"val_dir = os.path.join(output_dir, 'val')\n",
"test_dir = os.path.join(output_dir, 'test')\n",
"\n",
"# Count\n",
"def count_images(path):\n",
" return sum(len(files) for _, _, files in os.walk(path))\n",
"\n",
"print(f'Train: {count_images(train_dir)} | Val: {count_images(val_dir)} | Test: {count_images(test_dir)}')"
]
},
{
"cell_type": "markdown",
2026-06-11 16:49:37 +00:00
"id": "a0ab36ff",
2026-06-11 16:31:38 +00:00
"metadata": {},
"source": [
"## 5. Data Loader dengan Augmentasi Lanjutan\n",
"\n",
"Menggunakan pipeline augmentasi berlapis:\n",
"- **Geometric**: RandomFlip, Rotation, Zoom, Translation, Contrast, Brightness\n",
"- **CutMix & MixUp**: mencampur dua gambar dan label (probabilitas 50% masing-masing)\n",
"- **RandomErasing**: menghapus area acak pada gambar\n",
"- **GaussianNoise** di dalam model (layer terpisah)\n",
"- **Class weights**: menangani ketidakseimbangan kelas (capped max 2.5)"
]
},
{
"cell_type": "code",
"execution_count": null,
2026-06-11 16:49:37 +00:00
"id": "36109306",
2026-06-11 16:31:38 +00:00
"metadata": {},
"outputs": [],
"source": [
"# --- Load datasets ---\n",
2026-06-11 15:17:32 +00:00
"train_ds = tf.keras.utils.image_dataset_from_directory(\n",
" train_dir, shuffle=True, batch_size=BATCH_SIZE, image_size=IMG_SIZE)\n",
"val_ds = tf.keras.utils.image_dataset_from_directory(\n",
" val_dir, shuffle=True, batch_size=BATCH_SIZE, image_size=IMG_SIZE)\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",
2026-06-11 16:31:38 +00:00
"print(f\"Classes ({NUM_CLASSES}): {class_names}\")\n",
2026-06-11 15:17:32 +00:00
"\n",
2026-06-11 16:31:38 +00:00
"# --- Helper: one-hot ---\n",
2026-06-11 15:17:32 +00:00
"def to_one_hot(image, label):\n",
" return image, tf.one_hot(label, NUM_CLASSES)\n",
"\n",
2026-06-11 16:31:38 +00:00
"# --- Beta distribution for MixUp/CutMix ---\n",
"def sample_beta_distribution(size, concentration_0=0.2, concentration_1=0.2):\n",
" gamma_1 = tf.random.gamma(shape=[size], alpha=concentration_1, dtype=tf.float32)\n",
" gamma_2 = tf.random.gamma(shape=[size], alpha=concentration_0, dtype=tf.float32)\n",
" return gamma_2 / (gamma_1 + gamma_2 + 1e-8)\n",
2026-06-11 15:17:32 +00:00
"\n",
2026-06-11 16:31:38 +00:00
"# --- MixUp ---\n",
"def mix_up(images, labels, alpha=0.2):\n",
" batch_size = tf.shape(images)[0]\n",
" lambda_param = sample_beta_distribution(batch_size, alpha, alpha)\n",
2026-06-11 16:49:37 +00:00
" lambda_param_img = tf.reshape(lambda_param, [batch_size, 1, 1, 1])\n",
2026-06-11 16:31:38 +00:00
" random_indices = tf.random.shuffle(tf.range(batch_size))\n",
2026-06-11 16:49:37 +00:00
" mixed_images = lambda_param_img * images + (1 - lambda_param_img) * tf.gather(images, random_indices)\n",
2026-06-11 16:31:38 +00:00
" labels = tf.cast(labels, tf.float32)\n",
2026-06-11 16:49:37 +00:00
" lambda_param_lbl = tf.reshape(lambda_param, [-1, 1])\n",
" mixed_labels = lambda_param_lbl * labels + (1 - lambda_param_lbl) * tf.gather(labels, random_indices)\n",
2026-06-11 16:31:38 +00:00
" return mixed_images, mixed_labels\n",
2026-06-11 15:17:32 +00:00
"\n",
2026-06-11 16:49:37 +00:00
"# --- CutMix (batch-level via coordinate-grid broadcasting) ---\n",
2026-06-11 16:31:38 +00:00
"def cut_mix(images, labels, alpha=0.2):\n",
" batch_size = tf.shape(images)[0]\n",
2026-06-11 16:49:37 +00:00
" h = tf.shape(images)[1]\n",
" w = tf.shape(images)[2]\n",
" \n",
" lambda_param = sample_beta_distribution(batch_size, alpha, alpha) # [B]\n",
2026-06-11 16:31:38 +00:00
" random_indices = tf.random.shuffle(tf.range(batch_size))\n",
2026-06-11 16:49:37 +00:00
" \n",
" # Per-sample cut sizes (in pixels)\n",
" cut_ratio = tf.sqrt(1.0 - lambda_param) # [B]\n",
" r_h = tf.cast(cut_ratio * tf.cast(h, tf.float32), tf.int32) # [B]\n",
" r_w = tf.cast(cut_ratio * tf.cast(w, tf.float32), tf.int32) # [B]\n",
" \n",
" # Per-sample random cut centres\n",
" cx = tf.random.uniform([batch_size], 0, w, tf.int32) # [B]\n",
" cy = tf.random.uniform([batch_size], 0, h, tf.int32) # [B]\n",
" \n",
" half_h = r_h // 2\n",
" half_w = r_w // 2\n",
" x1 = tf.clip_by_value(cx - half_w, 0, w) # [B]\n",
" x2 = tf.clip_by_value(cx + half_w, 0, w) # [B]\n",
" y1 = tf.clip_by_value(cy - half_h, 0, h) # [B]\n",
" y2 = tf.clip_by_value(cy + half_h, 0, h) # [B]\n",
" \n",
" # Build boolean cut mask via coordinate broadcasting\n",
" col_idx = tf.range(w, dtype=tf.int32) # [W]\n",
" row_idx = tf.range(h, dtype=tf.int32) # [H]\n",
" \n",
" in_x = tf.logical_and(\n",
" tf.reshape(col_idx, [1, 1, w]) >= tf.reshape(x1, [batch_size, 1, 1]),\n",
" tf.reshape(col_idx, [1, 1, w]) < tf.reshape(x2, [batch_size, 1, 1])\n",
" ) # [B, 1, W]\n",
" in_y = tf.logical_and(\n",
" tf.reshape(row_idx, [1, h, 1]) >= tf.reshape(y1, [batch_size, 1, 1]),\n",
" tf.reshape(row_idx, [1, h, 1]) < tf.reshape(y2, [batch_size, 1, 1])\n",
" ) # [B, H, 1]\n",
" \n",
" cut_mask = tf.cast(tf.logical_and(in_y, in_x), tf.float32) # [B, H, W]\n",
" cut_mask = tf.expand_dims(cut_mask, -1) # [B, H, W, 1]\n",
" \n",
" # Mix images\n",
" shuffled = tf.gather(images, random_indices)\n",
" mixed_images = (1.0 - cut_mask) * images + cut_mask * shuffled\n",
" \n",
" # Mix labels\n",
2026-06-11 16:31:38 +00:00
" labels = tf.cast(labels, tf.float32)\n",
" lambda_reshaped = tf.reshape(lambda_param, [-1, 1])\n",
2026-06-11 16:49:37 +00:00
" mixed_labels = lambda_reshaped * labels + (1.0 - lambda_reshaped) * tf.gather(labels, random_indices)\n",
" \n",
2026-06-11 16:31:38 +00:00
" return mixed_images, mixed_labels\n",
"\n",
"# --- RandomErasing ---\n",
"def random_erasing(images, probability=0.5, scale=(0.02, 0.33), ratio=(0.3, 3.3)):\n",
" batch_size = tf.shape(images)[0]\n",
2026-06-11 16:49:37 +00:00
" h = tf.shape(images)[1]\n",
" w = tf.shape(images)[2]\n",
" \n",
2026-06-11 16:31:38 +00:00
" target_area = tf.random.uniform([], scale[0], scale[1]) * tf.cast(h * w, tf.float32)\n",
" aspect_ratio = tf.random.uniform([], ratio[0], ratio[1])\n",
2026-06-11 16:49:37 +00:00
" erasing_h = tf.cast(tf.math.sqrt(target_area / aspect_ratio), tf.int32)\n",
" erasing_w = tf.cast(tf.math.sqrt(target_area * aspect_ratio), tf.int32)\n",
2026-06-11 16:31:38 +00:00
" erasing_h = tf.clip_by_value(erasing_h, 1, h - 1)\n",
" erasing_w = tf.clip_by_value(erasing_w, 1, w - 1)\n",
2026-06-11 16:49:37 +00:00
" \n",
2026-06-11 16:31:38 +00:00
" cx = tf.random.uniform([], 0, w - erasing_w, tf.int32)\n",
" cy = tf.random.uniform([], 0, h - erasing_h, tf.int32)\n",
2026-06-11 16:49:37 +00:00
" \n",
" # Build erase mask via coordinate broadcasting (same pattern as CutMix)\n",
" col_idx = tf.range(w, dtype=tf.int32)\n",
" row_idx = tf.range(h, dtype=tf.int32)\n",
" \n",
" in_x = tf.logical_and(col_idx >= cx, col_idx < cx + erasing_w) # [W]\n",
" in_y = tf.logical_and(row_idx >= cy, row_idx < cy + erasing_h) # [H]\n",
" erase_mask = tf.cast(tf.expand_dims(in_y, 1) & tf.expand_dims(in_x, 0), tf.float32) # [H, W]\n",
" erase_mask = tf.expand_dims(erase_mask, 0) # [1, H, W]\n",
" erase_mask = tf.expand_dims(erase_mask, -1) # [1, H, W, 1]\n",
" \n",
" noise = tf.random.uniform([batch_size, erasing_h, erasing_w, 3], 0.0, 255.0, dtype=tf.float32)\n",
" \n",
" # Pad the noise patch to full image size\n",
" paddings = [[0, 0], [cy, h - (cy + erasing_h)], [cx, w - (cx + erasing_w)], [0, 0]]\n",
" noise_padded = tf.pad(noise, paddings, constant_values=0.0)\n",
" \n",
" erased = images * (1.0 - erase_mask) + noise_padded * erase_mask\n",
" return tf.cond(\n",
" tf.random.uniform([]) < probability,\n",
" lambda: erased,\n",
" lambda: images\n",
" )\n",
2026-06-11 16:31:38 +00:00
"\n",
"# --- Geometric augmentation (kept for TTA compatibility) ---\n",
2026-06-11 15:17:32 +00:00
"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",
2026-06-11 16:31:38 +00:00
"], name=\"data_augmentation\")\n",
"\n",
"# --- Augment + MixUp/CutMix + RandomErasing pipeline ---\n",
"def augment_and_mix(images, labels):\n",
" # images are uint8 [0,255], labels are int\n",
" # 1. Geometric augmentation\n",
" images = data_augmentation(images, training=True)\n",
" # 2. Convert to float32 for MixUp/CutMix\n",
" images = tf.cast(images, tf.float32)\n",
" # 3. Apply CutMix or MixUp with 50% probability\n",
" choice = tf.random.uniform([])\n",
" labels_onehot = tf.one_hot(labels, NUM_CLASSES)\n",
" images, labels_onehot = tf.cond(\n",
" choice < 0.3, # 30% MixUp\n",
" lambda: mix_up(images, labels_onehot),\n",
" lambda: tf.cond(\n",
" choice < 0.6, # 30% CutMix\n",
" lambda: cut_mix(images, labels_onehot),\n",
" lambda: (images, labels_onehot) # 40% no mix\n",
" )\n",
" )\n",
" # 4. Random Erasing\n",
" images = random_erasing(images, probability=0.25)\n",
" return images, labels_onehot\n",
"\n",
"# --- Preprocessing (EfficientNetV2: [-1,1]) ---\n",
"def preprocess_fn(image, label):\n",
" return preprocess_input(image), label\n",
"\n",
"# --- Class Weights ---\n",
"train_class_counts = Counter()\n",
"for cn in class_names:\n",
" p = os.path.join(train_dir, cn)\n",
" if os.path.exists(p):\n",
" train_class_counts[cn] = len(os.listdir(p))\n",
"\n",
"y_integer = []\n",
"for i, cn in enumerate(class_names):\n",
" y_integer.extend([i] * train_class_counts[cn])\n",
"\n",
"class_weights_array = compute_class_weight('balanced', classes=np.unique(y_integer), y=y_integer)\n",
"class_weights_capped = [min(w, 2.5) for w in class_weights_array]\n",
"class_weights_tensor = tf.constant(class_weights_capped, dtype=tf.float32)\n",
"\n",
"def add_sample_weight(image, label):\n",
" class_indices = tf.argmax(label, axis=-1)\n",
" sample_weights = tf.gather(class_weights_tensor, class_indices)\n",
" return image, label, sample_weights\n",
"\n",
"print(\"Class weights (capped at 2.5):\")\n",
"for i, cn in enumerate(class_names):\n",
" print(f\" {cn}: {class_weights_capped[i]:.4f}\")\n",
"\n",
"# --- Build pipelines ---\n",
"# Train: augment → mix → erase → preprocess → onehot → sample_weight → prefetch\n",
"train_ds = (train_ds\n",
" .map(augment_and_mix, num_parallel_calls=AUTOTUNE)\n",
" .map(preprocess_fn, num_parallel_calls=AUTOTUNE)\n",
" .map(add_sample_weight, num_parallel_calls=AUTOTUNE)\n",
" .prefetch(AUTOTUNE))\n",
"\n",
"# Val/Test: preprocess → onehot → prefetch\n",
"val_ds = (val_ds\n",
" .map(lambda img, lbl: (preprocess_input(tf.cast(img, tf.float32)), lbl), num_parallel_calls=AUTOTUNE)\n",
" .map(to_one_hot, num_parallel_calls=AUTOTUNE)\n",
" .prefetch(AUTOTUNE))\n",
"\n",
"test_ds = (test_ds\n",
" .map(lambda img, lbl: (preprocess_input(tf.cast(img, tf.float32)), lbl), num_parallel_calls=AUTOTUNE)\n",
" .map(to_one_hot, num_parallel_calls=AUTOTUNE)\n",
" .prefetch(AUTOTUNE))\n",
"\n",
"print(\"Data pipelines ready.\")"
2026-06-11 15:17:32 +00:00
]
},
{
"cell_type": "markdown",
2026-06-11 16:31:38 +00:00
"metadata": {},
2026-06-11 15:17:32 +00:00
"source": [
2026-06-11 16:31:38 +00:00
"## 6. Visualisasi Sampel Data (dengan Augmentasi)"
2026-06-11 15:17:32 +00:00
]
},
{
"cell_type": "code",
"execution_count": null,
2026-06-11 16:31:38 +00:00
"metadata": {},
2026-06-11 15:17:32 +00:00
"outputs": [],
"source": [
2026-06-11 16:31:38 +00:00
"# Visualisasi augmentasi (non-preprocessed)\n",
"vis_ds = tf.keras.utils.image_dataset_from_directory(\n",
" train_dir, shuffle=True, batch_size=BATCH_SIZE, image_size=IMG_SIZE)\n",
"\n",
"plt.figure(figsize=(16, 10))\n",
"for images, labels in vis_ds.take(1):\n",
" # Original (4)\n",
2026-06-11 15:17:32 +00:00
" for i in range(4):\n",
2026-06-11 16:31:38 +00:00
" plt.subplot(3, 4, i + 1)\n",
2026-06-11 15:17:32 +00:00
" plt.imshow(images[i].numpy().astype(\"uint8\"))\n",
2026-06-11 16:31:38 +00:00
" plt.title(f\"Asli: {class_names[labels[i].numpy()]}\", fontsize=11)\n",
2026-06-11 15:17:32 +00:00
" plt.axis(\"off\")\n",
2026-06-11 16:31:38 +00:00
" # Augmented (4) — geometric only\n",
" aug = data_augmentation(images, training=True)\n",
2026-06-11 15:17:32 +00:00
" for i in range(4):\n",
2026-06-11 16:31:38 +00:00
" plt.subplot(3, 4, i + 5)\n",
" plt.imshow(aug[i].numpy().astype(\"uint8\"))\n",
" plt.title(f\"Aug: {class_names[labels[i].numpy()]}\", fontsize=11)\n",
2026-06-11 15:17:32 +00:00
" plt.axis(\"off\")\n",
2026-06-11 16:31:38 +00:00
" # MixUp/CutMix result (4)\n",
" aug_f = tf.cast(images, tf.float32)\n",
" mixed, _ = mix_up(aug_f, tf.one_hot(labels, NUM_CLASSES))\n",
" for i in range(4):\n",
" plt.subplot(3, 4, i + 9)\n",
" plt.imshow(tf.clip_by_value(mixed[i], 0, 255).numpy().astype(\"uint8\"))\n",
" plt.title(\"MixUp/CutMix\", fontsize=11)\n",
" plt.axis(\"off\")\n",
"\n",
"plt.suptitle(\"Contoh Augmentasi Berlapis\", fontsize=16)\n",
2026-06-11 15:17:32 +00:00
"plt.tight_layout()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
2026-06-11 16:31:38 +00:00
"metadata": {},
2026-06-11 15:17:32 +00:00
"source": [
2026-06-11 16:31:38 +00:00
"## 7. Arsitektur Model CNN (EfficientNetV2B0)\n",
"\n",
"Base model **EfficientNetV2B0** (imagenet, frozen) + Conv2D tambahan + BatchNorm + Dropout + Dense.\n",
"Ditambah **GaussianNoise(0.1)** untuk regularisasi tambahan."
2026-06-11 15:17:32 +00:00
]
},
{
"cell_type": "code",
"execution_count": null,
2026-06-11 16:31:38 +00:00
"metadata": {},
2026-06-11 15:17:32 +00:00
"outputs": [],
2026-06-11 16:31:38 +00:00
"source": [
"def build_model(num_classes):\n",
" base_model = EfficientNetV2B0(\n",
" input_shape=IMG_SIZE + (3,),\n",
" include_top=False,\n",
" weights='imagenet',\n",
" )\n",
" base_model.trainable = False\n",
"\n",
" inputs = tf.keras.Input(shape=IMG_SIZE + (3,))\n",
" x = layers.GaussianNoise(0.1)(inputs)\n",
" x = base_model(x, training=False)\n",
" x = layers.Conv2D(512, (3, 3), padding='same', activation='swish')(x)\n",
" x = layers.BatchNormalization()(x)\n",
" x = layers.MaxPooling2D((2, 2))(x)\n",
" x = layers.Dropout(0.2)(x)\n",
" x = layers.Conv2D(256, (3, 3), padding='same', activation='swish')(x)\n",
" x = layers.BatchNormalization()(x)\n",
" x = layers.GlobalAveragePooling2D()(x)\n",
" x = layers.Dropout(0.3)(x)\n",
" x = layers.Dense(1024, activation='swish')(x)\n",
" x = layers.BatchNormalization()(x)\n",
" x = layers.Dropout(0.4)(x)\n",
" outputs = layers.Dense(num_classes, activation='softmax', dtype='float32')(x)\n",
" return models.Model(inputs, outputs), base_model\n",
"\n",
"if IS_COLAB:\n",
" ckpt_dir = '/content/best_model'\n",
"else:\n",
" ckpt_dir = os.path.join(os.getcwd(), 'best_model')\n",
"checkpoint_path = os.path.join(ckpt_dir, 'best_model.keras')\n",
"\n",
"if os.path.exists(checkpoint_path):\n",
" print(f\"Loading checkpoint: {checkpoint_path}\")\n",
" try:\n",
" model = models.load_model(checkpoint_path, compile=False)\n",
" except Exception as e:\n",
" print(f\"Load failed: {e}. Building fresh.\")\n",
" model, base_model = build_model(NUM_CLASSES)\n",
"else:\n",
" print(\"No checkpoint. Building fresh model.\")\n",
" model, base_model = build_model(NUM_CLASSES)\n",
"\n",
"os.makedirs(ckpt_dir, exist_ok=True)\n",
"model.summary()"
]
2026-06-11 15:17:32 +00:00
},
{
"cell_type": "markdown",
2026-06-11 16:31:38 +00:00
"metadata": {},
2026-06-11 15:17:32 +00:00
"source": [
2026-06-11 16:31:38 +00:00
"## 8. Callbacks\n",
"\n",
"- **ModelCheckpoint**: simpan yang terbaik (val_accuracy)\n",
"- **EarlyStopping**: patience 15 (lebih panjang untuk fine-tuning)\n",
"- **ReduceLROnPlateau**: faktor 0.2, patience 5, min 1e-8\n",
"- **CSVLogger**: riwayat training"
2026-06-11 15:17:32 +00:00
]
},
{
"cell_type": "code",
"execution_count": null,
2026-06-11 16:31:38 +00:00
"metadata": {},
2026-06-11 15:17:32 +00:00
"outputs": [],
"source": [
2026-06-11 16:31:38 +00:00
"log_dir = \"logs/fit/\" + time.strftime(\"%Y%m%d-%H%M%S\")\n",
"import time\n",
"\n",
2026-06-11 15:17:32 +00:00
"checkpoint_cb = callbacks.ModelCheckpoint(\n",
2026-06-11 16:31:38 +00:00
" checkpoint_path,\n",
2026-06-11 15:17:32 +00:00
" save_best_only=True,\n",
2026-06-11 16:31:38 +00:00
" monitor=\"val_accuracy\",\n",
" mode=\"max\",\n",
" verbose=1\n",
2026-06-11 15:17:32 +00:00
")\n",
"\n",
"early_stopping_cb = callbacks.EarlyStopping(\n",
2026-06-11 16:31:38 +00:00
" monitor=\"val_accuracy\",\n",
" patience=15,\n",
2026-06-11 15:17:32 +00:00
" restore_best_weights=True,\n",
2026-06-11 16:31:38 +00:00
" mode=\"max\",\n",
" verbose=1\n",
2026-06-11 15:17:32 +00:00
")\n",
"\n",
"reduce_lr_cb = callbacks.ReduceLROnPlateau(\n",
" monitor='val_loss',\n",
" factor=0.2,\n",
2026-06-11 16:31:38 +00:00
" patience=5,\n",
" min_lr=1e-8,\n",
2026-06-11 15:17:32 +00:00
" verbose=1,\n",
" mode=\"min\"\n",
")\n",
"\n",
2026-06-11 16:31:38 +00:00
"csv_logger = callbacks.CSVLogger(os.path.join(ckpt_dir, 'training_log.csv'))\n",
"\n",
"callbacks_list = [checkpoint_cb, early_stopping_cb, reduce_lr_cb, csv_logger]"
2026-06-11 15:17:32 +00:00
]
},
{
"cell_type": "markdown",
2026-06-11 16:31:38 +00:00
"metadata": {},
2026-06-11 15:17:32 +00:00
"source": [
2026-06-11 16:31:38 +00:00
"## 9. Pelatihan Fase 1 — Head Only\n",
"\n",
"Optimizer **AdamW** dengan EMA (Exponential Moving Average) dan **Label Smoothing** 0.2.\n",
"Base model beku, hanya head yang dilatih."
2026-06-11 15:17:32 +00:00
]
},
{
"cell_type": "code",
"execution_count": null,
2026-06-11 16:31:38 +00:00
"metadata": {},
2026-06-11 15:17:32 +00:00
"outputs": [],
"source": [
"model.compile(\n",
2026-06-11 16:31:38 +00:00
" optimizer=AdamW(use_ema=True, ema_momentum=0.999,\n",
" learning_rate=1e-3, weight_decay=1e-4),\n",
" loss=tf.keras.losses.CategoricalCrossentropy(label_smoothing=0.2),\n",
" metrics=['accuracy']\n",
2026-06-11 15:17:32 +00:00
")\n",
"\n",
2026-06-11 16:31:38 +00:00
"print(\"Fase 1: Head training (base frozen)...\")\n",
2026-06-11 15:17:32 +00:00
"history_1 = model.fit(\n",
" train_ds,\n",
" validation_data=val_ds,\n",
2026-06-11 16:31:38 +00:00
" epochs=30,\n",
2026-06-11 15:17:32 +00:00
" callbacks=callbacks_list\n",
")"
]
},
{
"cell_type": "markdown",
2026-06-11 16:31:38 +00:00
"metadata": {},
2026-06-11 15:17:32 +00:00
"source": [
2026-06-11 16:31:38 +00:00
"## 10. Fine-tuning Fase 2 — Unfreeze Layer Atas\n",
"\n",
"Membuka **100 layer teratas** base model. Learning rate diturunkan ke 1e-4."
2026-06-11 15:17:32 +00:00
]
},
{
"cell_type": "code",
"execution_count": null,
2026-06-11 16:31:38 +00:00
"metadata": {},
2026-06-11 15:17:32 +00:00
"outputs": [],
"source": [
2026-06-11 16:31:38 +00:00
"base_model = model.layers[1] # layer[0]=GaussianNoise, layer[1]=EfficientNetV2B0\n",
"base_model.trainable = True\n",
"for layer in base_model.layers[:-100]:\n",
" layer.trainable = False\n",
2026-06-11 15:17:32 +00:00
"\n",
2026-06-11 16:31:38 +00:00
"model.compile(\n",
" optimizer=AdamW(use_ema=True, ema_momentum=0.999,\n",
" learning_rate=1e-4, weight_decay=1e-4),\n",
" loss=tf.keras.losses.CategoricalCrossentropy(label_smoothing=0.2),\n",
" metrics=['accuracy']\n",
")\n",
2026-06-11 15:17:32 +00:00
"\n",
2026-06-11 16:31:38 +00:00
"print(\"Fase 2: Fine-tuning top 100 layers...\")\n",
"history_2 = model.fit(\n",
" train_ds,\n",
" validation_data=val_ds,\n",
" epochs=60,\n",
" initial_epoch=history_1.epoch[-1] + 1,\n",
" callbacks=callbacks_list\n",
")"
2026-06-11 15:17:32 +00:00
]
},
{
"cell_type": "markdown",
2026-06-11 16:31:38 +00:00
"metadata": {},
2026-06-11 15:17:32 +00:00
"source": [
2026-06-11 16:31:38 +00:00
"## 11. Fine-tuning Fase 3 — Full Unfreeze\n",
"\n",
"Membuka **semua layer** base model. Learning rate 5e-5 (sangat kecil agar tidak merusak bobot pretrained)."
2026-06-11 15:17:32 +00:00
]
},
{
"cell_type": "code",
"execution_count": null,
2026-06-11 16:31:38 +00:00
"metadata": {},
2026-06-11 15:17:32 +00:00
"outputs": [],
"source": [
2026-06-11 16:31:38 +00:00
"base_model.trainable = True\n",
"\n",
"model.compile(\n",
" optimizer=AdamW(use_ema=True, ema_momentum=0.999,\n",
" learning_rate=5e-5, weight_decay=1e-4),\n",
" loss=tf.keras.losses.CategoricalCrossentropy(label_smoothing=0.2),\n",
" metrics=['accuracy']\n",
")\n",
"\n",
"print(\"Fase 3: Full fine-tuning...\")\n",
"history_3 = model.fit(\n",
" train_ds,\n",
" validation_data=val_ds,\n",
" epochs=90,\n",
" initial_epoch=history_2.epoch[-1] + 1,\n",
" callbacks=callbacks_list\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 12. Plot Akurasi dan Loss (Gabungan Semua Fase)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Gabungkan history\n",
"acc = history_1.history['accuracy'] + history_2.history['accuracy'] + history_3.history['accuracy']\n",
"val_acc = history_1.history['val_accuracy'] + history_2.history['val_accuracy'] + history_3.history['val_accuracy']\n",
"loss = history_1.history['loss'] + history_2.history['loss'] + history_3.history['loss']\n",
"val_loss = history_1.history['val_loss'] + history_2.history['val_loss'] + history_3.history['val_loss']\n",
"\n",
"# Batas antar fase\n",
"boundary_1 = len(history_1.history['accuracy']) - 1\n",
"boundary_2 = boundary_1 + len(history_2.history['accuracy'])\n",
"\n",
"plt.figure(figsize=(16, 6))\n",
"\n",
"plt.subplot(1, 2, 1)\n",
"plt.plot(acc, label='Training Accuracy', linewidth=2)\n",
"plt.plot(val_acc, label='Validation Accuracy', linewidth=2)\n",
"plt.axvline(x=boundary_1, color='gray', linestyle='--', alpha=0.7, label='Fase 2 start')\n",
"plt.axvline(x=boundary_2, color='black', linestyle='--', alpha=0.7, label='Fase 3 start')\n",
"plt.legend(fontsize=12)\n",
"plt.title('Training & Validation Accuracy', fontsize=14)\n",
"plt.xlabel('Epoch')\n",
"plt.ylabel('Accuracy')\n",
"plt.grid(alpha=0.3)\n",
"\n",
"plt.subplot(1, 2, 2)\n",
"plt.plot(loss, label='Training Loss', linewidth=2)\n",
"plt.plot(val_loss, label='Validation Loss', linewidth=2)\n",
"plt.axvline(x=boundary_1, color='gray', linestyle='--', alpha=0.7, label='Fase 2 start')\n",
"plt.axvline(x=boundary_2, color='black', linestyle='--', alpha=0.7, label='Fase 3 start')\n",
"plt.legend(fontsize=12)\n",
"plt.title('Training & Validation Loss', fontsize=14)\n",
"plt.xlabel('Epoch')\n",
"plt.ylabel('Loss')\n",
"plt.grid(alpha=0.3)\n",
"\n",
"plt.tight_layout()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 13. Test Time Augmentation (TTA)\n",
"\n",
"Menggunakan model terbaik (EMA) dan menerapkan augmentasi geometrik saat inferensi untuk meningkatkan akurasi."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Load model terbaik\n",
"print(f\"Loading best model from {checkpoint_path}...\")\n",
"best_model = tf.keras.models.load_model(checkpoint_path, compile=False)\n",
"\n",
"# Kumpulkan gambar test asli\n",
"raw_test_ds = tf.keras.utils.image_dataset_from_directory(\n",
" test_dir, shuffle=False, batch_size=BATCH_SIZE, image_size=IMG_SIZE)\n",
2026-06-11 15:17:32 +00:00
"\n",
"test_images = []\n",
2026-06-11 16:31:38 +00:00
"test_labels_true_raw = []\n",
"for images, labels in raw_test_ds.unbatch():\n",
2026-06-11 15:17:32 +00:00
" test_images.append(images.numpy())\n",
2026-06-11 16:31:38 +00:00
" test_labels_true_raw.append(labels.numpy())\n",
2026-06-11 15:17:32 +00:00
"\n",
"test_images = np.array(test_images)\n",
2026-06-11 16:31:38 +00:00
"test_labels_true = tf.one_hot(np.array(test_labels_true_raw), NUM_CLASSES).numpy()\n",
2026-06-11 15:17:32 +00:00
"\n",
"TTA_STEPS = 5\n",
"tta_predictions = []\n",
"\n",
"for i in range(TTA_STEPS):\n",
" aug_images = data_augmentation(test_images, training=True)\n",
2026-06-11 16:31:38 +00:00
" aug_images = preprocess_input(aug_images)\n",
" preds = best_model.predict(aug_images, batch_size=BATCH_SIZE, verbose=0)\n",
2026-06-11 15:17:32 +00:00
" tta_predictions.append(preds)\n",
2026-06-11 16:31:38 +00:00
" print(f\" TTA step {i+1}/{TTA_STEPS}\")\n",
2026-06-11 15:17:32 +00:00
"\n",
2026-06-11 16:31:38 +00:00
"mean_tta = np.mean(tta_predictions, axis=0)\n",
2026-06-11 15:17:32 +00:00
"\n",
2026-06-11 16:31:38 +00:00
"test_preds = np.argmax(mean_tta, axis=1)\n",
"test_true = np.argmax(test_labels_true, axis=1)\n",
"tta_acc = np.mean(test_preds == test_true)\n",
2026-06-11 15:17:32 +00:00
"\n",
2026-06-11 16:31:38 +00:00
"print(f\"\\nTest Accuracy (TTA {TTA_STEPS}x): {tta_acc*100:.2f}%\")"
2026-06-11 15:17:32 +00:00
]
},
{
"cell_type": "markdown",
2026-06-11 16:31:38 +00:00
"metadata": {},
2026-06-11 15:17:32 +00:00
"source": [
2026-06-11 16:31:38 +00:00
"## 14. Evaluasi — Classification Report & Confusion Matrix"
2026-06-11 15:17:32 +00:00
]
},
{
"cell_type": "code",
"execution_count": null,
2026-06-11 16:31:38 +00:00
"metadata": {},
2026-06-11 15:17:32 +00:00
"outputs": [],
2026-06-11 16:31:38 +00:00
"source": [
"print(\"\\nClassification Report:\\n\")\n",
"print(classification_report(test_true, test_preds, target_names=class_names))\n",
"\n",
"cm = confusion_matrix(test_true, test_preds)\n",
"plt.figure(figsize=(10, 8))\n",
"sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',\n",
" xticklabels=class_names, yticklabels=class_names)\n",
"plt.title('Confusion Matrix', fontsize=14)\n",
"plt.xlabel('Predicted', fontsize=12)\n",
"plt.ylabel('True', fontsize=12)\n",
"plt.tight_layout()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 15. Simpan Model Akhir"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Simpan model training final (dengan EMA weights)\n",
"final_path = os.path.join(ckpt_dir, 'best_model.keras')\n",
"model.save(final_path)\n",
"print(f\"Model saved to {final_path}\")\n",
"\n",
"# Simpan juga versi tanpa EMA untuk fallback\n",
"model.save(os.path.join(ckpt_dir, 'final_model.keras'))\n",
"print(\"Final model saved.\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 16. Export Model untuk Produksi\n",
"\n",
"Setelah training selesai, jalankan pipeline ekspor secara berurutan:\n",
"\n",
"### 1. SavedModel + TFLite\n",
"```bash\n",
"python save_model.py\n",
"```\n",
"Memuat `best_model/best_model.keras`, membangun arsitektur bersih (tanpa augmentasi), dan mengekspor ke:\n",
"- `model/saved_model/` — format produksi\n",
"- `model/model.tflite` — untuk perangkat mobile/edge\n",
"\n",
"### 2. ONNX (Rust ML Service)\n",
"```bash\n",
"python convert_onnx.py\n",
"```\n",
"Mengonversi SavedModel ke `model/model.onnx` untuk digunakan oleh Rust/Axum/ONNX Runtime.\n",
"\n",
"### 3. TensorFlow.js (Web)\n",
"```bash\n",
"export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python\n",
"tensorflowjs_converter --input_format=tf_saved_model --output_format=tfjs_graph_model --signature_name=serving_default --saved_model_tags=serve model/saved_model model/tfjs_model\n",
"```\n",
"\n",
"> **Catatan**: Pipeline ekspor terpisah dari notebook karena `save_model.py` membangun ulang arsitektur tanpa layer training (GaussianNoise, augmentasi) untuk produksi."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 17. Model Card — ZeaVis Edu Corn Disease Classifier\n",
"\n",
"| Atribut | Detail |\n",
"|---|---|\n",
"| **Nama Model** | ZeaVis Edu — EfficientNetV2B0 Classifier |\n",
"| **Versi** | 2.0 |\n",
"| **Arsitektur** | EfficientNetV2B0 (Transfer Learning) + GaussianNoise + Conv2D(512) + Conv2D(256) + Dense(1024) |\n",
"| **Framework** | TensorFlow 2.x / Keras (float32) |\n",
"| **Dataset** | ~6000-8000 gambar daun jagung (4 kelas) |\n",
"| **Kelas** | Bercak Daun, Hawar Daun, Karat Daun, Daun Sehat |\n",
"| **Input** | Gambar RGB 224× 224 piksel |\n",
"| **Output** | Probabilitas per kelas (softmax) |\n",
"| **Augmentasi** | Flip, Rotation, Zoom, Translation, Contrast, Brightness, MixUp, CutMix, RandomErasing, GaussianNoise |\n",
"| **Optimizer** | AdamW + EMA + Label Smoothing 0.2 |\n",
"| **Training** | 3 fase: Head (lr=1e-3) → Partial FT (lr=1e-4) → Full FT (lr=5e-5) |\n",
"| **Target Akurasi** | ≥95% test accuracy |\n",
"| **Cara Pakai** | Upload gambar daun jagung → model memprediksi kelas penyakit |\n",
"| **Etika** | Model ini hanya untuk tujuan edukasi/penelitian pertanian. Jangan gunakan sebagai satu-satunya alat diagnosis. Konsultasi dengan ahli pertanian tetap diperlukan. |\n",
"\n",
"---\n",
"\n",
"© ZeaVis Edu — Proyek klasifikasi penyakit daun jagung"
]
2026-06-11 15:17:32 +00:00
}
],
"metadata": {
"kernelspec": {
2026-06-11 16:39:04 +00:00
"display_name": ".venv",
2026-06-11 15:17:32 +00:00
"language": "python",
"name": "python3"
},
"language_info": {
2026-06-11 16:39:04 +00:00
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
2026-06-11 15:17:32 +00:00
"name": "python",
2026-06-11 16:39:04 +00:00
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.3"
2026-06-11 15:17:32 +00:00
}
},
"nbformat": 4,
2026-06-11 16:31:38 +00:00
"nbformat_minor": 5
}