{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"tpuV5e8","dataSources":[{"sourceId":21154,"databundleVersionId":1243559,"sourceType":"competition"}],"dockerImageVersionId":31194,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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":{"execution_failed":"2025-12-02T08:29:57.209Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import tensorflow as tf\nfrom kaggle_datasets import KaggleDatasets\nimport numpy as np\n\nprint(\"TensorFlow version:\", tf.__version__)","metadata":{"trusted":true,"execution":{"execution_failed":"2025-12-02T08:29:57.208Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Detect hardware, return distribution strategy\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    print(\"Running on TPU:\", tpu.master())\nexcept ValueError:\n    tpu = None\n    print(\"No TPU found\")\n\nif tpu:\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    # versi baru: gunakan TPUStrategy (bukan experimental.TPUStrategy)\n    strategy = tf.distribute.TPUStrategy(tpu)\nelse:\n    # fallback (CPU/GPU) kalau kamu jalankan di environment non-TPU\n    strategy = tf.distribute.get_strategy()\n\nprint(\"REPLICAS:\", strategy.num_replicas_in_sync)","metadata":{"trusted":true,"execution":{"execution_failed":"2025-12-02T08:29:57.208Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Dapatkan path GCS dataset kompetisi\n# Lebih eksplisit: sebutkan nama dataset \"tpu-getting-started\"\nGCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')\nprint(\"GCS path:\", GCS_DS_PATH)\n\nIMAGE_SIZE = [192, 192]   # sesuai referensi\nEPOCHS = 5\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\n\nNUM_TRAINING_IMAGES = 12753\nNUM_TEST_IMAGES     = 7382\nSTEPS_PER_EPOCH     = NUM_TRAINING_IMAGES // BATCH_SIZE\n\nprint(\"Batch size:\", BATCH_SIZE)\nprint(\"Steps per epoch:\", STEPS_PER_EPOCH)","metadata":{"trusted":true,"execution":{"execution_failed":"2025-12-02T08:29:57.208Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"AUTO = tf.data.AUTOTUNE\n\ndef decode_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3)\n    image = tf.cast(image, tf.float32) / 255.0\n    image = tf.reshape(image, [*IMAGE_SIZE, 3])  # ukuran eksplisit untuk TPU\n    return image\n\ndef read_labeled_tfrecord(example):\n    LABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string),\n        \"class\": tf.io.FixedLenFeature([], tf.int64),\n    }\n    example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)\n    image = decode_image(example[\"image\"])\n    label = tf.cast(example[\"class\"], tf.int32)\n    return image, label\n\ndef read_unlabeled_tfrecord(example):\n    UNLABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string),\n        \"id\": tf.io.FixedLenFeature([], tf.string),\n    }\n    example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)\n    image = decode_image(example[\"image\"])\n    idnum = example[\"id\"]\n    return image, idnum\n\ndef load_dataset(filenames, labeled=True, ordered=False):\n    options = tf.data.Options()\n    if not ordered:\n        options.experimental_deterministic = False  # boleh acak demi speed\n\n    dataset = tf.data.TFRecordDataset(\n        filenames,\n        num_parallel_reads=AUTO\n    )\n    dataset = dataset.with_options(options)\n    dataset = dataset.map(\n        read_labeled_tfrecord if labeled else read_unlabeled_tfrecord,\n        num_parallel_calls=AUTO\n    )\n    return dataset\n\ndef get_training_dataset():\n    train_fns = tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-192x192/train/*.tfrec')\n    dataset = load_dataset(train_fns, labeled=True, ordered=False)\n    dataset = dataset.repeat()\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO)\n    return dataset\n\ndef get_validation_dataset():\n    val_fns = tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-192x192/val/*.tfrec')\n    dataset = load_dataset(val_fns, labeled=True, ordered=True)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache()\n    dataset = dataset.prefetch(AUTO)\n    return dataset\n\ndef get_test_dataset(ordered=False):\n    test_fns = tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-192x192/test/*.tfrec')\n    dataset = load_dataset(test_fns, labeled=False, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO)\n    return dataset\n\ntraining_dataset   = get_training_dataset()\nvalidation_dataset = get_validation_dataset()\n\nfor imgs, labels in training_dataset.take(1):\n    print(\"Train batch shape:\", imgs.shape, labels.shape)","metadata":{"trusted":true,"execution":{"execution_failed":"2025-12-02T08:29:57.208Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"with strategy.scope():\n    base_model = tf.keras.applications.VGG16(\n        weights='imagenet',          # kalau error internet, ganti None\n        include_top=False,\n        input_shape=(*IMAGE_SIZE, 3)\n    )\n    base_model.trainable = False  # transfer learning: hanya head yang dilatih\n\n    model = tf.keras.Sequential([\n        base_model,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(104, activation='softmax')\n    ])\n\nmodel.compile(\n    optimizer='adam',\n    loss='sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy']\n)\n\nmodel.summary()","metadata":{"trusted":true,"execution":{"execution_failed":"2025-12-02T08:29:57.208Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_ds = get_test_dataset(ordered=True)\n\nprint(\"Computing predictions on test set...\")\ntest_images_ds = test_ds.map(lambda image, idnum: image)\nprobabilities = model.predict(test_images_ds)\npredictions = np.argmax(probabilities, axis=-1)\nprint(\"Predictions shape:\", predictions.shape)\n\nprint(\"Generating submission.csv file...\")\ntest_ids_ds = test_ds.map(lambda image, idnum: idnum).unbatch()\ntest_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U')  # all ids in one batch\n\nprint(\"IDs shape:\", test_ids.shape)\n\n# Simpan submission\nnp.savetxt(\n    'submission.csv',\n    np.rec.fromarrays([test_ids, predictions]),\n    fmt=['%s', '%d'],\n    delimiter=',',\n    header='id,label',\n    comments=''\n)\n\nprint(\"Done, file 'submission.csv' siap di-download & submit.\")","metadata":{"trusted":true,"execution":{"execution_failed":"2025-12-02T08:29:57.209Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"history = model.fit(\n    training_dataset,\n    steps_per_epoch=STEPS_PER_EPOCH,\n    epochs=EPOCHS,\n    validation_data=validation_dataset\n)","metadata":{"trusted":true,"execution":{"execution_failed":"2025-12-02T08:29:57.209Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_ds = get_test_dataset(ordered=True)\n\nprint(\"Computing predictions on test set...\")\ntest_images_ds = test_ds.map(lambda image, idnum: image)\nprobabilities = model.predict(test_images_ds)\npredictions = np.argmax(probabilities, axis=-1)\nprint(\"Predictions shape:\", predictions.shape)\n\nprint(\"Generating submission.csv file...\")\ntest_ids_ds = test_ds.map(lambda image, idnum: idnum).unbatch()\ntest_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U')  # all ids in one batch\n\nprint(\"IDs shape:\", test_ids.shape)\n\n# Simpan submission\nnp.savetxt(\n    'submission.csv',\n    np.rec.fromarrays([test_ids, predictions]),\n    fmt=['%s', '%d'],\n    delimiter=',',\n    header='id,label',\n    comments=''\n)\n\nprint(\"Done, file 'submission.csv' siap di-download & submit.\")\n","metadata":{"trusted":true,"execution":{"execution_failed":"2025-12-02T08:29:57.209Z"}},"outputs":[],"execution_count":null}]}