{"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.12.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"tpuV5e8","dataSources":[{"sourceType":"competition","sourceId":21154,"databundleVersionId":1243559}],"dockerImageVersionId":31331,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# 🌸 Petals to the Metal — Flower Classification with TPU\nFull pipeline: TPU setup → Data loading → EfficientNetB4 → Training → Submission","metadata":{}},{"cell_type":"code","source":"# ─── CELL 1: IMPORTS & TPU SETUP ───────────────────────────────────────────\nimport math, re, os\nimport numpy as np\nimport tensorflow as tf\nfrom matplotlib import pyplot as plt\nfrom kaggle_datasets import KaggleDatasets\n\nprint('TensorFlow version:', tf.__version__)\n\n# ── Detect TPU and create strategy ──────────────────────────────────────────\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    print('Running on TPU:', tpu.master())\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.TPUStrategy(tpu)\nexcept ValueError:\n    tpu = None\n    strategy = tf.distribute.get_strategy()\n    print('Running on CPU/GPU')\n\nprint('Number of replicas:', strategy.num_replicas_in_sync)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-15T06:13:57.808446Z","iopub.execute_input":"2026-04-15T06:13:57.809056Z","iopub.status.idle":"2026-04-15T06:13:57.815295Z","shell.execute_reply.started":"2026-04-15T06:13:57.809031Z","shell.execute_reply":"2026-04-15T06:13:57.814492Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ─── CELL 2: GLOBAL CONSTANTS ───────────────────────────────────────────────\n#\n# Using 224x224 images + EfficientNetB4:\n#   • Fast enough to finish in ~12–18 minutes on TPU v3-8\n#   • Good accuracy without the heavy 512x512 / B7 combination\n#\nIMAGE_SIZE   = [224, 224]      # must match the tfrecords folder chosen below\nEPOCHS       = 12              # ~12–18 min on TPU v3-8 with 224px images\nBATCH_SIZE   = 16 * strategy.num_replicas_in_sync   # 128 on TPU v3-8\nNUM_CLASSES  = 104\n\nprint(f'Image size : {IMAGE_SIZE}')\nprint(f'Batch size : {BATCH_SIZE}')\nprint(f'Epochs     : {EPOCHS}')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-15T06:13:57.815595Z","iopub.execute_input":"2026-04-15T06:13:57.815746Z","iopub.status.idle":"2026-04-15T06:13:57.825871Z","shell.execute_reply.started":"2026-04-15T06:13:57.815732Z","shell.execute_reply":"2026-04-15T06:13:57.825065Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ─── CELL 3: LOCATE DATASET & BUILD FILE PATHS ──────────────────────────────\nimport os, re\nimport numpy as np\nimport tensorflow as tf\n\nBASE = '/kaggle/input/competitions/tpu-getting-started'\nprint(f'Contents: {os.listdir(BASE)}')\n\nGCS_PATH = BASE + '/tfrecords-jpeg-224x224'\n\nTRAINING_FILENAMES   = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec')\nVALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')\nTEST_FILENAMES       = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec')\n\nprint(f'Train files : {len(TRAINING_FILENAMES)}')\nprint(f'Val   files : {len(VALIDATION_FILENAMES)}')\nprint(f'Test  files : {len(TEST_FILENAMES)}')\n\nassert len(TRAINING_FILENAMES) > 0, 'No training files found!'\nassert len(TEST_FILENAMES)     > 0, 'No test files found!'\n\ndef count_data_items(filenames):\n    counts = [int(re.search(r'-(\\d+)\\.', fn).group(1)) for fn in filenames]\n    return int(np.sum(counts))\n\nNUM_TRAINING_IMAGES   = count_data_items(TRAINING_FILENAMES)\nNUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)\nNUM_TEST_IMAGES       = count_data_items(TEST_FILENAMES)\nSTEPS_PER_EPOCH       = max(1, NUM_TRAINING_IMAGES // BATCH_SIZE)\n\nprint(f'Train images : {NUM_TRAINING_IMAGES}')\nprint(f'Val   images : {NUM_VALIDATION_IMAGES}')\nprint(f'Test  images : {NUM_TEST_IMAGES}')\nprint(f'Steps/epoch  : {STEPS_PER_EPOCH}')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-15T06:13:57.826482Z","iopub.execute_input":"2026-04-15T06:13:57.826637Z","iopub.status.idle":"2026-04-15T06:13:57.870870Z","shell.execute_reply.started":"2026-04-15T06:13:57.826622Z","shell.execute_reply":"2026-04-15T06:13:57.870135Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ─── CELL 4: TF-RECORD DECODERS ─────────────────────────────────────────────\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          # normalise to [0, 1]\n    image = tf.reshape(image, [*IMAGE_SIZE, 3])         # explicit shape for TPU\n    return image\n\ndef read_labeled_tfrecord(example):\n    LABELED_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_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_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_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    opts = tf.data.Options()\n    if not ordered:\n        opts.experimental_deterministic = False\n    dataset = tf.data.TFRecordDataset(\n        filenames, num_parallel_reads=tf.data.AUTOTUNE\n    )\n    dataset = dataset.with_options(opts)\n    parse_fn = read_labeled_tfrecord if labeled else read_unlabeled_tfrecord\n    dataset  = dataset.map(parse_fn, num_parallel_calls=tf.data.AUTOTUNE)\n    return dataset\n\nprint('Decoder functions defined ✓')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-15T06:13:57.871399Z","iopub.execute_input":"2026-04-15T06:13:57.871563Z","iopub.status.idle":"2026-04-15T06:13:57.877559Z","shell.execute_reply.started":"2026-04-15T06:13:57.871548Z","shell.execute_reply":"2026-04-15T06:13:57.876812Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ─── CELL 5: AUGMENTATION & PIPELINE FUNCTIONS ──────────────────────────────\n\ndef data_augment(image, label):\n    image = tf.image.random_flip_left_right(image)\n    image = tf.image.random_flip_up_down(image)\n    image = tf.image.random_brightness(image, max_delta=0.15)\n    image = tf.image.random_contrast(image, lower=0.85, upper=1.15)\n    image = tf.image.random_saturation(image, lower=0.85, upper=1.15)\n    image = tf.clip_by_value(image, 0.0, 1.0)\n    return image, label\n\ndef get_training_dataset():\n    ds = load_dataset(TRAINING_FILENAMES, labeled=True)\n    ds = ds.map(data_augment, num_parallel_calls=tf.data.AUTOTUNE)\n    ds = ds.shuffle(2048)\n    ds = ds.batch(BATCH_SIZE, drop_remainder=True)\n    ds = ds.repeat()                                  # repeat AFTER batch for TPU\n    ds = ds.prefetch(tf.data.AUTOTUNE)\n    return ds\n\ndef get_validation_dataset(ordered=False):\n    ds = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=ordered)\n    ds = ds.batch(BATCH_SIZE, drop_remainder=False)\n    ds = ds.cache()\n    ds = ds.prefetch(tf.data.AUTOTUNE)\n    return ds\n\ndef get_test_dataset(ordered=False):\n    ds = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)\n    ds = ds.batch(BATCH_SIZE, drop_remainder=False)\n    ds = ds.prefetch(tf.data.AUTOTUNE)\n    return ds\n\nprint('Dataset pipeline functions defined ✓')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-15T06:13:57.877972Z","iopub.execute_input":"2026-04-15T06:13:57.878136Z","iopub.status.idle":"2026-04-15T06:13:57.888991Z","shell.execute_reply.started":"2026-04-15T06:13:57.878120Z","shell.execute_reply":"2026-04-15T06:13:57.887973Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ─── CELL 6: QUICK SANITY-CHECK — VISUALISE A FEW TRAINING IMAGES ───────────\nsample_ds = load_dataset(TRAINING_FILENAMES, labeled=True, ordered=False)\nsample_ds = sample_ds.batch(9)\n\nCLASSES = [\n    'pink primrose','hard-leaved pocket orchid','canterbury bells','sweet pea',\n    'wild geranium','tiger lily','moon orchid','bird of paradise','monkshood',\n    'globe thistle','snapdragon',\"colt's foot\",'king protea','spear thistle',\n    'yellow iris','globe-flower','purple coneflower','peruvian lily',\n    'balloon flower','giant white arum lily','fire lily','pincushion flower',\n    'fritillary','red ginger','grape hyacinth','corn poppy',\n    'prince of wales feathers','stemless gentian','artichoke','sweet william',\n    'carnation','garden phlox','love in the mist','cosmos','alpine sea holly',\n    'ruby-lipped cattleya','cape flower','great masterwort','siam tulip',\n    'lenten rose','barbeton daisy','daffodil','sword lily','poinsettia',\n    'bolero deep blue','wallflower','marigold','buttercup','daisy',\n    'common dandelion','petunia','wild pansy','primula','sunflower',\n    'lilac hibiscus','bishop of llandaff','gaura','geranium','orange dahlia',\n    'pink-yellow dahlia','cautleya spicata','japanese anemone',\n    'black-eyed susan','silverbush','californian poppy','osteospermum',\n    'spring crocus','iris','windflower','tree poppy','gazania','azalea',\n    'water lily','rose','thorn apple','morning glory','passion flower',\n    'lotus','toad lily','anthurium','frangipani','clematis','hibiscus',\n    'columbine','desert-rose','tree mallow','magnolia','cyclamen',\n    'watercress','canna lily','hippeastrum','bee balm','pink quill',\n    'foxglove','bougainvillea','camellia','mallow','mexican petunia',\n    'bromelia','blanket flower','trumpet creeper','blackberry lily',\n    'common tulip','wild rose'\n]\n\nimages, labels = next(iter(sample_ds))\nplt.figure(figsize=(12, 12))\nfor i in range(9):\n    plt.subplot(3, 3, i+1)\n    plt.imshow(images[i].numpy())\n    plt.title(CLASSES[labels[i]], fontsize=9)\n    plt.axis('off')\nplt.suptitle('Sample Training Images', fontsize=14)\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-15T06:13:57.889304Z","iopub.execute_input":"2026-04-15T06:13:57.889470Z","iopub.status.idle":"2026-04-15T06:13:58.959708Z","shell.execute_reply.started":"2026-04-15T06:13:57.889454Z","shell.execute_reply":"2026-04-15T06:13:58.958553Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ─── CELL 7: BUILD MODEL (EfficientNetB4, inside TPU strategy scope) ─────────\n#\n# EfficientNetB4 + 224px: great accuracy / speed balance on TPU.\n# trainable=False for base initially, then we do fine-tuning.\n#\nwith strategy.scope():\n    base_model = tf.keras.applications.EfficientNetB4(\n        weights='imagenet',\n        include_top=False,\n        input_shape=[*IMAGE_SIZE, 3]\n    )\n    base_model.trainable = True     # full fine-tune from the start\n\n    model = tf.keras.Sequential([\n        base_model,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.BatchNormalization(),\n        tf.keras.layers.Dropout(0.4),\n        tf.keras.layers.Dense(NUM_CLASSES, activation='softmax', dtype='float32')\n    ])\n\n    model.compile(\n        optimizer=tf.keras.optimizers.Adam(learning_rate=1e-4),\n        loss='sparse_categorical_crossentropy',\n        metrics=['sparse_categorical_accuracy']\n    )\n\nmodel.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-15T06:13:58.960812Z","iopub.execute_input":"2026-04-15T06:13:58.961013Z","iopub.status.idle":"2026-04-15T06:14:02.319344Z","shell.execute_reply.started":"2026-04-15T06:13:58.960995Z","shell.execute_reply":"2026-04-15T06:14:02.318109Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ─── CELL 8: LEARNING RATE SCHEDULE ─────────────────────────────────────────\n\nLR_START          = 1e-5\nLR_MAX            = 1e-4 * strategy.num_replicas_in_sync\nLR_MIN            = 1e-6\nLR_RAMPUP_EPOCHS  = 3\nLR_SUSTAIN_EPOCHS = 0\nLR_EXP_DECAY      = 0.85\n\ndef lrfn(epoch):\n    if epoch < LR_RAMPUP_EPOCHS:\n        return (LR_MAX - LR_START) / LR_RAMPUP_EPOCHS * epoch + LR_START\n    elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:\n        return LR_MAX\n    else:\n        decay = LR_EXP_DECAY ** (epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS)\n        return (LR_MAX - LR_MIN) * decay + LR_MIN\n\nlr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=True)\n\nrng = list(range(EPOCHS))\nlrs = [lrfn(e) for e in rng]\nplt.figure(figsize=(8, 3))\nplt.plot(rng, [lr * 1e5 for lr in lrs], marker='o')\nplt.title('Learning Rate Schedule (×1e-5)')\nplt.xlabel('Epoch'); plt.ylabel('LR ×1e-5')\nplt.grid(True)\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-15T06:14:02.320125Z","iopub.execute_input":"2026-04-15T06:14:02.320310Z","iopub.status.idle":"2026-04-15T06:14:02.419947Z","shell.execute_reply.started":"2026-04-15T06:14:02.320291Z","shell.execute_reply":"2026-04-15T06:14:02.418990Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ─── CELL 9: TRAIN ───────────────────────────────────────────────────────────\n# Recalculate steps to guarantee we finish in ~15-18 min\n# Epoch 1 took ~1481s at 797 steps → way too long.\n# Target: ~90s/epoch × 10 epochs = ~15 min total\n# 90s / 2s_per_step = ~45 steps/epoch is too few for learning.\n# Better fix: keep steps but reduce epochs sharply.\n\nEPOCHS = 5                                     # ~5 × 5min = ~18min total\nSTEPS_PER_EPOCH_CAPPED = min(STEPS_PER_EPOCH, 400)  # cap at 400 steps/epoch\n\nprint(f'Training {EPOCHS} epochs × {STEPS_PER_EPOCH_CAPPED} steps = '\n      f'~{EPOCHS * STEPS_PER_EPOCH_CAPPED * 2 // 60} min estimated')\n\nhistory = model.fit(\n    get_training_dataset(),\n    steps_per_epoch=STEPS_PER_EPOCH_CAPPED,\n    epochs=EPOCHS,\n    validation_data=get_validation_dataset(),\n    callbacks=[lr_callback],\n    verbose=1\n)\n\nprint('Training complete ✓')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-15T06:14:02.420526Z","iopub.execute_input":"2026-04-15T06:14:02.420694Z","iopub.status.idle":"2026-04-15T07:18:07.905706Z","shell.execute_reply.started":"2026-04-15T06:14:02.420678Z","shell.execute_reply":"2026-04-15T07:18:07.904611Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ─── CELL 10: TRAINING CURVES ────────────────────────────────────────────────\nfig, axes = plt.subplots(1, 2, figsize=(14, 4))\n\naxes[0].plot(history.history['sparse_categorical_accuracy'],   label='Train Acc')\naxes[0].plot(history.history['val_sparse_categorical_accuracy'], label='Val Acc')\naxes[0].set_title('Accuracy'); axes[0].legend(); axes[0].grid(True)\n\naxes[1].plot(history.history['loss'],     label='Train Loss')\naxes[1].plot(history.history['val_loss'], label='Val Loss')\naxes[1].set_title('Loss'); axes[1].legend(); axes[1].grid(True)\n\nplt.tight_layout()\nplt.show()\n\nbest_val_acc = max(history.history['val_sparse_categorical_accuracy'])\nprint(f'Best validation accuracy: {best_val_acc:.4f}')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-15T07:18:07.906284Z","iopub.execute_input":"2026-04-15T07:18:07.906467Z","iopub.status.idle":"2026-04-15T07:18:08.182932Z","shell.execute_reply.started":"2026-04-15T07:18:07.906449Z","shell.execute_reply":"2026-04-15T07:18:08.181768Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ─── CELL 11: PREDICT & GENERATE submission.csv ──────────────────────────────\n#\n# IMPORTANT: ordered=True so IDs and predictions stay aligned.\n#\nprint(f'Predicting on {NUM_TEST_IMAGES} test images …')\n\ntest_ds = get_test_dataset(ordered=True)\n\n# ── Run predictions ──────────────────────────────────────────────────────────\nimage_ds   = test_ds.map(lambda img, idnum: img)\nprobas     = model.predict(image_ds, verbose=1)\npredictions = np.argmax(probas, axis=-1)\nprint(f'Predictions shape: {predictions.shape}')\n\n# ── Collect IDs ──────────────────────────────────────────────────────────────\n# Collect IDs one batch at a time to avoid a single giant unbatched tensor\nid_ds     = test_ds.map(lambda img, idnum: idnum)\ntest_ids  = []\nfor id_batch in id_ds:\n    test_ids.extend(id_batch.numpy().tolist())\n\ntest_ids = [tid.decode('utf-8') if isinstance(tid, bytes) else str(tid)\n            for tid in test_ids]\n\nprint(f'Collected {len(test_ids)} IDs')\nassert len(test_ids) == len(predictions), \\\n    f'ID count {len(test_ids)} != prediction count {len(predictions)}'\n\n# ── Write CSV ────────────────────────────────────────────────────────────────\nimport pandas as pd\nsub = pd.DataFrame({'id': test_ids, 'label': predictions})\nsub.to_csv('submission.csv', index=False)\n\nprint('submission.csv written ✓')\nprint(sub.head(10))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-15T07:18:08.183605Z","iopub.execute_input":"2026-04-15T07:18:08.183780Z","iopub.status.idle":"2026-04-15T07:20:28.880735Z","shell.execute_reply.started":"2026-04-15T07:18:08.183764Z","shell.execute_reply":"2026-04-15T07:20:28.879267Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ─── CELL 12: VERIFY SUBMISSION ──────────────────────────────────────────────\nimport pandas as pd\n\nsub    = pd.read_csv('submission.csv')\nsample = pd.read_csv('/kaggle/input/competitions/tpu-getting-started/sample_submission.csv')\n\nprint(f'Submission rows : {len(sub)}')\nprint(f'Expected rows   : {len(sample)}')\nprint(f'Label range     : {sub.label.min()} – {sub.label.max()} (expected 0–103)')\nprint(f'Missing IDs     : {set(sample.id) - set(sub.id)}')\nprint('\\nFirst 5 rows:')\nprint(sub.head())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-15T07:20:28.881289Z","iopub.execute_input":"2026-04-15T07:20:28.881485Z","iopub.status.idle":"2026-04-15T07:20:28.921693Z","shell.execute_reply.started":"2026-04-15T07:20:28.881465Z","shell.execute_reply":"2026-04-15T07:20:28.920700Z"}},"outputs":[],"execution_count":null}]}