{"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 tensorflow as tf\nfrom kaggle_datasets import KaggleDatasets\nimport numpy as np\nimport math\nimport re\nimport matplotlib.pyplot as plt\nprint(\"Tensorflow version \" + tf.__version__)","metadata":{"execution":{"iopub.status.busy":"2023-10-03T05:29:19.332716Z","iopub.execute_input":"2023-10-03T05:29:19.333585Z","iopub.status.idle":"2023-10-03T05:29:19.338944Z","shell.execute_reply.started":"2023-10-03T05:29:19.333542Z","shell.execute_reply":"2023-10-03T05:29:19.337956Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Detect hardware, return appropriate distribution strategy\ntry:\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-10-03T05:29:19.340436Z","iopub.execute_input":"2023-10-03T05:29:19.340678Z","iopub.status.idle":"2023-10-03T05:29:26.678759Z","shell.execute_reply.started":"2023-10-03T05:29:19.340656Z","shell.execute_reply":"2023-10-03T05:29:26.677625Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"GCS_DS_PATH = \"/kaggle/input/tpu-getting-started\"","metadata":{"execution":{"iopub.status.busy":"2023-10-03T05:29:26.680358Z","iopub.execute_input":"2023-10-03T05:29:26.680625Z","iopub.status.idle":"2023-10-03T05:29:26.684605Z","shell.execute_reply.started":"2023-10-03T05:29:26.680601Z","shell.execute_reply":"2023-10-03T05:29:26.683723Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMAGE_SIZE = [331, 331] # at this size, a GPU will run out of memory. Use the TPU\nEPOCHS = 30\nBATCH_SIZE = 8 * strategy.num_replicas_in_sync if strategy.num_replicas_in_sync>1 else 64\nAUTO = tf.data.experimental.AUTOTUNE\nNUM_TRAINING_IMAGES = 12753\nNUM_TEST_IMAGES = 7382\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE","metadata":{"execution":{"iopub.status.busy":"2023-10-03T05:52:24.611054Z","iopub.execute_input":"2023-10-03T05:52:24.612166Z","iopub.status.idle":"2023-10-03T05:52:24.616762Z","shell.execute_reply.started":"2023-10-03T05:52:24.612133Z","shell.execute_reply":"2023-10-03T05:52:24.615821Z"},"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 data_augment(image, label):\n    image_aug = tf.image.random_brightness(image, 0.3)\n    image_aug = tf.image.random_contrast(image_aug, 0.3, 0.7)\n    image_aug = tf.image.random_flip_left_right(image_aug)\n    image_aug = tf.image.random_flip_up_down(image_aug)\n    image_aug = tf.image.random_hue(image_aug, 0.3)\n    image_aug = tf.image.adjust_gamma(image_aug, 0.3)\n    image_aug = tf.image.random_saturation(image_aug, 0.3, 0.7)\n    return image_aug, label  \n\ndef get_training_dataset():\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-331x331/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_training_dataset_aug():\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-331x331/train/*.tfrec'), labeled=True)\n    dataset = dataset.map(data_augment, num_parallel_calls=AUTO)\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(ordered=False):\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-331x331/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-331x331/test/*.tfrec'), labeled=False, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    return dataset","metadata":{"execution":{"iopub.status.busy":"2023-10-03T05:29:26.699032Z","iopub.execute_input":"2023-10-03T05:29:26.699287Z","iopub.status.idle":"2023-10-03T05:29:26.715402Z","shell.execute_reply.started":"2023-10-03T05:29:26.699264Z","shell.execute_reply":"2023-10-03T05:29:26.714585Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"training_dataset = get_training_dataset()\naug_training_dataset = get_training_dataset_aug()\ntrain_dataset_augmented = training_dataset.concatenate(aug_training_dataset)\nvalidation_dataset = get_validation_dataset()\ntest_dataset = get_test_dataset(ordered=True)","metadata":{"execution":{"iopub.status.busy":"2023-10-03T05:29:26.716411Z","iopub.execute_input":"2023-10-03T05:29:26.716659Z","iopub.status.idle":"2023-10-03T05:29:27.441094Z","shell.execute_reply.started":"2023-10-03T05:29:26.716637Z","shell.execute_reply":"2023-10-03T05:29:27.439880Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define configuration parameters\nstart_lr = 0.00001\nmin_lr = 0.00001\nmax_lr = 0.00005 * strategy.num_replicas_in_sync\nrampup_epochs = 5\nsustain_epochs = 0\nexp_decay = 0.8\n\n# Define the scheduling function\ndef schedule(epoch):\n  def lr(epoch, start_lr, min_lr, max_lr, rampup_epochs, sustain_epochs, exp_decay):\n    if epoch < rampup_epochs:\n      lr = (max_lr - start_lr)/rampup_epochs * epoch + start_lr\n    elif epoch < rampup_epochs + sustain_epochs:\n      lr = max_lr\n    else:\n      lr = (max_lr - min_lr) * exp_decay**(epoch-rampup_epochs-sustain_epochs) + min_lr\n    return lr\n  return lr(epoch, start_lr, min_lr, max_lr, rampup_epochs, sustain_epochs, exp_decay)\n\nlr_callback = tf.keras.callbacks.LearningRateScheduler(schedule, verbose = True)","metadata":{"execution":{"iopub.status.busy":"2023-10-03T05:52:31.170754Z","iopub.execute_input":"2023-10-03T05:52:31.171821Z","iopub.status.idle":"2023-10-03T05:52:31.178697Z","shell.execute_reply.started":"2023-10-03T05:52:31.171782Z","shell.execute_reply":"2023-10-03T05:52:31.177692Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"rng = [i for i in range(EPOCHS)]\ny = [schedule(x) for x in rng]\nplt.plot(rng, y)\nprint(\"Learning rate schedule: {:.3g} to {:.3g} to {:.3g}\".format(y[0], max(y), y[-1]))","metadata":{"execution":{"iopub.status.busy":"2023-10-03T05:52:33.092229Z","iopub.execute_input":"2023-10-03T05:52:33.093255Z","iopub.status.idle":"2023-10-03T05:52:33.286944Z","shell.execute_reply.started":"2023-10-03T05:52:33.093220Z","shell.execute_reply":"2023-10-03T05:52:33.285943Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nwith strategy.scope():\n    pretrained_model = tf.keras.applications.densenet.DenseNet201(\n        input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3),\n        weights='imagenet',\n        include_top=False,\n        pooling='avg'\n    )\n    # trainable rnet\n    pretrained_model.trainable = True\n    model = tf.keras.Sequential([\n        pretrained_model,\n        tf.keras.layers.Dense(512, activation=\"relu\"),\n        tf.keras.layers.Dense(104, activation='softmax')\n    ])\n\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2023-10-03T05:52:38.085723Z","iopub.execute_input":"2023-10-03T05:52:38.086698Z","iopub.status.idle":"2023-10-03T05:53:14.381001Z","shell.execute_reply.started":"2023-10-03T05:52:38.086664Z","shell.execute_reply":"2023-10-03T05:53:14.379874Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(\n    optimizer='adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy']\n)\nhistory = model.fit(train_dataset_augmented, \n                  steps_per_epoch=STEPS_PER_EPOCH, \n                  epochs=EPOCHS, \n                  callbacks = [lr_callback],\n                  validation_data=validation_dataset)","metadata":{"execution":{"iopub.status.busy":"2023-10-03T05:53:14.382700Z","iopub.execute_input":"2023-10-03T05:53:14.383120Z","iopub.status.idle":"2023-10-03T06:29:46.002726Z","shell.execute_reply.started":"2023-10-03T05:53:14.383080Z","shell.execute_reply":"2023-10-03T06:29:46.001237Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Plot the results\nacc = history.history['sparse_categorical_accuracy']\nval_acc = history.history['val_sparse_categorical_accuracy']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(len(acc))\n\nplt.plot(epochs, acc, 'r', label='Training accuracy')\nplt.plot(epochs, val_acc, 'b', label='Validation accuracy')\nplt.title('Training and validation accuracy')\nplt.legend(loc=0)\nplt.figure()\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-10-03T06:31:01.182178Z","iopub.execute_input":"2023-10-03T06:31:01.182718Z","iopub.status.idle":"2023-10-03T06:31:01.392135Z","shell.execute_reply.started":"2023-10-03T06:31:01.182671Z","shell.execute_reply":"2023-10-03T06:31:01.390901Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import f1_score\n\ncmdataset = get_validation_dataset(ordered=True)\nimages_ds = cmdataset.map(lambda image, label: image)\nlabels_ds = cmdataset.map(lambda image, label: label).unbatch()\n\ncm_correct_labels = next(iter(labels_ds.batch(3712))).numpy()\ncm_probabilities = model.predict(images_ds)\ncm_predictions = np.argmax(cm_probabilities, axis=-1)\n\nlabels = range(104)\n\nscore = f1_score(\n    cm_correct_labels,\n    cm_predictions,\n    labels=labels,\n    average='macro',\n)\n\nprint(\"F1 macro score for validation dataset - \", score)","metadata":{"execution":{"iopub.status.busy":"2023-10-03T06:31:09.075256Z","iopub.execute_input":"2023-10-03T06:31:09.075691Z","iopub.status.idle":"2023-10-03T06:31:39.728953Z","shell.execute_reply.started":"2023-10-03T06:31:09.075657Z","shell.execute_reply":"2023-10-03T06:31:39.727568Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('Computing predictions...')\ntest_images_ds = test_dataset.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_dataset.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-10-03T06:31:39.730804Z","iopub.execute_input":"2023-10-03T06:31:39.731132Z","iopub.status.idle":"2023-10-03T06:32:33.205613Z","shell.execute_reply.started":"2023-10-03T06:31:39.731102Z","shell.execute_reply":"2023-10-03T06:32:33.204254Z"},"trusted":true},"execution_count":null,"outputs":[]}]}