{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Custom training with TPU\n\nThis kernel demonstrate how to use custom model and custom training loop with TPU.\n\n    * Wrap 3 models into Flower_Classifier (Xception, ResNet152V2, InceptionResNetV2).\n    * Learn ensemble coefficients during training.\n    * Label smoothing to avoid overconfidence.\n    \n## Table of Contents (of interesting parts)\n\n1. [Custom model definition](#Custom_model_definition)\n1. [Custom learning schedule](#Custom_learning_schedule)\n1. [Optimizer](#Optimizer)\n1. [Define loss function](#Define_loss_function)\n1. [Define metrics](#Define_metrics)\n1. [Define Training / Validation / Test steps](#Define_Training_/_Validation_/_Test_steps)\n1. [Distributed datasets](#Distributed_datasets)\n1. [Training / Validation / Prediction](#Training_/_Validation_/_Prediction)\n\n## Recommended training kernels\n\n   1. [Getting started with 100+ flowers on TPU](https://www.kaggle.com/mgornergoogle/getting-started-with-100-flowers-on-tpu)\n\n   2. [Custom Training Loop with 100+ flowers on TPU](https://www.kaggle.com/mgornergoogle/custom-training-loop-with-100-flowers-on-tpu)\n\n   3. Any other kernels promoted by Kaggle in the previous `Flower Classification with TPUs` competition.\n    \n","execution_count":null},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import math, re, os\nimport tensorflow as tf\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom kaggle_datasets import KaggleDatasets\nfrom sklearn.metrics import f1_score, precision_score, recall_score, confusion_matrix\nimport datetime\nprint(\"Tensorflow version \" + tf.__version__)\nAUTO = tf.data.experimental.AUTOTUNE","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.applications import Xception\nfrom tensorflow.keras.applications import DenseNet121, DenseNet169, DenseNet201\nfrom tensorflow.keras.applications import ResNet50V2, ResNet101V2, ResNet152V2\nfrom tensorflow.keras.applications import InceptionV3\nfrom tensorflow.keras.applications import InceptionResNetV2","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# TPU or GPU detection","execution_count":null},{"metadata":{"trusted":true},"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.experimental.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)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Competition data access\nTPUs read data directly from Google Cloud Storage (GCS). This Kaggle utility will copy the dataset to a GCS bucket co-located with the TPU. If you have multiple datasets attached to the notebook, you can pass the name of a specific dataset to the get_gcs_path function. The name of the dataset is the name of the directory it is mounted in. Use `!ls /kaggle/input/` to list attached datasets.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"!ls -l '/kaggle/input'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"GCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started') # you can list the bucket with \"!gsutil ls $GCS_DS_PATH\"\n!gsutil ls -l $GCS_DS_PATH","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Configuration","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# At the size 512, a GPU will run out of memory. Use the TPU.\n# We use the size 192 here in order to save time.\nIMAGE_SIZE = [512, 512] \n\nEPOCHS = 40\nWARMUP_EPOCHS = 8\nBATCH_SIZE = 8 * strategy.num_replicas_in_sync\n\nGCS_PATH_SELECT = { # available image sizes\n    192: GCS_DS_PATH + '/tfrecords-jpeg-192x192',\n    224: GCS_DS_PATH + '/tfrecords-jpeg-224x224',\n    331: GCS_DS_PATH + '/tfrecords-jpeg-331x331',\n    512: GCS_DS_PATH + '/tfrecords-jpeg-512x512'\n}\nGCS_PATH = GCS_PATH_SELECT[IMAGE_SIZE[0]]\n\nTRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec')\nVALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')\nTEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec') # predictions on this dataset should be submitted for the competition\n\nCLASSES = ['pink primrose',    'hard-leaved pocket orchid', 'canterbury bells', 'sweet pea',     'wild geranium',     'tiger lily',           'moon orchid',              'bird of paradise', 'monkshood',        'globe thistle',         # 00 - 09\n           'snapdragon',       \"colt's foot\",               'king protea',      'spear thistle', 'yellow iris',       'globe-flower',         'purple coneflower',        'peruvian lily',    'balloon flower',   'giant white arum lily', # 10 - 19\n           'fire lily',        'pincushion flower',         'fritillary',       'red ginger',    'grape hyacinth',    'corn poppy',           'prince of wales feathers', 'stemless gentian', 'artichoke',        'sweet william',         # 20 - 29\n           'carnation',        'garden phlox',              'love in the mist', 'cosmos',        'alpine sea holly',  'ruby-lipped cattleya', 'cape flower',              'great masterwort', 'siam tulip',       'lenten rose',           # 30 - 39\n           'barberton daisy',  'daffodil',                  'sword lily',       'poinsettia',    'bolero deep blue',  'wallflower',           'marigold',                 'buttercup',        'daisy',            'common dandelion',      # 40 - 49\n           'petunia',          'wild pansy',                'primula',          'sunflower',     'lilac hibiscus',    'bishop of llandaff',   'gaura',                    'geranium',         'orange dahlia',    'pink-yellow dahlia',    # 50 - 59\n           'cautleya spicata', 'japanese anemone',          'black-eyed susan', 'silverbush',    'californian poppy', 'osteospermum',         'spring crocus',            'iris',             'windflower',       'tree poppy',            # 60 - 69\n           'gazania',          'azalea',                    'water lily',       'rose',          'thorn apple',       'morning glory',        'passion flower',           'lotus',            'toad lily',        'anthurium',             # 70 - 79\n           'frangipani',       'clematis',                  'hibiscus',         'columbine',     'desert-rose',       'tree mallow',          'magnolia',                 'cyclamen ',        'watercress',       'canna lily',            # 80 - 89\n           'hippeastrum ',     'bee balm',                  'pink quill',       'foxglove',      'bougainvillea',     'camellia',             'mallow',                   'mexican petunia',  'bromelia',         'blanket flower',        # 90 - 99\n           'trumpet creeper',  'blackberry lily',           'common tulip',     'wild rose']                                                                                                                                               # 100 - 102","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Visualization utilities\ndata -> pixels, nothing of much interest for the machine learning practitioner in this section.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# numpy and matplotlib defaults\nnp.set_printoptions(threshold=15, linewidth=80)\n\ndef batch_to_numpy_images_and_labels(data):\n    images, labels = data\n    numpy_images = images.numpy()\n    numpy_labels = labels.numpy()\n    if numpy_labels.dtype == object: # binary string in this case, these are image ID strings\n        numpy_labels = [None for _ in enumerate(numpy_images)]\n    # If no labels, only image IDs, return None for labels (this is the case for test data)\n    return numpy_images, numpy_labels\n\ndef title_from_label_and_target(label, correct_label):\n    if correct_label is None:\n        return CLASSES[label], True\n    correct = (label == correct_label)\n    return \"{} [{}{}{}]\".format(CLASSES[label], 'OK' if correct else 'NO', u\"\\u2192\" if not correct else '',\n                                CLASSES[correct_label] if not correct else ''), correct\n\ndef display_one_flower(image, title, subplot, red=False, titlesize=16):\n    plt.subplot(*subplot)\n    plt.axis('off')\n    plt.imshow(image)\n    if len(title) > 0:\n        plt.title(title, fontsize=int(titlesize) if not red else int(titlesize/1.2), color='red' if red else 'black', fontdict={'verticalalignment':'center'}, pad=int(titlesize/1.5))\n    return (subplot[0], subplot[1], subplot[2]+1)\n    \ndef display_batch_of_images(databatch, predictions=None):\n    \"\"\"This will work with:\n    display_batch_of_images(images)\n    display_batch_of_images(images, predictions)\n    display_batch_of_images((images, labels))\n    display_batch_of_images((images, labels), predictions)\n    \"\"\"\n    # data\n    images, labels = batch_to_numpy_images_and_labels(databatch)\n    if labels is None:\n        labels = [None for _ in enumerate(images)]\n        \n    # auto-squaring: this will drop data that does not fit into square or square-ish rectangle\n    rows = int(math.sqrt(len(images)))\n    cols = len(images)//rows\n        \n    # size and spacing\n    FIGSIZE = 13.0\n    SPACING = 0.1\n    subplot=(rows,cols,1)\n    if rows < cols:\n        plt.figure(figsize=(FIGSIZE,FIGSIZE/cols*rows))\n    else:\n        plt.figure(figsize=(FIGSIZE/rows*cols,FIGSIZE))\n    \n    # display\n    for i, (image, label) in enumerate(zip(images[:rows*cols], labels[:rows*cols])):\n        title = '' if label is None else CLASSES[label]\n        correct = True\n        if predictions is not None:\n            title, correct = title_from_label_and_target(predictions[i], label)\n        dynamic_titlesize = FIGSIZE*SPACING/max(rows,cols)*40+3 # magic formula tested to work from 1x1 to 10x10 images\n        subplot = display_one_flower(image, title, subplot, not correct, titlesize=dynamic_titlesize)\n    \n    #layout\n    plt.tight_layout()\n    if label is None and predictions is None:\n        plt.subplots_adjust(wspace=0, hspace=0)\n    else:\n        plt.subplots_adjust(wspace=SPACING, hspace=SPACING)\n    plt.show()\n\ndef display_confusion_matrix(cmat, score, precision, recall):\n    plt.figure(figsize=(15,15))\n    ax = plt.gca()\n    ax.matshow(cmat, cmap='Reds')\n    ax.set_xticks(range(len(CLASSES)))\n    ax.set_xticklabels(CLASSES, fontdict={'fontsize': 7})\n    plt.setp(ax.get_xticklabels(), rotation=45, ha=\"left\", rotation_mode=\"anchor\")\n    ax.set_yticks(range(len(CLASSES)))\n    ax.set_yticklabels(CLASSES, fontdict={'fontsize': 7})\n    plt.setp(ax.get_yticklabels(), rotation=45, ha=\"right\", rotation_mode=\"anchor\")\n    titlestring = \"\"\n    if score is not None:\n        titlestring += 'f1 = {:.3f} '.format(score)\n    if precision is not None:\n        titlestring += '\\nprecision = {:.3f} '.format(precision)\n    if recall is not None:\n        titlestring += '\\nrecall = {:.3f} '.format(recall)\n    if len(titlestring) > 0:\n        ax.text(101, 1, titlestring, fontdict={'fontsize': 18, 'horizontalalignment':'right', 'verticalalignment':'top', 'color':'#804040'})\n    plt.show()\n    \ndef display_training_curves(training, validation, title, subplot):\n    if subplot%10==1: # set up the subplots on the first call\n        plt.subplots(figsize=(10,10), facecolor='#F0F0F0')\n        plt.tight_layout()\n    ax = plt.subplot(subplot)\n    ax.set_facecolor('#F8F8F8')\n    ax.plot(training)\n    ax.plot(validation)\n    ax.set_title('model '+ title)\n    ax.set_ylabel(title)\n    #ax.set_ylim(0.28,1.05)\n    ax.set_xlabel('epoch')\n    ax.legend(['train', 'valid.'])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Datasets","execution_count":null},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"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, 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 data_augment(image, label):\n    # data augmentation. Thanks to the dataset.prefetch(AUTO) statement in the next function (below),\n    # this happens essentially for free on TPU. Data pipeline code is executed on the \"CPU\" part\n    # of the TPU while the TPU itself is computing gradients.\n    image = tf.image.random_flip_left_right(image)\n    #image = tf.image.random_saturation(image, 0, 2)\n    return image, label   \n\ndef get_training_dataset():\n    dataset = load_dataset(TRAINING_FILENAMES, labeled=True)\n    dataset = dataset.map(data_augment, num_parallel_calls=AUTO)\n    # dataset = dataset.repeat() # Since we use custom training loop, we don't need to use repeat() here.\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE, drop_remainder=True)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef get_validation_dataset(ordered=False):\n    dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=ordered)\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(TEST_FILENAMES, 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\ndef count_data_items(filenames):\n    # the number of data items is written in the name of the .tfrec files, i.e. flowers00-230.tfrec = 230 data items\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    return np.sum(n)\n\nNUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)\nNUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\nprint('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Dataset visualizations","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# data dump\nprint(\"Training data shapes:\")\nfor image, label in get_training_dataset().take(3):\n    print(image.numpy().shape, label.numpy().shape)\nprint(\"Training data label examples:\", label.numpy())\nprint(\"Validation data shapes:\")\nfor image, label in get_validation_dataset().take(3):\n    print(image.numpy().shape, label.numpy().shape)\nprint(\"Validation data label examples:\", label.numpy())\nprint(\"Test data shapes:\")\nfor image, idnum in get_test_dataset().take(3):\n    print(image.numpy().shape, idnum.numpy().shape)\nprint(\"Test data IDs:\", idnum.numpy().astype('U')) # U=unicode string","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Peek at training data\ntraining_dataset = get_training_dataset()\ntraining_dataset = training_dataset.unbatch().batch(20)\ntrain_batch = iter(training_dataset)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# run this cell again for next set of images\ndisplay_batch_of_images(next(train_batch))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# peer at test data\ntest_dataset = get_test_dataset()\ntest_dataset = test_dataset.unbatch().batch(20)\ntest_batch = iter(test_dataset)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# run this cell again for next set of images\ndisplay_batch_of_images(next(test_batch))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Custom model definition","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# Enable this if you want to use `EfficientNetB7` model\n\n# !pip install -q efficientnet\n# from efficientnet.tfkeras import EfficientNetB7","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class Flower_Classifier(tf.keras.models.Model):\n    \n    def __init__(self):\n\n        super(Flower_Classifier, self).__init__()\n        \n        self.image_embedding_layers = []\n        \n        self.image_embedding_layers.append(Xception(weights='imagenet', include_top=False, input_shape=(*IMAGE_SIZE, 3)))\n        self.image_embedding_layers.append(ResNet152V2(weights='imagenet', include_top=False, input_shape=(*IMAGE_SIZE, 3)))\n        self.image_embedding_layers.append(InceptionResNetV2(weights='imagenet', include_top=False, input_shape=(*IMAGE_SIZE, 3)))\n        \n        # self.image_embedding_layers.append(DenseNet201(weights='imagenet', include_top=False ,input_shape=(*IMAGE_SIZE, 3)))\n        # self.image_embedding_layers.append(EfficientNetB7(weights='imagenet', include_top=False ,input_shape=(*IMAGE_SIZE, 3)))\n        \n        self.pooling_layer = tf.keras.layers.GlobalAveragePooling2D()\n\n        self.layer_normalization_layers = []\n        self.prob_dist_layers = []\n        for model_idx, image_embedding_layer in enumerate(self.image_embedding_layers):\n            \n            self.layer_normalization_layers.append(tf.keras.layers.LayerNormalization(epsilon=1e-6))\n            \n            self.prob_dist_layers.append(\n                tf.keras.layers.Dense(\n                    len(CLASSES),\n                    activation='softmax',\n                    name='prob_dist_{}'.format(model_idx)\n                )\n            )\n            \n        # These values are obtained by previous training.\n        kernel_init = tf.constant_initializer(np.array([0.86690587, 1.0948032, 1.1121726])) \n        bias_init = tf.constant_initializer(np.array([-0.13309559, 0.09480964, 0.11218266]))            \n            \n        self.prob_dist_weight = tf.keras.layers.Dense(\n            len(self.image_embedding_layers), activation=\"softmax\",\n            kernel_initializer=kernel_init,\n            bias_initializer=bias_init,\n            name='prob_dist_weight'\n        )\n\n    def call(self, inputs, training=False):\n        \n        all_model_outputs = []\n        for i in range(len(self.image_embedding_layers)):\n            \n            embedding = self.image_embedding_layers[i](inputs, training=training)\n            pooling = self.pooling_layer(embedding, training=training)\n\n            pooling_normalized = self.layer_normalization_layers[i](pooling, training=training)\n            \n            # shape = (batch_size, nb_classes)\n            model_output = self.prob_dist_layers[i](pooling_normalized, training=training)\n\n            all_model_outputs.append(model_output)\n               \n        # stack the outputs from different models\n        # shape = (batch_size, nb_models, nb_classes)\n        all_model_outputs = tf.stack(all_model_outputs, axis=1)\n        \n        # Get the model's current prob_dist_weights\n        # shape = (1, nb_models)\n        prob_dist_weight = self.prob_dist_weight(tf.constant(1, shape=(1, 1)), training=training)\n\n        # Get the weighted prob_dist\n        # shape = (batch_size, 1, nb_classes)\n        prob_dist = tf.linalg.matmul(prob_dist_weight, all_model_outputs)\n        \n        # Remove axis 1\n        # shape = (batch_size, nb_classess)\n        prob_dist = prob_dist[:, 0, :]\n        \n        return prob_dist\n\n\nwith strategy.scope():\n    \n    flower_classifier = Flower_Classifier()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Custom learning schedule","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"class CustomExponentialDecaySchedule(tf.keras.optimizers.schedules.ExponentialDecay):\n    \n    def __init__(self,\n      initial_learning_rate,\n      decay_steps,\n      decay_rate,\n      staircase=False,\n      cycle=False,\n      name=None,        \n      num_warmup_steps=1000):\n        \n        # Since we have a custom __call__() method, we pass cycle=False when calling `super().__init__()` and\n        # in self.__call__(), we simply do `step = step % self.decay_steps` to have cyclic behavior.\n        super(CustomExponentialDecaySchedule, self).__init__(initial_learning_rate, decay_steps - num_warmup_steps, decay_rate, staircase, name=name)\n        \n        self.num_warmup_steps = num_warmup_steps\n        \n        self.cycle = tf.constant(cycle, dtype=tf.bool)\n        \n    def __call__(self, step):\n        \"\"\" `step` is actually the step index, starting at 0.\n        \"\"\"\n        \n        # For cyclic behavior\n        step = tf.cond(self.cycle and step >= self.decay_steps, lambda: step % self.decay_steps, lambda: step)\n        \n        # learning_rate = super(CustomExponentialDecaySchedule, self).__call__(step, war)\n\n        # Copy (including the comments) from original bert optimizer with minor change.\n        # Ref: https://github.com/google-research/bert/blob/master/optimization.py#L25\n        \n        # Implements linear warmup: if global_step < num_warmup_steps, the\n        # learning rate will be `global_step / num_warmup_steps * init_lr`.\n        if self.num_warmup_steps > 0:\n            \n            steps_int = tf.cast(step, tf.int32)\n            warmup_steps_int = tf.constant(self.num_warmup_steps, dtype=tf.int32)\n\n            steps_float = tf.cast(steps_int, tf.float32)\n            warmup_steps_float = tf.cast(warmup_steps_int, tf.float32)\n\n            # The first training step has index (`step`) 0.\n            # The original code use `steps_float / warmup_steps_float`, which gives `warmup_percent_done` being 0,\n            # and causing `learning_rate` = 0, which is undesired.\n            # For this reason, we use `(steps_float + 1) / warmup_steps_float`.\n            # At `step = warmup_steps_float - 1`, i.e , at the `warmup_steps_float`-th step, \n            #`learning_rate` is `self.initial_learning_rate`.\n            warmup_percent_done = (steps_float + 1) / warmup_steps_float\n            \n            warmup_learning_rate = self.initial_learning_rate * warmup_percent_done\n\n            is_warmup = tf.cast(steps_int < warmup_steps_int, tf.float32)\n\n            learning_rate = super(CustomExponentialDecaySchedule, self).__call__(steps_int - warmup_steps_int)\n\n            learning_rate = ((1.0 - is_warmup) * learning_rate + is_warmup * warmup_learning_rate)\n                        \n        return learning_rate\n    \n\nwith strategy.scope():\n    \n    # number of training steps\n    decay_steps = int(NUM_TRAINING_IMAGES * EPOCHS / BATCH_SIZE)\n\n    num_warmup_steps = int(NUM_TRAINING_IMAGES * WARMUP_EPOCHS / BATCH_SIZE)\n    \n    print(\"decay_steps = {}\".format(decay_steps))\n    print(\"num_warmup_steps = {}\".format(num_warmup_steps))\n    \n    learning_rate = CustomExponentialDecaySchedule(\n        initial_learning_rate=1e-4,\n        decay_steps=decay_steps,\n        decay_rate=0.1,\n        cycle=False,\n        name=None,\n        num_warmup_steps=num_warmup_steps\n)\n\n%matplotlib inline\nif decay_steps <= 20000:\n    xs = tf.range(decay_steps)\n    ys = [learning_rate(x) for x in xs]\n    plt.plot(xs, ys)\n    plt.ylabel(\"Learning Rate\")\n    plt.xlabel(\"Train Step\")\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Optimizer","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    \n    optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Define loss function","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.python.ops import clip_ops\nfrom tensorflow.python.framework import constant_op\n\n\ndef _constant_to_tensor(x, dtype):\n    return constant_op.constant(x, dtype=dtype)\n\n\nwith strategy.scope():\n\n    num_classes = len(CLASSES)\n    \n    # About why we set `reduction` to 'none', please check this tutorial\n    # https://www.tensorflow.org/tutorials/distribute/custom_training#define_the_loss_function\n    # In particular, read the paragraph\n    #     <<If using tf.keras.losses classes (as in the example below), the loss reduction needs to be explicitly specified to be one of NONE or SUM. AUTO and SUM_OVER_BATCH_SIZE are disallowed when used with tf.distribute.Strategy.>>\n    \n    loss_object = tf.keras.losses.CategoricalCrossentropy(from_logits=False, reduction='none', label_smoothing=0.1)\n\n    def loss_function(labels, prob_dists, sample_weights=None):\n\n        if not sample_weights:\n            sample_weights = 1.0\n\n        # While trained with BATCH_SIZE = 8 * strategy.num_replicas_in_sync, I got `nan` values.\n        # Since we pass probability distribution to `CategoricalCrossentropy` with `from_logits` = False,\n        # which has numerical unstability issue,\n        # we use the same trick in the source code to avoid such unstabiltiy.\n        epsilon_ = _constant_to_tensor(tf.keras.backend.epsilon(), prob_dists.dtype.base_dtype)\n        prob_dists = clip_ops.clip_by_value(prob_dists, epsilon_, 1 - epsilon_)\n        \n        labels = tf.keras.backend.one_hot(labels, num_classes)\n        \n        loss = loss_object(labels, prob_dists)\n        \n        # About why we use `tf.nn.compute_average_loss`, please check this tutorial\n        # https://www.tensorflow.org/tutorials/distribute/custom_training#define_the_loss_function\n        \n        loss = tf.nn.compute_average_loss(loss, global_batch_size=BATCH_SIZE)\n\n        return loss","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Define metrics\n## (used to record loss values and accuracy)","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_metrics(name):\n\n    loss = tf.keras.metrics.Mean(name=f'{name}_loss')\n    acc = tf.keras.metrics.SparseCategoricalAccuracy(name=f'{name}_acc')\n    \n    return loss, acc\n\n\nwith strategy.scope():\n    \n    train_loss_obj, train_acc_obj = get_metrics(\"train\")\n    valid_loss_obj, valid_acc_obj = get_metrics(\"valid\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Define Training / Validation / Test steps","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"train_input_signature = [\n    tf.TensorSpec(shape=(None, None, None, None), dtype=tf.float32),\n    tf.TensorSpec(shape=(None,), dtype=tf.int32)\n]\n\n# They have the same input format\nvalid_input_signature = train_input_signature\n\ntest_input_signature = [\n    tf.TensorSpec(shape=(None, None, None, None), dtype=tf.float32)\n]\n\nwith strategy.scope():\n\n    @tf.function(input_signature=train_input_signature)\n    def train_step(images, labels):\n\n        with tf.GradientTape() as tape:\n\n            prob_dists = flower_classifier(images, training=True)\n            loss = loss_function(labels, prob_dists)\n            train_acc_obj(labels, prob_dists)\n\n        gradients = tape.gradient(loss, flower_classifier.trainable_variables)\n        \n        gradients, global_norm = tf.clip_by_global_norm(\n            gradients,\n            clip_norm=1.0\n        )\n        \n        optimizer.apply_gradients(zip(gradients, flower_classifier.trainable_variables))\n\n        return loss\n\n    @tf.function\n    def distributed_train_step(inputs):\n\n        (images, labels) = inputs\n        loss = strategy.experimental_run_v2(train_step, args=(images, labels))\n        \n        return loss\n\n    @tf.function(input_signature=valid_input_signature)\n    def valid_step(images, labels):\n\n        prob_dists = flower_classifier(images, training=False)\n        loss = loss_function(labels, prob_dists, sample_weights=None)\n        valid_acc_obj(labels, prob_dists)\n        \n        return loss, prob_dists\n\n\n    @tf.function\n    def distributed_valid_step(inputs):\n\n        (images, labels) = inputs\n        loss, prob_dists = strategy.experimental_run_v2(valid_step, args=(images, labels))\n     \n        return loss, prob_dists\n\n    \n    @tf.function(input_signature=test_input_signature)\n    def test_step(images):\n\n        prob_dists = flower_classifier(images, training=False)\n\n        return prob_dists\n\n    \n    @tf.function\n    def distributed_test_step(inputs):\n\n        images = inputs\n        prob_dists = strategy.experimental_run_v2(test_step, args=(images,))\n\n        return prob_dists","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Distributed datasets","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"validation_dataset = get_validation_dataset(ordered=True)\nvalidation_dist_dataset = strategy.experimental_distribute_dataset(validation_dataset)\n\ntest_dataset = get_test_dataset(ordered=True)\ntest_image_dataset = test_dataset.map(lambda image, idnum: image)\ntest_dist_dataset = strategy.experimental_distribute_dataset(test_image_dataset)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Save the labels","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"labels_ds = validation_dataset.map(lambda image, label: label).unbatch()\ncm_correct_labels = next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES))).numpy() # get everything as one batch\n\n# Save correct labels\nwith open(\"correct_labels\", \"w\", encoding=\"UTF-8\") as fp:\n    np.savetxt(fp, cm_correct_labels, delimiter=',', fmt='%10.6f')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Training / Validation / Prediction","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"history = {\n    \"train_loss\": [],\n    \"valid_loss\": [],\n    \"train_acc\": [],\n    \"valid_acc\": [],\n    \"valid_f1\": [],\n    \"valid_precision\": [],\n    \"valid_recall\": [],\n    \"model_coefs\": []\n}\n\nprint(\"start training at {}\".format(datetime.datetime.now()))\n\nfor epoch in range(EPOCHS):\n    \n    epoch_start_time = datetime.datetime.now()\n\n    # We need to shuffle the training dataset in every epoch.\n    # I don't know if there is a better way than the following way.\n    training_dataset = get_training_dataset()\n    training_dist_dataset = strategy.experimental_distribute_dataset(training_dataset)\n    \n    train_loss_obj.reset_states()\n    train_acc_obj.reset_states()\n    valid_loss_obj.reset_states()\n    valid_acc_obj.reset_states()\n    \n    for batch_idx, inputs in enumerate(training_dist_dataset):\n                \n        batch_start_time = datetime.datetime.now()\n        \n        # See explaination below in validation part.\n        per_replica_train_loss = distributed_train_step(inputs)\n        train_loss = tf.stack(per_replica_train_loss.values, axis=0)\n        train_loss = tf.math.reduce_sum(train_loss)\n        train_loss_obj(train_loss)        \n        \n        batch_end_time = datetime.datetime.now()\n        batch_elapsed_time = (batch_end_time - batch_start_time).total_seconds()\n        \n        if (batch_idx + 1) % 50 == 0:\n            \n            # print training results\n            print('Epoch {} | Batch {} | Timing {}'.format(epoch + 1, batch_idx + 1, batch_elapsed_time))\n            print('Train Loss: {:.6f}'.format(train_loss_obj.result()))\n            print('Train  Acc: {:.6f}'.format(train_acc_obj.result()))\n            print('Model Coef: {}'.format(flower_classifier.prob_dist_weight(tf.constant(1, shape=(1, 1))).numpy()[0]))\n            print(\"-\" * 40)\n            \n    history['train_loss'].append(train_loss_obj.result())        \n    history['train_acc'].append(train_acc_obj.result())        \n        \n    # print training results\n    print('\\nEpoch {}'.format(epoch + 1))\n    print('Train Loss: {:.6f}'.format(train_loss_obj.result()))\n    print('Train  Acc: {:.6f}'.format(train_acc_obj.result()))\n\n    print('\\nComputing valid predictions...')\n    \n    all_valid_preds = []\n    for batch_idx, inputs in enumerate(validation_dist_dataset):\n    \n        \"\"\"\n        # The return values of `strategy.experimental_run_v2 ` are actually `PerReplica` objects.\n        # For valid_step we defined above, the return value is a tuple of 2 `PerReplica` object.\n        # The 2nd element in the return value is for valid_preds, and it looks like. \n        \n        PerReplica:{\n            0 /job:worker/replica:0/task:0/device:TPU:0: tf.Tensor(..., shape=(16, 104), dtype=float32),\n            1 /job:worker/replica:0/task:0/device:TPU:0: tf.Tensor(..., shape=(16, 104), dtype=float32),\n            ...\n            7 /job:worker/replica:0/task:0/device:TPU:0: tf.Tensor(..., shape=(16, 104), dtype=float32)\n        }\n        \n        # The 1st element in the return value is for valid_loss. It's similar to the above, but just scalar.\n        \n        So we have to convert each of them to a single tf.Tensor manually.\n        \n        Remark: Maybe there is a method to do this automatically. If you find it, let me know!\n        \"\"\"\n        per_replica_valid_results = distributed_valid_step(inputs)\n        per_replica_valid_loss, per_replica_valid_preds = per_replica_valid_results\n        \n        valid_preds = tf.concat(per_replica_valid_preds.values, axis=0)\n        valid_preds = valid_preds.numpy()        \n   \n        all_valid_preds.append(valid_preds)\n\n        valid_loss = tf.stack(per_replica_valid_loss.values, axis=0)\n        valid_loss = tf.math.reduce_sum(valid_loss)\n        valid_loss_obj(valid_loss)\n    \n    # print validation results\n    print('\\nEpoch {}'.format(epoch + 1))\n    print('Valid Loss: {:.6f}'.format(valid_loss_obj.result()))\n    print('Valid  Acc: {:.6f}'.format(valid_acc_obj.result()))\n    \n    history['valid_loss'].append(valid_loss_obj.result())        \n    history['valid_acc'].append(valid_acc_obj.result())     \n    \n    # Make the whole valid predictions as a numpy array\n    all_valid_preds = np.concatenate(all_valid_preds, axis=0, out=None)\n\n    # Save valid predictions\n    with open(\"valid_preds_epoch_{}\".format(epoch), \"w\", encoding=\"UTF-8\") as fp:\n        np.savetxt(fp, all_valid_preds, delimiter=',', fmt='%10.6f')\n\n    cm_predictions = np.argmax(all_valid_preds, axis=-1)\n    f1 = f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)), average='macro')\n    precision = precision_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)), average='macro')\n    recall = recall_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)), average='macro')    \n\n    print('\\nf1       : {:.6f}'.format(f1))\n    print('precision: {:.6f}'.format(precision))\n    print('recall   : {:.6f}'.format(recall))    \n    \n    history['valid_f1'].append(f1)        \n    history['valid_precision'].append(precision)\n    history['valid_recall'].append(recall)\n    \n    history['model_coefs'].append(flower_classifier.prob_dist_weight(tf.constant(1, shape=(1, 1))).numpy()[0])\n    \n    epoch_end_time = datetime.datetime.now()\n    epoch_elapsed_time = (epoch_end_time - epoch_start_time).total_seconds()        \n    print('\\nTime taken for 1 epoch: {} secs'.format(epoch_elapsed_time))\n    print(\"\\n\" + \"=\" * 80 + \"\\n\")\n    \nprint('Computing predictions...')\nprediction_start_time = datetime.datetime.now()\n\nall_test_preds = []\nfor batch_idx, inputs in enumerate(test_dist_dataset):\n    \n    per_replica_test_preds = distributed_test_step(inputs)\n\n    test_preds = tf.concat(per_replica_test_preds.values, axis=0)\n    test_preds = test_preds.numpy()        \n\n    all_test_preds.append(test_preds)\n    \n# Make the whole test predictions as a numpy array\nall_test_preds = np.concatenate(all_test_preds, axis=0, out=None)\n\n# Save test predictions\nwith open(\"test_preds\", \"w\", encoding=\"UTF-8\") as fp:\n    np.savetxt(fp, all_test_preds, delimiter=',', fmt='%10.6f')\n    \nprint('Computing predictions finished.')\n\nprediction_end_time = datetime.datetime.now()\nprediction_elapsed_time = (prediction_end_time - prediction_start_time).total_seconds()        \nprint('\\nTime taken for prediction: {} secs'.format(prediction_elapsed_time))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"display_training_curves(history['train_loss'], history['valid_loss'], 'loss', 211)\ndisplay_training_curves(history['train_acc'], history['valid_acc'], 'accuracy', 212)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Confusion matrix","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"for epoch in range(EPOCHS - 1, EPOCHS):\n    \n    # Load valid predictions\n    with open(\"valid_preds_epoch_{}\".format(epoch), \"r\", encoding=\"UTF-8\") as fp:\n        cm_probabilities = np.loadtxt(fp, delimiter=',')\n        \n    cm_predictions = np.argmax(cm_probabilities, axis=-1)\n    \n    print(\"Epoch {}\\n\".format(epoch))\n    print(\"Correct   labels: \", cm_correct_labels.shape, cm_correct_labels)\n    print(\"Predicted labels: \", cm_predictions.shape, cm_predictions)\n    \n    cmat = confusion_matrix(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)))\n    score = f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)), average='macro')\n    precision = precision_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)), average='macro')\n    recall = recall_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)), average='macro')\n    #cmat = (cmat.T / cmat.sum(axis=1)).T # normalized\n    display_confusion_matrix(cmat, score, precision, recall)\n    print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))\n    print(\"-\"  * 80)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Save confusion matrices","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# Save confusion matrix\nwith open(\"confusion_matrix\", \"w\", encoding=\"UTF-8\") as fp:\n    np.savetxt(fp, cmat, delimiter=',', fmt='%d')\n\ncmat_normalized = (cmat.T / cmat.sum(axis=1)).T # normalized\nwith open(\"confusion_matrix_normalized\", \"w\", encoding=\"UTF-8\") as fp:\n    np.savetxt(fp, cmat_normalized, delimiter=',', fmt='%d')\n    \nprint(cmat_normalized)\n\ndisplay_confusion_matrix(cmat_normalized, score, precision, recall)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Plot scores","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def display_scores(f1, precision, recall, title, subplot):\n    if subplot%10==1: # set up the subplots on the first call\n        plt.subplots(figsize=(10,10), facecolor='#F0F0F0')\n        plt.tight_layout()\n    ax = plt.subplot(subplot)\n    ax.set_facecolor('#F8F8F8')\n    ax.plot(f1)\n    ax.plot(precision)\n    ax.plot(recall)\n    ax.set_title('model '+ title)\n    ax.set_ylabel(title)\n    #ax.set_ylim(0.28,1.05)\n    ax.set_xlabel('epoch')\n    ax.legend(['f1', 'precision', 'recall'])\n        \ndisplay_scores(history['valid_f1'], history['valid_precision'], history['valid_recall'], 'score', 211)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Plot model coefficients","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def display_model_coefs(model_coefficients, title, subplot):\n    \n    model_coefficients = np.transpose(np.array(model_coefficients))\n    \n    if subplot%10==1: # set up the subplots on the first call\n        plt.subplots(figsize=(10,10), facecolor='#F0F0F0')\n        plt.tight_layout()\n    ax = plt.subplot(subplot)\n    ax.set_facecolor('#F8F8F8')\n    for model_coef in model_coefficients:\n        ax.plot(model_coef)\n\n    ax.set_title('model '+ title)\n    ax.set_ylabel(title)\n    #ax.set_ylim(0.28,1.05)\n    ax.set_xlabel('epoch')\n    ax.legend(['model_coefs_{}'.format(idx) for idx in range(len(flower_classifier.image_embedding_layers))])\n        \ndisplay_model_coefs(history['model_coefs'], \"model_coefs\", 211)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Predictions","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# Load test predictions\nwith open(\"test_preds\", \"r\", encoding=\"UTF-8\") as fp:\n    probabilities = np.loadtxt(fp, delimiter=',')\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='')\n!head submission.csv","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!ls -l","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}