{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.15","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"tpu1vmV38","dataSources":[{"sourceId":21154,"databundleVersionId":1243559,"sourceType":"competition"}],"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\nimport warnings\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\n\nfrom kaggle_datasets import KaggleDatasets\nfrom tensorflow.keras.callbacks import EarlyStopping\n\nwarnings.filterwarnings('ignore')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-20T20:10:13.434755Z","iopub.execute_input":"2024-11-20T20:10:13.435614Z","iopub.status.idle":"2024-11-20T20:10:13.439336Z","shell.execute_reply.started":"2024-11-20T20:10:13.435562Z","shell.execute_reply":"2024-11-20T20:10:13.438611Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print('Tensorflow version ' + tf.__version__)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-20T20:10:13.450829Z","iopub.execute_input":"2024-11-20T20:10:13.451405Z","iopub.status.idle":"2024-11-20T20:10:13.454816Z","shell.execute_reply.started":"2024-11-20T20:10:13.451380Z","shell.execute_reply":"2024-11-20T20:10:13.454072Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-20T20:10:13.466414Z","iopub.execute_input":"2024-11-20T20:10:13.466909Z","iopub.status.idle":"2024-11-20T20:10:13.489234Z","shell.execute_reply.started":"2024-11-20T20:10:13.466881Z","shell.execute_reply":"2024-11-20T20:10:13.488579Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# AUTO = tf.data.experimental.AUTOTUNE\n\nprint(f\"TensorFlow version: {tf.__version__}\")\n\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    print(f\"TPU founded: {tpu.master()}\")\n\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.TPUStrategy(tpu)\n    print(\"TPU success initialized!\")\nexcept (ValueError, tf.errors.NotFoundError) as e:\n    print(\"TPU not found or fail to initialized.\")\n    print(f\"Error: {e}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-20T20:10:13.490289Z","iopub.execute_input":"2024-11-20T20:10:13.490513Z","iopub.status.idle":"2024-11-20T20:10:18.824044Z","shell.execute_reply.started":"2024-11-20T20:10:13.490492Z","shell.execute_reply":"2024-11-20T20:10:18.823186Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(\"REPLICAS: \", strategy.num_replicas_in_sync)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-20T20:10:18.825491Z","iopub.execute_input":"2024-11-20T20:10:18.825781Z","iopub.status.idle":"2024-11-20T20:10:18.829423Z","shell.execute_reply.started":"2024-11-20T20:10:18.825755Z","shell.execute_reply":"2024-11-20T20:10:18.828784Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"GCS_DS_PATH = '/kaggle/input/tpu-getting-started'\n\nIMAGE_SIZE = [192, 192]\nEPOCHS = 25\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":"2024-11-20T20:10:18.830158Z","iopub.execute_input":"2024-11-20T20:10:18.830368Z","iopub.status.idle":"2024-11-20T20:10:18.844515Z","shell.execute_reply.started":"2024-11-20T20:10:18.830347Z","shell.execute_reply":"2024-11-20T20:10:18.843802Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def 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) # 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)\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    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    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    return dataset\n\ntraining_dataset = get_training_dataset()\nvalidation_dataset = get_validation_dataset()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-20T20:10:18.846222Z","iopub.execute_input":"2024-11-20T20:10:18.846527Z","iopub.status.idle":"2024-11-20T20:10:18.962076Z","shell.execute_reply.started":"2024-11-20T20:10:18.846502Z","shell.execute_reply":"2024-11-20T20:10:18.961363Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"early_stop = EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-20T20:10:18.963078Z","iopub.execute_input":"2024-11-20T20:10:18.963558Z","iopub.status.idle":"2024-11-20T20:10:18.967004Z","shell.execute_reply.started":"2024-11-20T20:10:18.963498Z","shell.execute_reply":"2024-11-20T20:10:18.966327Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Assuming `strategy` is your TPU strategy\nwith strategy.scope():\n    # pretrained_model = tf.keras.applications.VGG16(weights='imagenet', include_top=False, input_shape=[*IMAGE_SIZE, 3])\n    # pretrained_model.trainable = False  # Transfer 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 = tf.keras.Sequential([\n        tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=([*IMAGE_SIZE, 3])),\n        tf.keras.layers.MaxPooling2D((2, 2)),\n        tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),\n        tf.keras.layers.MaxPooling2D((2, 2)),\n        tf.keras.layers.Conv2D(128, (3, 3), activation='relu'),\n        tf.keras.layers.MaxPooling2D((2, 2)),\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dropout(0.5),  # Dropout layer for regularization\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# Fit the model within the strategy scope\nhistorical = model.fit(\n    training_dataset,\n    steps_per_epoch=STEPS_PER_EPOCH,\n    epochs=EPOCHS,\n    validation_data=validation_dataset,\n    callbacks=[early_stop]\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-20T20:10:18.967880Z","iopub.execute_input":"2024-11-20T20:10:18.968133Z","iopub.status.idle":"2024-11-20T20:19:30.256814Z","shell.execute_reply.started":"2024-11-20T20:10:18.968107Z","shell.execute_reply":"2024-11-20T20:19:30.255652Z"}},"outputs":[],"execution_count":null},{"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,"execution":{"iopub.status.busy":"2024-11-20T20:19:30.258411Z","iopub.execute_input":"2024-11-20T20:19:30.258735Z","iopub.status.idle":"2024-11-20T20:19:45.818048Z","shell.execute_reply.started":"2024-11-20T20:19:30.258705Z","shell.execute_reply":"2024-11-20T20:19:45.816712Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df = pd.read_csv('submission.csv')\nprint(df)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-20T20:19:45.819245Z","iopub.execute_input":"2024-11-20T20:19:45.819515Z","iopub.status.idle":"2024-11-20T20:19:45.834086Z","shell.execute_reply.started":"2024-11-20T20:19:45.819489Z","shell.execute_reply":"2024-11-20T20:19:45.833094Z"}},"outputs":[],"execution_count":null}]}