{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.7.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceType":"competition","sourceId":21154,"databundleVersionId":1243559,"isSourceIdPinned":false}],"dockerImageVersionId":30299,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# A Simple TF 2.2 notebook\n\nThis is intended as a simple, short introduction to the operations competitors will need to perform with TPUs.","metadata":{}},{"cell_type":"code","source":"import tensorflow as tf\nfrom kaggle_datasets import KaggleDatasets\nimport numpy as np\n\nprint(\"Tensorflow version \" + tf.__version__)","metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","trusted":true,"execution":{"iopub.status.busy":"2026-03-04T07:16:34.017642Z","iopub.execute_input":"2026-03-04T07:16:34.018176Z","iopub.status.idle":"2026-03-04T07:16:39.556953Z","shell.execute_reply.started":"2026-03-04T07:16:34.018055Z","shell.execute_reply":"2026-03-04T07:16:39.555574Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Detect my accelerator","metadata":{}},{"cell_type":"code","source":"import tensorflow as tf\nimport os\nimport logging\n\nlogging.basicConfig(level=logging.INFO)\n\ndef get_distribution_strategy():\n    \"\"\"\n    Auto-detect best available hardware (TPU > Multi-GPU > Single GPU > CPU)\n    and return appropriate tf.distribute strategy.\n    \"\"\"\n    try:\n        # --- TPU Detection ---\n        resolver = tf.distribute.cluster_resolver.TPUClusterResolver()\n        tf.config.experimental_connect_to_cluster(resolver)\n        tf.tpu.experimental.initialize_tpu_system(resolver)\n        logging.info(f\"✅ Running on TPU: {resolver.master()}\")\n        return tf.distribute.TPUStrategy(resolver)\n\n    except (ValueError, tf.errors.NotFoundError):\n        # --- GPU Detection ---\n        gpus = tf.config.list_physical_devices('GPU')\n        \n        if len(gpus) > 1:\n            logging.info(f\"✅ Running on {len(gpus)} GPUs (MirroredStrategy)\")\n            return tf.distribute.MirroredStrategy()\n\n        elif len(gpus) == 1:\n            logging.info(\"✅ Running on single GPU\")\n            return tf.distribute.get_strategy()\n\n        else:\n            logging.info(\"⚠️ Running on CPU\")\n            return tf.distribute.get_strategy()\n\n\n# Initialize strategy\nstrategy = get_distribution_strategy()\n\nprint(f\"REPLICAS IN SYNC: {strategy.num_replicas_in_sync}\")","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Get my data path","metadata":{}},{"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\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","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-04T07:17:10.095626Z","iopub.execute_input":"2026-03-04T07:17:10.096046Z","iopub.status.idle":"2026-03-04T07:17:10.102472Z","shell.execute_reply.started":"2026-03-04T07:17:10.096013Z","shell.execute_reply":"2026-03-04T07:17:10.101093Z"}},"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":"AUTO = tf.data.AUTOTUNE\n\n# ===============================\n# IMAGE DECODER\n# ===============================\ndef decode_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3)\n    image = tf.image.convert_image_dtype(image, tf.float32)  # safer & faster normalization\n    image = tf.reshape(image, (*IMAGE_SIZE, 3))  # explicit for TPU\n    return image\n\n\n# ===============================\n# OPTIONAL AUGMENTATION (train only)\n# ===============================\ndef augment_image(image, label):\n    image = tf.image.random_flip_left_right(image)\n    image = tf.image.random_brightness(image, 0.1)\n    image = tf.image.random_contrast(image, 0.8, 1.2)\n    return image, label\n\n\n# ===============================\n# TFRECORD READERS\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\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\n    return image, label\n\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\n    example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)\n    image = decode_image(example[\"image\"])\n    idnum = example[\"id\"]\n\n    return image, idnum\n\n\n# ===============================\n# DATASET LOADER (Optimized)\n# ===============================\ndef load_dataset(filenames, labeled=True, ordered=False):\n\n    options = tf.data.Options()\n    options.experimental_deterministic = ordered\n\n    dataset = tf.data.Dataset.from_tensor_slices(filenames)\n    dataset = dataset.interleave(\n        lambda x: tf.data.TFRecordDataset(x),\n        cycle_length=AUTO,\n        num_parallel_calls=AUTO\n    )\n\n    dataset = dataset.with_options(options)\n\n    dataset = dataset.map(\n        read_labeled_tfrecord if labeled else read_unlabeled_tfrecord,\n        num_parallel_calls=AUTO\n    )\n\n    return dataset\n\n\n# ===============================\n# TRAIN DATASET\n# ===============================\ndef get_training_dataset():\n    files = tf.io.gfile.glob(\n        GCS_DS_PATH + \"/tfrecords-jpeg-192x192/train/*.tfrec\"\n    )\n\n    dataset = load_dataset(files, labeled=True, ordered=False)\n\n    dataset = dataset.shuffle(4096)\n    dataset = dataset.map(augment_image, num_parallel_calls=AUTO)\n    dataset = dataset.repeat()\n    dataset = dataset.batch(BATCH_SIZE, drop_remainder=True)\n    dataset = dataset.prefetch(AUTO)\n\n    return dataset\n\n\n# ===============================\n# VALIDATION DATASET\n# ===============================\ndef get_validation_dataset():\n    files = tf.io.gfile.glob(\n        GCS_DS_PATH + \"/tfrecords-jpeg-192x192/val/*.tfrec\"\n    )\n\n    dataset = load_dataset(files, labeled=True, ordered=True)\n\n    dataset = dataset.batch(BATCH_SIZE, drop_remainder=False)\n    dataset = dataset.cache()\n    dataset = dataset.prefetch(AUTO)\n\n    return dataset\n\n\n# ===============================\n# TEST DATASET\n# ===============================\ndef get_test_dataset(ordered=True):\n    files = tf.io.gfile.glob(\n        GCS_DS_PATH + \"/tfrecords-jpeg-192x192/test/*.tfrec\"\n    )\n\n    dataset = load_dataset(files, labeled=False, ordered=ordered)\n\n    dataset = dataset.batch(BATCH_SIZE, drop_remainder=False)\n    dataset = dataset.prefetch(AUTO)\n\n    return dataset\n\n\n# ===============================\n# BUILD DATASETS\n# ===============================\ntraining_dataset = get_training_dataset()\nvalidation_dataset = get_validation_dataset()","metadata":{"trusted":true},"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        \nmodel.compile(\n    optimizer='adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy']\n)\n\nhistorical = model.fit(training_dataset, \n          steps_per_epoch=STEPS_PER_EPOCH, \n          epochs=EPOCHS, \n          validation_data=validation_dataset)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-04T07:17:25.989309Z","iopub.execute_input":"2026-03-04T07:17:25.990169Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Compute your predictions on the test set!\n\nThis will create a file that can be submitted to the competition.","metadata":{}},{"cell_type":"code","source":"test_ds = get_test_dataset(ordered=True) # since we are splitting the dataset and iterating separately on images and ids, order matters.\n\nprint('Computing predictions...')\ntest_images_ds = test_ds.map(lambda image, idnum: image)\nprobabilities = model.predict(test_images_ds)\npredictions = np.argmax(probabilities, axis=-1)\nprint(predictions)\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 in one batch\nnp.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}