{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.applications.xception import Xception\nfrom tensorflow.keras.callbacks import CSVLogger, EarlyStopping, ModelCheckpoint, LearningRateScheduler\nfrom keras.layers import Dense, Flatten, GlobalAveragePooling2D, Dropout\nimport tensorflow as tf\n\nprint(\"Tensorflow version \" + tf.__version__)","metadata":{"execution":{"iopub.status.busy":"2023-04-17T16:22:49.753242Z","iopub.execute_input":"2023-04-17T16:22:49.753982Z","iopub.status.idle":"2023-04-17T16:22:58.155389Z","shell.execute_reply.started":"2023-04-17T16:22:49.753949Z","shell.execute_reply":"2023-04-17T16:22:58.153044Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"try:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()  # TPU detection. No parameters necessary if TPU_NAME environment variable is set. On Kaggle this is always the case.\n    print('Running on TPU ', tpu.master())\nexcept ValueError:\n    tpu = None\n\nif tpu:\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.TPUStrategy(tpu)\nelse:\n    strategy = tf.distribute.get_strategy() # default distribution strategy in Tensorflow. Works on CPU and single GPU.\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","metadata":{"execution":{"iopub.status.busy":"2023-04-17T16:22:58.157777Z","iopub.execute_input":"2023-04-17T16:22:58.158534Z","iopub.status.idle":"2023-04-17T16:22:58.170879Z","shell.execute_reply.started":"2023-04-17T16:22:58.158492Z","shell.execute_reply":"2023-04-17T16:22:58.169625Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"GCS_DS_PATH = \"/kaggle/input/tpu-getting-started/tfrecords-jpeg-512x512\" # you can list the bucket with ","metadata":{"execution":{"iopub.status.busy":"2023-04-17T16:22:58.172602Z","iopub.execute_input":"2023-04-17T16:22:58.173185Z","iopub.status.idle":"2023-04-17T16:22:58.177744Z","shell.execute_reply.started":"2023-04-17T16:22:58.173147Z","shell.execute_reply":"2023-04-17T16:22:58.176547Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Load The Dataset","metadata":{}},{"cell_type":"code","source":"IMAGE_SIZE = [512, 512]\nEPOCHS = 300\nBATCH_SIZE = 32\nnumberOfClass = 104\n\nNUM_TRAINING_IMAGES = 12753\nNUM_TEST_IMAGES = 7382\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE","metadata":{"execution":{"iopub.status.busy":"2023-04-17T16:22:58.181148Z","iopub.execute_input":"2023-04-17T16:22:58.181532Z","iopub.status.idle":"2023-04-17T16:22:58.188328Z","shell.execute_reply.started":"2023-04-17T16:22:58.181504Z","shell.execute_reply":"2023-04-17T16:22:58.187290Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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 + '/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 + '/val/*.tfrec'), labeled=True, ordered=False)\n    dataset = dataset.batch(BATCH_SIZE)\n    return dataset\n\ndef get_test_dataset(ordered=False):\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/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":{"execution":{"iopub.status.busy":"2023-04-17T16:22:58.190026Z","iopub.execute_input":"2023-04-17T16:22:58.190603Z","iopub.status.idle":"2023-04-17T16:23:00.966069Z","shell.execute_reply.started":"2023-04-17T16:22:58.190550Z","shell.execute_reply":"2023-04-17T16:23:00.965028Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for images, labels in training_dataset.take(1):  \n    print(images.shape)  \n    print(labels.shape)","metadata":{"execution":{"iopub.status.busy":"2023-04-17T16:23:00.967333Z","iopub.execute_input":"2023-04-17T16:23:00.967716Z","iopub.status.idle":"2023-04-17T16:23:10.967367Z","shell.execute_reply.started":"2023-04-17T16:23:00.967671Z","shell.execute_reply":"2023-04-17T16:23:10.966264Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"densenet = tf.keras.models.load_model('/kaggle/input/densenetx512/densenet_512x512.h5')\nxception = tf.keras.models.load_model('/kaggle/input/xception-512/xception_512x512.h5')","metadata":{"execution":{"iopub.status.busy":"2023-04-17T16:23:10.968818Z","iopub.execute_input":"2023-04-17T16:23:10.969494Z","iopub.status.idle":"2023-04-17T16:23:20.672581Z","shell.execute_reply.started":"2023-04-17T16:23:10.969453Z","shell.execute_reply":"2023-04-17T16:23:20.671472Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Submitting ","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)\n#probabilities = densenet.predict(test_images_ds)\n\nm1 = xception.predict(test_images_ds)\nm2 = densenet.predict(test_images_ds)\nprobabilities = (m1 + m2) / 2\n\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":{"execution":{"iopub.status.busy":"2023-04-17T16:23:20.674533Z","iopub.execute_input":"2023-04-17T16:23:20.674921Z","iopub.status.idle":"2023-04-17T16:28:27.985587Z","shell.execute_reply.started":"2023-04-17T16:23:20.674881Z","shell.execute_reply":"2023-04-17T16:28:27.984549Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}