{"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":18278,"databundleVersionId":968043,"sourceType":"competition"}],"dockerImageVersionId":31194,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Setup","metadata":{}},{"cell_type":"code","source":"!export PATH=\"${HOME}/.local/bin:${PATH}\" && uv pip uninstall --system jax\n!export PATH=\"${HOME}/.local/bin:${PATH}\" && uv pip install --system tensorflow-tpu==\"2.18.0\" --find-links https://storage.googleapis.com/libtpu-tf-releases/index.html","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-20T12:03:18.775943Z","iopub.execute_input":"2025-11-20T12:03:18.776177Z","iopub.status.idle":"2025-11-20T12:03:37.510201Z","shell.execute_reply.started":"2025-11-20T12:03:18.776158Z","shell.execute_reply":"2025-11-20T12:03:37.509452Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Detection of Accelerator","metadata":{}},{"cell_type":"code","source":"import tensorflow as tf\nfrom kaggle_datasets import KaggleDatasets\nimport numpy as np\n\nprint(\"Tensorflow version \" + tf.__version__)\n\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver(tpu=\"local\")\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.TPUStrategy(tpu)\n    print(f\"Running on TPU: {tpu.master()}\")\n    print(\"REPLICAS: \", strategy.num_replicas_in_sync)\nexcept Exception as e:\n    print(f\"Error initializing TPU: {e}\")\n    # Fallback to default\n    strategy = tf.distribute.get_strategy()\n    print(\"Running on CPU/GPU\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-20T12:03:37.510856Z","iopub.execute_input":"2025-11-20T12:03:37.511015Z","iopub.status.idle":"2025-11-20T12:04:10.794985Z","shell.execute_reply.started":"2025-11-20T12:03:37.510997Z","shell.execute_reply":"2025-11-20T12:04:10.793969Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Get data path","metadata":{}},{"cell_type":"code","source":"# BTW running does nothing since following gets printed\n# get_gcs_path is not required on TPU VMs which can directly use Kaggle datasets, using path: /kaggle/input/flower-classification-with-tpus\n# GCS_DS_PATH = KaggleDatasets().get_gcs_path() # you can list the bucket with \"!gsutil ls $GCS_DS_PATH\"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-20T12:04:10.795673Z","iopub.execute_input":"2025-11-20T12:04:10.795865Z","iopub.status.idle":"2025-11-20T12:04:10.798542Z","shell.execute_reply.started":"2025-11-20T12:04:10.795848Z","shell.execute_reply":"2025-11-20T12:04:10.797730Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Set some parameters","metadata":{}},{"cell_type":"code","source":"# IMAGE_SIZE = [192, 192] # at this size, a GPU will run out of memory. Use the TPU\n# EPOCHS = 5\n# BATCH_SIZE = 16 * strategy.num_replicas_in_sync\n\n# NUM_TRAINING_IMAGES = 12753\n# NUM_TEST_IMAGES = 7382\n# STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\n# AUTO = tf.data.experimental.AUTOTUNE","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-20T12:04:10.798971Z","iopub.execute_input":"2025-11-20T12:04:10.799123Z","iopub.status.idle":"2025-11-20T12:04:10.811327Z","shell.execute_reply.started":"2025-11-20T12:04:10.799108Z","shell.execute_reply":"2025-11-20T12:04:10.810617Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Load my data\n\nThis data is loaded from Kaggle and automatically sharded to maximize parallelization.","metadata":{}},{"cell_type":"code","source":"# DATA_PATH = \"/kaggle/input/flower-classification-with-tpus\" \n# IMAGE_SIZE = [192, 192]\n# EPOCHS = 5\n\n# BATCH_SIZE = 16 * strategy.num_replicas_in_sync\n# AUTO = tf.data.AUTOTUNE\n# NUM_TRAINING_IMAGES = 12753\n# STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\n\n# def 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]) \n#     return image\n\n# def 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\n# def 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\n# def load_dataset(filenames, labeled=True, ordered=False):\n#     ignore_order = tf.data.Options()\n#     if not ordered:\n#         ignore_order.experimental_deterministic = False \n#     dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO) \n#     dataset = dataset.with_options(ignore_order) \n#     dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)\n#     return dataset\n\n# # def get_mat_dataset(filenames, labeled=True, ordered=False):\n# #     dataset = load_dataset(filenames, labeled=labeled, ordered=ordered)\n# #     dataset = dataset.batch(1024) # Large batch for faster loading\n    \n# #     print(f\"Loading data into RAM... (This will take ~60 seconds)\")\n    \n# #     all_images = []\n# #     all_labels = []\n    \n# #     for batch_imgs, batch_lbls in dataset:\n# #         all_images.append(batch_imgs.numpy())\n# #         all_labels.append(batch_lbls.numpy())\n        \n# #     all_images = np.concatenate(all_images)\n# #     all_labels = np.concatenate(all_labels)\n    \n# #     print(f\"Successfully loaded {len(all_images)} images into RAM.\")\n    \n# #     ram_ds = tf.data.Dataset.from_tensor_slices((all_images, all_labels))\n# #     return ram_ds\n\n# def get_training_dataset():\n#     dataset = get_mat_dataset(tf.io.gfile.glob(DATA_PATH + '/tfrecords-jpeg-192x192/train/*.tfrec'), labeled=True)\n#     dataset = dataset.repeat()\n#     dataset = dataset.shuffle(2048)\n#     dataset = dataset.batch(BATCH_SIZE, drop_remainder=True) \n#     dataset = dataset.prefetch(AUTO)\n#     return dataset\n\n# def get_validation_dataset():\n#     dataset = get_mat_dataset(tf.io.gfile.glob(DATA_PATH + '/tfrecords-jpeg-192x192/val/*.tfrec'), labeled=True, ordered=False)\n#     dataset = dataset.batch(BATCH_SIZE, drop_remainder=True)\n#     dataset = dataset.prefetch(AUTO)\n#     return dataset\n\n# training_dataset = get_training_dataset()\n# validation_dataset = get_validation_dataset()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-20T12:04:10.811884Z","iopub.execute_input":"2025-11-20T12:04:10.812037Z","iopub.status.idle":"2025-11-20T12:04:10.824672Z","shell.execute_reply.started":"2025-11-20T12:04:10.812022Z","shell.execute_reply":"2025-11-20T12:04:10.823969Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"DATA_PATH = \"/kaggle/input/flower-classification-with-tpus\"\nGCS_DS_PATH = DATA_PATH\nIMAGE_SIZE = [192, 192]\nEPOCHS = 5\n\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\nAUTO = tf.data.AUTOTUNE\nNUM_TRAINING_IMAGES = 12753\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\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  # convert image to floats in [0, 1] range\n    image = tf.reshape(image, [*IMAGE_SIZE, 3]) # explicit size needed for TPU\n    return image\n\ndef read_labeled_tfrecord(example):\n    LABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"class\": tf.io.FixedLenFeature([], tf.int64),  # shape [] means single element\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 # returns a dataset of (image, label) pairs\n\ndef read_unlabeled_tfrecord(example):\n    UNLABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"id\": tf.io.FixedLenFeature([], tf.string),  # shape [] means single element\n        # class is missing, this competitions's challenge is to predict flower classes for the test dataset\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 # returns a dataset of image(s)\n\ndef load_dataset(filenames, labeled=True, ordered=False):\n    # Read from TFRecords. For optimal performance, reading from multiple files at once and\n    # disregarding data order. Order does not matter since we will be shuffling the data anyway.\n\n    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False # disable order, increase speed\n\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO) # automatically interleaves reads from multiple files\n    dataset = dataset.with_options(ignore_order) # uses data as soon as it streams in, rather than in its original order\n    dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)\n    # returns a dataset of (image, label) pairs if labeled=True or (image, id) pairs if labeled=False\n    return dataset\n\ndef get_training_dataset():\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-192x192/train/*.tfrec'), labeled=True)\n    dataset = dataset.repeat() # the training dataset must repeat for several epochs\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef get_validation_dataset():\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-192x192/val/*.tfrec'), labeled=True, ordered=False)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache()\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef get_test_dataset(ordered=False):\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-192x192/test/*.tfrec'), labeled=False, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ntraining_dataset = get_training_dataset()\nvalidation_dataset = get_validation_dataset()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-20T12:05:15.926258Z","iopub.execute_input":"2025-11-20T12:05:15.926518Z","iopub.status.idle":"2025-11-20T12:05:16.121657Z","shell.execute_reply.started":"2025-11-20T12:05:15.926493Z","shell.execute_reply":"2025-11-20T12:05:16.120611Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Build a model on TPU (or GPU, or CPU...) with Tensorflow 2.1!","metadata":{}},{"cell_type":"code","source":"with strategy.scope():    \n    pretrained_model = tf.keras.applications.VGG16(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])\n    pretrained_model.trainable = False # tramsfer learning\n    \n    model = tf.keras.Sequential([\n        pretrained_model,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(104, activation='softmax')\n    ])\n        \n    model.compile(\n        optimizer='adam',\n        loss = 'sparse_categorical_crossentropy',\n        metrics=['sparse_categorical_accuracy']\n    )\n    \n    historical = model.fit(training_dataset, \n              steps_per_epoch=STEPS_PER_EPOCH, \n              epochs=EPOCHS, \n              validation_data=validation_dataset)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-20T12:13:39.131192Z","iopub.execute_input":"2025-11-20T12:13:39.131503Z","iopub.status.idle":"2025-11-20T12:17:35.630369Z","shell.execute_reply.started":"2025-11-20T12:13:39.131487Z","shell.execute_reply":"2025-11-20T12:17:35.629133Z"}},"outputs":[],"execution_count":null}]}