{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":21154,"databundleVersionId":1243559,"sourceType":"competition"}],"dockerImageVersionId":31194,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-12-04T08:32:22.315233Z","iopub.execute_input":"2025-12-04T08:32:22.315462Z","iopub.status.idle":"2025-12-04T08:32:24.087189Z","shell.execute_reply.started":"2025-12-04T08:32:22.315443Z","shell.execute_reply":"2025-12-04T08:32:24.085595Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import sys, subprocess, os, re, warnings\nwarnings.filterwarnings(\"ignore\")\n\ntry:\n    subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"-q\", \"protobuf==3.20.3\"])\nexcept:\n    pass\n\nimport tensorflow as tf\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom kaggle_datasets import KaggleDatasets\nfrom sklearn.metrics import classification_report\n\nprint(\"TensorFlow Version:\", tf.__version__)\n\n# ============================================================\n# 1. STRATEGY — GPU ONLY (STABLE UNTUK T4)\n# ============================================================\nstrategy = tf.distribute.MirroredStrategy()\nprint(\">> GPU Detected, Using MirroredStrategy\")\n\n# ============================================================\n# 2. HYPERPARAMETERS\n# ============================================================\nIMAGE_SIZE = [128, 128]     # lebih optimal untuk CNN\nEPOCHS = 20                 # cukup untuk konvergensi\nBATCH_SIZE = 64 * strategy.num_replicas_in_sync\nLEARNING_RATE = 0.0008      \nCLASSES = 104\nAUTO = tf.data.AUTOTUNE\n\n# ============================================================\n# 3. LOAD DATASET PATH\n# ============================================================\ntry:\n    GCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')\nexcept:\n    GCS_DS_PATH = \"/kaggle/input/tpu-getting-started\"\n\nTRAIN_FILES = tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-192x192/train/*.tfrec')\nVAL_FILES   = tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-192x192/val/*.tfrec')\nTEST_FILES  = tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-192x192/test/*.tfrec')\n\ndef count_data_items(files):\n    return np.sum([int(re.search(r\"-(\\d+)\\.\", f).group(1)) for f in files])\n\nNUM_TRAIN = count_data_items(TRAIN_FILES)\nSTEPS_PER_EPOCH = NUM_TRAIN // BATCH_SIZE\nprint(\"Training Images:\", NUM_TRAIN)\n\n# ============================================================\n# 4. TFRecord Parsing\n# ============================================================\ndef decode_image(image_raw):\n    img = tf.image.decode_jpeg(image_raw, channels=3)\n    img = tf.image.resize(img, IMAGE_SIZE)\n    return tf.cast(img, tf.float32) / 255.0\n\ndef parse_train(example):\n    feature = {\n        \"image\": tf.io.FixedLenFeature([], tf.string),\n        \"class\": tf.io.FixedLenFeature([], tf.int64)\n    }\n    example = tf.io.parse_single_example(example, feature)\n    img = decode_image(example['image'])\n    label = example['class']\n    return img, label\n\ndef parse_test(example):\n    feature = {\n        \"image\": tf.io.FixedLenFeature([], tf.string),\n        \"id\": tf.io.FixedLenFeature([], tf.string)\n    }\n    example = tf.io.parse_single_example(example, feature)\n    img = decode_image(example['image'])\n    return img, example['id']\n\ndef augment(img, label):\n    img = tf.image.random_flip_left_right(img)\n    img = tf.image.random_saturation(img, 0.8, 1.2)\n    img = tf.image.random_brightness(img, 0.1)\n    return img, label\n\ndef load_dataset(files, labeled=True, augment_data=False):\n    ds = tf.data.TFRecordDataset(files, num_parallel_reads=AUTO)\n    ds = ds.map(parse_train if labeled else parse_test, num_parallel_calls=AUTO)\n    if labeled and augment_data:\n        ds = ds.map(augment, num_parallel_calls=AUTO)\n    return ds\n\ntrain_ds = (\n    load_dataset(TRAIN_FILES, labeled=True, augment_data=True)\n    .shuffle(2048)\n    .repeat()\n    .batch(BATCH_SIZE)\n    .prefetch(AUTO)\n)\n\nval_ds = (\n    load_dataset(VAL_FILES, labeled=True)\n    .batch(BATCH_SIZE)\n    .prefetch(AUTO)\n)\n\ntest_ds = (\n    load_dataset(TEST_FILES, labeled=False)\n    .batch(BATCH_SIZE)\n    .prefetch(AUTO)\n)\n\n# ============================================================\n# 5. MODEL — CNN (LEBIH SESUAI UNTUK CITRA)\n# ============================================================\nwith strategy.scope():\n    model = tf.keras.Sequential([\n        \n        tf.keras.layers.Conv2D(32, (3,3), activation='relu', padding='same',\n                               input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3)),\n        tf.keras.layers.MaxPooling2D(),\n        \n        tf.keras.layers.Conv2D(64, (3,3), activation='relu', padding='same'),\n        tf.keras.layers.MaxPooling2D(),\n        \n        tf.keras.layers.Conv2D(128, (3,3), activation='relu', padding='same'),\n        tf.keras.layers.MaxPooling2D(),\n        \n        tf.keras.layers.Conv2D(256, (3,3), activation='relu', padding='same'),\n        tf.keras.layers.GlobalAveragePooling2D(),\n        \n        tf.keras.layers.Dense(256, activation='relu'),\n        tf.keras.layers.Dropout(0.3),\n\n        tf.keras.layers.Dense(CLASSES, activation='softmax')\n    ])\n\n    model.compile(\n        optimizer=tf.keras.optimizers.Adam(learning_rate=LEARNING_RATE),\n        loss='sparse_categorical_crossentropy',\n        metrics=['accuracy']\n    )\n\nmodel.summary()\n\n# ============================================================\n# 6. TRAINING\n# ============================================================\ncallbacks = [\n    tf.keras.callbacks.EarlyStopping(\n        monitor='val_loss', patience=5, restore_best_weights=True),\n    tf.keras.callbacks.ReduceLROnPlateau(\n        monitor='val_loss', patience=3, factor=0.3, min_lr=1e-6)\n]\n\nhistory = model.fit(\n    train_ds,\n    steps_per_epoch=STEPS_PER_EPOCH,\n    epochs=EPOCHS,\n    validation_data=val_ds,\n    callbacks=callbacks,\n    verbose=1\n)\n\n# ============================================================\n# 7. PLOTTING\n# ============================================================\nplt.figure(figsize=(14,5))\nplt.subplot(1,2,1)\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title(\"Accuracy\")\nplt.legend([\"Train\", \"Validation\"])\n\nplt.subplot(1,2,2)\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title(\"Loss\")\nplt.legend([\"Train\", \"Validation\"])\nplt.show()\n\n# ============================================================\n# 8. EVALUATION — CLASSIFICATION REPORT\n# ============================================================\nval_labels = np.concatenate([y for x, y in val_ds], axis=0)\n\nval_probs = model.predict(val_ds, verbose=1)\nval_preds = np.argmax(val_probs, axis=1)\nprint(classification_report(val_labels, val_preds))\n\n# ============================================================\n# 9. SUBMISSION\n# ============================================================\nprint(\"Creating submission...\")\n\ntest_ids = np.concatenate([id for _, id in test_ds], axis=0)\ntest_probs = model.predict(test_ds, verbose=1)\ntest_preds = np.argmax(test_probs, axis=1)\n\nsubmission = pd.DataFrame({\n    'id': test_ids.astype(str),\n    'label': test_preds\n})\n\nsubmission.to_csv(\"submission.csv\", index=False)\nprint(\"DONE — submission.csv created!\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-04T08:32:31.854333Z","iopub.execute_input":"2025-12-04T08:32:31.854619Z","iopub.status.idle":"2025-12-04T08:36:37.380399Z","shell.execute_reply.started":"2025-12-04T08:32:31.854598Z","shell.execute_reply":"2025-12-04T08:36:37.379815Z"}},"outputs":[],"execution_count":null}]}