{"cells":[{"metadata":{},"cell_type":"markdown","source":"###### Version 2 Log -> \n\n1) Mixed Precision Added <br>\n2) Custom Model Training"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# Necessary imports \nimport 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\nprint(\"Tensorflow version: -> \", tf.__version__)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"AUTO = tf.data.experimental.AUTOTUNE","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"try:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver.connect()\n    \n    strategy = tf.distribute.TPUStrategy(tpu)\nexcept ValueError:\n    strategy = tf.distribute.MirroredStrategy()\n    \n\nprint(\"Number of Accelerators : \", strategy.num_replicas_in_sync)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from kaggle_datasets import KaggleDatasets\nGCS_DS_PATH = KaggleDatasets().get_gcs_path('flower-classification-with-tpus')\nprint(GCS_DS_PATH)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Configuration"},{"metadata":{"trusted":true},"cell_type":"code","source":"IMAGE_SIZE = [331, 331]\nEPOCHS = 13 \nBATCH_SIZE = 16 * strategy.num_replicas_in_sync","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# LR Scheduling\n\n# Learning rate schedule\nLR_START = 0.00001\nLR_MAX = 0.00004 * strategy.num_replicas_in_sync\nLR_MIN = 0.00001\nLR_RAMPUP_EPOCHS = 3\nLR_SUSTAIN_EPOCHS = 0\nLR_EXP_DECAY = .7","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"GCS_PATH_SELECT = {\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}","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"GCS_PATH = GCS_PATH_SELECT[IMAGE_SIZE[0]]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"TRAINING_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')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"CLASSES = ['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":{"trusted":true},"cell_type":"code","source":"@tf.function\ndef lrfn(epoch):\n    if float(epoch) < LR_RAMPUP_EPOCHS:\n        lr = (LR_MAX - LR_START) / LR_RAMPUP_EPOCHS * float(epoch) + LR_START\n    elif float(epoch) < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:\n        lr = LR_MAX\n    else:\n        lr = (LR_MAX - LR_MIN) * LR_EXP_DECAY**(float(epoch) - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS) + LR_MIN\n    return lr\n    \nlr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=True)\n\nrng = [i for i in range(EPOCHS)]\ny = [lrfn(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]))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### Datasets"},{"metadata":{"trusted":true},"cell_type":"code","source":"def decode_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels = 3)\n    image = tf.reshape(image, [*IMAGE_SIZE, 3])\n    return image\n\n\ndef read_labeled_tfrecord(example):\n    \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    return image, idnum\n\n\ndef load_dataset(filenames, labeled = True, ordered = False):\n    ignore_order = tf.data.Options()\n    \n    if not ordered:\n        ignore_order.experimental_deterministic = False\n        \n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads = AUTO)\n    \n    dataset = dataset.with_options(ignore_order)\n    dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls = AUTO)\n    \n    return dataset\n\ndef data_augment(image, label):\n    image = tf.image.random_flip_left_right(image)\n    return image, label\n\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()\n    \n    \n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO)\n    \n    \n    return dataset\n\n\n\ndef get_validation_dataset(ordered = False, repeated = False):\n    dataset = load_dataset(VALIDATION_FILENAMES, labeled = True, ordered = ordered)\n    if repeated:\n        dataset = dataset.repeat()\n        dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache()\n    dataset = dataset.prefetch(AUTO)\n    \n    return dataset\n\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)\n    \n    return dataset\n\n\ndef count_data_items(filenames):\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    return np.sum(n)\n\n\ndef int_div_round_up(a, b):\n    return (a + b - 1) // b\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)\n\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\n#VALIDATION_STEPS = -(-NUM_VALIDATION_IMAGES // BATCH_SIZE)\nVALIDATION_STEPS = int_div_round_up(NUM_VALIDATION_IMAGES, BATCH_SIZE)\n\n#TEST_STEPS = -(-NUM_TEST_IMAGES // BATCH_SIZE)\nTEST_STEPS = int_div_round_up(NUM_TEST_IMAGES, BATCH_SIZE)\n\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":"#### Model Training"},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    pretrained_model = tf.keras.applications.NASNetLarge(weights = 'imagenet', include_top = False)\n    \n    \n    \n    model = tf.keras.Sequential([\n        # convert image format from int [0,255] to the format expected by this model\n        tf.keras.layers.Lambda(lambda data: tf.keras.applications.nasnet.preprocess_input(tf.cast(data, tf.float32)), input_shape=[*IMAGE_SIZE, 3]),\n        pretrained_model,\n        # models in tf.keras.applications with include_top=False output a 3D feature map which must be converted to 2D\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    ])\n    \n    model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['sparse_categorical_accuracy'], steps_per_execution = 16)\n    \nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Model Training"},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit(get_training_dataset(), steps_per_epoch = STEPS_PER_EPOCH, epochs = EPOCHS, validation_data = get_validation_dataset(), validation_steps = VALIDATION_STEPS, callbacks = [lr_callback])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### Model Custom Training Loop (Coming soon)"},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    pretrained_model = tf.keras.applications.Xception(weights = 'imagenet', include_top = False, input_shape = [*IMAGE_SIZE, 3])\n    \n    pretrained_model.trainable = True\n    \n    model = tf.keras.Sequential([\n        tf.keras.layers.Lambda(lambda data: tf.keras.applications.xception.preprocess_input(tf.cast(data, tf.float32)), input_shape = [*IMAGE_SIZE, 3]),\n        pretrained_model,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(len(CLASSES), activation = 'softmax')\n        \n    ])\n    \n    model.summary()\n    \n    \n    class LRSchedule(tf.keras.optimizers.schedules.LearningRateSchedule):\n        def __call__(self, step):\n            return lrfn(epoch = step // STEPS_PER_EPOCH)\n        \n    optimizer = tf.keras.optimizers.Adam(learning_rate = LRSchedule())\n    \n    train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()\n    valid_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()\n    \n    train_loss = tf.keras.metrics.Sum()\n    valid_loss = tf.keras.metrics.Sum()\n    \n    loss_fn = lambda a,b : tf.nn.compute_average_loss(tf.keras.losses.sparse_categorical_crossentropy(a,b), global_batch_size = BATCH_SIZE)\n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"@tf.function \ndef train_step(images, labels):\n    with tf.GradientTape() as tape:\n        probabilities = model(images, training = True)\n        loss = loss_fn(labels, probabilities)\n    grads = tape.gradient(loss, model.trainable_variables)\n    optimizer.apply_gradients(zip(grads, model.trainable_variables))\n    \n    train_accuracy.update_state(labels, probabilities)\n    train_loss.update_state(loss)\n    \n\n@tf.function\ndef valid_step(images, labels):\n    probabilities = model(images, training = False)\n    loss = loss_fn(labels, probabilities)\n    \n    # update metrics\n    valid_accuracy.update_state(labels, probabilities)\n    valid_loss.update_state(loss)\n    \n    \n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### Training Loop"},{"metadata":{"trusted":true},"cell_type":"code","source":"import time","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"start_time = epoch_start_time = time.time()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_dist_ds = strategy.experimental_distribute_dataset(get_training_dataset())\n\nvalid_dist_ds = strategy.experimental_distribute_dataset(get_validation_dataset())\n\nprint(\"Steps per epoch: \", STEPS_PER_EPOCH)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from collections import namedtuple\nHistory = namedtuple('History', 'history')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = History(history = {\"loss\" : [], \"val_loss\" : [], \"sparse_categorical_accuracy\" : [], \"val_sparse_categorical_accuracy\" : []})\n\n\nepoch = 0\n\nfor step, (images, labels) in enumerate(train_dist_ds):\n    strategy.run(train_step, args = (images, labels))\n    print('=', end = '', flush = True)\n    \n    if ((step + 1) // STEPS_PER_EPOCH) > epoch:\n        print('|', end = '', flush = True)\n        \n        for image, labels in valid_dist_ds:\n            strategy.run(valid_step, args = (image, labels))\n            print(\"=\", end = '', flush = True)\n            \n        # metrics\n        history.history['sparse_categorical_accuracy'].append(train_accuracy.result().numpy())\n        history.history['val_sparse_categorical_accuracy'].append(valid_accuracy.result().numpy())\n        \n        epoch_time = time.time() - epoch_start_time\n        print(\"\\nEPOCH {:d}/{:d}\".format(epoch + 1, EPOCHS))\n        print(\"time : {:0.1f}s\".format(epoch + 1, EPOCHS))\n        print(\"loss : {:0.4f}\".format(history.history['loss'][-1]))\n        print(\"accuracy : {:0.4f}\".format(history.history['sparse_categorical_accuracy'][-1]))\n        print(\"val_loss : {:0.4f}\".format(history.history['val_loss'][-1]))\n        print(\"val_acc : {:0.4f}\".format(history.history[\"val_sparse_categorical_accuracy\"][-1]))\n        print(\"lr : {:0.4g}\".format(lrfn(epoch)), flush = True)\n        \n    epoch = (step + 1) // STEPS_PER_EPOCH\n    \n    epoch_start_time = time.time()\n    train_accuracy.reset_states()\n    valid_accuracy.reset_states()\n    \n    valid_loss.reset_states()\n    train_loss.reset_states()\n    \n    if epoch >= EPOCHS:\n        break\n        \n        \nsimple_ctl_training_time = time.time() - start_time \nprint(\"Training Time -> \", simple_ctl_training_time)\n    ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Optimized Model Training"},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    pretrained_model = tf.keras.applications.Xception(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])\n    pretrained_model.trainable = True # False = transfer learning, True = fine-tuning\n    \n    model = tf.keras.Sequential([\n        # convert image format from int [0,255] to the format expected by this model\n        tf.keras.layers.Lambda(lambda data: tf.keras.applications.xception.preprocess_input(tf.cast(data, tf.float32)), input_shape=[*IMAGE_SIZE, 3]),\n        pretrained_model,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    ])\n    model.summary()\n    \n    # Instiate optimizer with learning rate schedule\n    class LRSchedule(tf.keras.optimizers.schedules.LearningRateSchedule):\n        def __call__(self, step):\n            return lrfn(epoch=step//STEPS_PER_EPOCH)\n    optimizer = tf.keras.optimizers.Adam(learning_rate=LRSchedule())\n        \n    # this also works but is not very readable\n    #optimizer = tf.keras.optimizers.Adam(learning_rate=lambda: lrfn(tf.cast(optimizer.iterations, tf.float32)//STEPS_PER_EPOCH))\n    \n    # Instantiate metrics\n    train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()\n    valid_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()\n    train_loss = tf.keras.metrics.Sum()\n    valid_loss = tf.keras.metrics.Sum()\n    \n    # Loss\n    # The recommendation from the Tensorflow custom training loop  documentation is:\n    # loss_fn = lambda a,b: tf.nn.compute_average_loss(tf.keras.losses.sparse_categorical_crossentropy(a,b), global_batch_size=BATCH_SIZE)\n    # https://www.tensorflow.org/tutorials/distribute/custom_training#define_the_loss_function\n    # This works too and shifts all the averaging to the training loop which is easier:\n    loss_fn = tf.keras.losses.sparse_categorical_crossentropy","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"STEPS_PER_TPU_CALL = 99\nVALIDATION_STEPS_PER_TPU_CALL = 29\n\n@tf.function\ndef train_step(data_iter):\n    def train_step_fn(images, labels):\n        with tf.GradientTape() as tape:\n            probabilities = model(images, training=True)\n            loss = loss_fn(labels, probabilities)\n        grads = tape.gradient(loss, model.trainable_variables)\n        optimizer.apply_gradients(zip(grads, model.trainable_variables))\n        \n        #update metrics\n        train_accuracy.update_state(labels, probabilities)\n        train_loss.update_state(loss)\n        \n    # this loop runs on the TPU\n    for _ in tf.range(STEPS_PER_TPU_CALL):\n        strategy.run(train_step_fn, next(data_iter))\n\n@tf.function\ndef valid_step(data_iter):\n    def valid_step_fn(images, labels):\n        probabilities = model(images, training=False)\n        loss = loss_fn(labels, probabilities)\n        \n        # update metrics\n        valid_accuracy.update_state(labels, probabilities)\n        valid_loss.update_state(loss)\n        \n    # this loop runs on the TPU\n    for _ in tf.range(VALIDATION_STEPS_PER_TPU_CALL):\n        strategy.run(valid_step_fn, next(data_iter))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import time\nfrom collections import namedtuple","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"start_time = epoch_start_time = time.time()\n\n# distribute the datset according to the strategy\ntrain_dist_ds = strategy.experimental_distribute_dataset(get_training_dataset())\n# Hitting End Of Dataset exceptions is a problem in this setup. Using a repeated validation set instead.\n# This will introduce a slight inaccuracy because the validation dataset now has some repeated elements.\nvalid_dist_ds = strategy.experimental_distribute_dataset(get_validation_dataset(repeated=True))\n\nprint(\"Training steps per epoch:\", STEPS_PER_EPOCH, \"in increments of\", STEPS_PER_TPU_CALL)\nprint(\"Validation images:\", NUM_VALIDATION_IMAGES,\n      \"Batch size:\", BATCH_SIZE,\n      \"Validation steps:\", NUM_VALIDATION_IMAGES//BATCH_SIZE, \"in increments of\", VALIDATION_STEPS_PER_TPU_CALL)\nprint(\"Repeated validation images:\", int_div_round_up(NUM_VALIDATION_IMAGES, BATCH_SIZE*VALIDATION_STEPS_PER_TPU_CALL)*VALIDATION_STEPS_PER_TPU_CALL*BATCH_SIZE-NUM_VALIDATION_IMAGES)\nHistory = namedtuple('History', 'history')\nhistory = History(history={'loss': [], 'val_loss': [], 'sparse_categorical_accuracy': [], 'val_sparse_categorical_accuracy': []})\n\nepoch = 0\ntrain_data_iter = iter(train_dist_ds) # the training data iterator is repeated and it is not reset\n                                      # for each validation run (same as model.fit)\nvalid_data_iter = iter(valid_dist_ds) # the validation data iterator is repeated and it is not reset\n                                      # for each validation run (different from model.fit whre the\n                                      # recommendation is to use a non-repeating validation dataset)\n\nstep = 0\nepoch_steps = 0\nwhile True:\n    \n    # run training step\n    train_step(train_data_iter)\n    epoch_steps += STEPS_PER_TPU_CALL\n    step += STEPS_PER_TPU_CALL\n    print('=', end='', flush=True)\n\n    # validation run at the end of each epoch\n    if (step // STEPS_PER_EPOCH) > epoch:\n        print('|', end='', flush=True)\n        \n        # validation run\n        valid_epoch_steps = 0\n        for _ in range(int_div_round_up(NUM_VALIDATION_IMAGES, BATCH_SIZE*VALIDATION_STEPS_PER_TPU_CALL)):\n            valid_step(valid_data_iter)\n            valid_epoch_steps += VALIDATION_STEPS_PER_TPU_CALL\n            print('=', end='', flush=True)\n\n        # compute metrics\n        history.history['sparse_categorical_accuracy'].append(train_accuracy.result().numpy())\n        history.history['val_sparse_categorical_accuracy'].append(valid_accuracy.result().numpy())\n        history.history['loss'].append(train_loss.result().numpy() / (BATCH_SIZE*epoch_steps))\n        history.history['val_loss'].append(valid_loss.result().numpy() / (BATCH_SIZE*valid_epoch_steps))\n        \n        # report metrics\n        epoch_time = time.time() - epoch_start_time\n        print('\\nEPOCH {:d}/{:d}'.format(epoch+1, EPOCHS))\n        print('time: {:0.1f}s'.format(epoch_time),\n              'loss: {:0.4f}'.format(history.history['loss'][-1]),\n              'accuracy: {:0.4f}'.format(history.history['sparse_categorical_accuracy'][-1]),\n              'val_loss: {:0.4f}'.format(history.history['val_loss'][-1]),\n              'val_acc: {:0.4f}'.format(history.history['val_sparse_categorical_accuracy'][-1]),\n              'lr: {:0.4g}'.format(lrfn(epoch)),\n              'steps/val_steps: {:d}/{:d}'.format(epoch_steps, valid_epoch_steps), flush=True)\n        \n        # set up next epoch\n        epoch = step // STEPS_PER_EPOCH\n        epoch_steps = 0\n        epoch_start_time = time.time()\n        train_accuracy.reset_states()\n        valid_accuracy.reset_states()\n        valid_loss.reset_states()\n        train_loss.reset_states()\n        if epoch >= EPOCHS:\n            break\n\noptimized_ctl_training_time = time.time() - start_time\nprint(\"OPTIMIZED CTL TRAINING TIME: {:0.1f}s\".format(optimized_ctl_training_time))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"##### Optimized Model Training + Mixed Precision"},{"metadata":{"trusted":true},"cell_type":"code","source":"### Mixed Precision Training\n\nMIXED_PRECISION = True\nXLA_ACCELERATE = True\n\nif MIXED_PRECISION:\n    from tensorflow.keras.mixed_precision import experimental as mixed_precision \n    if tpu: policy = tf.keras.mixed_precision.experimental.Policy('mixed_bfloat16')\n    else: policy = tf.keras.mixed_precision.experimental.Policy(\"float32\")\n        \n    mixed_precision.set_policy(policy)\n    print(\"Mixed Precision enabled\")\n    \nif XLA_ACCELERATE:\n    tf.config.optimizer.set_jit(True)\n    print(\"XLA Enabled\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    pretrained_model = tf.keras.applications.Xception(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])\n    pretrained_model.trainable = True # False = transfer learning, True = fine-tuning\n    \n    model = tf.keras.Sequential([\n        # convert image format from int [0,255] to the format expected by this model\n        tf.keras.layers.Lambda(lambda data: tf.keras.applications.xception.preprocess_input(tf.cast(data, tf.float32)), input_shape=[*IMAGE_SIZE, 3]),\n        pretrained_model,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    ])\n    model.summary()\n    \n    # Instiate optimizer with learning rate schedule\n    class LRSchedule(tf.keras.optimizers.schedules.LearningRateSchedule):\n        def __call__(self, step):\n            return lrfn(epoch=step//STEPS_PER_EPOCH)\n    optimizer = tf.keras.optimizers.Adam(learning_rate=LRSchedule())\n        \n    # this also works but is not very readable\n    #optimizer = tf.keras.optimizers.Adam(learning_rate=lambda: lrfn(tf.cast(optimizer.iterations, tf.float32)//STEPS_PER_EPOCH))\n    \n    # Instantiate metrics\n    train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()\n    valid_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()\n    train_loss = tf.keras.metrics.Sum()\n    valid_loss = tf.keras.metrics.Sum()\n    \n    # Loss\n    # The recommendation from the Tensorflow custom training loop  documentation is:\n    # loss_fn = lambda a,b: tf.nn.compute_average_loss(tf.keras.losses.sparse_categorical_crossentropy(a,b), global_batch_size=BATCH_SIZE)\n    # https://www.tensorflow.org/tutorials/distribute/custom_training#define_the_loss_function\n    # This works too and shifts all the averaging to the training loop which is easier:\n    loss_fn = tf.keras.losses.sparse_categorical_crossentropy","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"STEPS_PER_TPU_CALL = 99\nVALIDATION_STEPS_PER_TPU_CALL = 29\n\n@tf.function\ndef train_step(data_iter):\n    def train_step_fn(images, labels):\n        with tf.GradientTape() as tape:\n            probabilities = model(images, training=True)\n            loss = loss_fn(labels, probabilities)\n        grads = tape.gradient(loss, model.trainable_variables)\n        optimizer.apply_gradients(zip(grads, model.trainable_variables))\n        \n        #update metrics\n        train_accuracy.update_state(labels, probabilities)\n        train_loss.update_state(loss)\n        \n    # this loop runs on the TPU\n    for _ in tf.range(STEPS_PER_TPU_CALL):\n        strategy.run(train_step_fn, next(data_iter))\n\n@tf.function\ndef valid_step(data_iter):\n    def valid_step_fn(images, labels):\n        probabilities = model(images, training=False)\n        loss = loss_fn(labels, probabilities)\n        \n        # update metrics\n        valid_accuracy.update_state(labels, probabilities)\n        valid_loss.update_state(loss)\n        \n    # this loop runs on the TPU\n    for _ in tf.range(VALIDATION_STEPS_PER_TPU_CALL):\n        strategy.run(valid_step_fn, next(data_iter))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import time\nfrom collections import namedtuple","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"start_time = epoch_start_time = time.time()\n\n# distribute the datset according to the strategy\ntrain_dist_ds = strategy.experimental_distribute_dataset(get_training_dataset())\n# Hitting End Of Dataset exceptions is a problem in this setup. Using a repeated validation set instead.\n# This will introduce a slight inaccuracy because the validation dataset now has some repeated elements.\nvalid_dist_ds = strategy.experimental_distribute_dataset(get_validation_dataset(repeated=True))\n\nprint(\"Training steps per epoch:\", STEPS_PER_EPOCH, \"in increments of\", STEPS_PER_TPU_CALL)\nprint(\"Validation images:\", NUM_VALIDATION_IMAGES,\n      \"Batch size:\", BATCH_SIZE,\n      \"Validation steps:\", NUM_VALIDATION_IMAGES//BATCH_SIZE, \"in increments of\", VALIDATION_STEPS_PER_TPU_CALL)\nprint(\"Repeated validation images:\", int_div_round_up(NUM_VALIDATION_IMAGES, BATCH_SIZE*VALIDATION_STEPS_PER_TPU_CALL)*VALIDATION_STEPS_PER_TPU_CALL*BATCH_SIZE-NUM_VALIDATION_IMAGES)\nHistory = namedtuple('History', 'history')\nhistory = History(history={'loss': [], 'val_loss': [], 'sparse_categorical_accuracy': [], 'val_sparse_categorical_accuracy': []})\n\nepoch = 0\ntrain_data_iter = iter(train_dist_ds) # the training data iterator is repeated and it is not reset\n                                      # for each validation run (same as model.fit)\nvalid_data_iter = iter(valid_dist_ds) # the validation data iterator is repeated and it is not reset\n                                      # for each validation run (different from model.fit whre the\n                                      # recommendation is to use a non-repeating validation dataset)\n\nstep = 0\nepoch_steps = 0\nwhile True:\n    \n    # run training step\n    train_step(train_data_iter)\n    epoch_steps += STEPS_PER_TPU_CALL\n    step += STEPS_PER_TPU_CALL\n    print('=', end='', flush=True)\n\n    # validation run at the end of each epoch\n    if (step // STEPS_PER_EPOCH) > epoch:\n        print('|', end='', flush=True)\n        \n        # validation run\n        valid_epoch_steps = 0\n        for _ in range(int_div_round_up(NUM_VALIDATION_IMAGES, BATCH_SIZE*VALIDATION_STEPS_PER_TPU_CALL)):\n            valid_step(valid_data_iter)\n            valid_epoch_steps += VALIDATION_STEPS_PER_TPU_CALL\n            print('=', end='', flush=True)\n\n        # compute metrics\n        history.history['sparse_categorical_accuracy'].append(train_accuracy.result().numpy())\n        history.history['val_sparse_categorical_accuracy'].append(valid_accuracy.result().numpy())\n        history.history['loss'].append(train_loss.result().numpy() / (BATCH_SIZE*epoch_steps))\n        history.history['val_loss'].append(valid_loss.result().numpy() / (BATCH_SIZE*valid_epoch_steps))\n        \n        # report metrics\n        epoch_time = time.time() - epoch_start_time\n        print('\\nEPOCH {:d}/{:d}'.format(epoch+1, EPOCHS))\n        print('time: {:0.1f}s'.format(epoch_time),\n              'loss: {:0.4f}'.format(history.history['loss'][-1]),\n              'accuracy: {:0.4f}'.format(history.history['sparse_categorical_accuracy'][-1]),\n              'val_loss: {:0.4f}'.format(history.history['val_loss'][-1]),\n              'val_acc: {:0.4f}'.format(history.history['val_sparse_categorical_accuracy'][-1]),\n              'lr: {:0.4g}'.format(lrfn(epoch)),\n              'steps/val_steps: {:d}/{:d}'.format(epoch_steps, valid_epoch_steps), flush=True)\n        \n        # set up next epoch\n        epoch = step // STEPS_PER_EPOCH\n        epoch_steps = 0\n        epoch_start_time = time.time()\n        train_accuracy.reset_states()\n        valid_accuracy.reset_states()\n        valid_loss.reset_states()\n        train_loss.reset_states()\n        if epoch >= EPOCHS:\n            break\n\noptimized_ctl_training_time = time.time() - start_time\nprint(\"OPTIMIZED CTL TRAINING TIME: {:0.1f}s\".format(optimized_ctl_training_time))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Generating the confusion matrix"},{"metadata":{"trusted":true},"cell_type":"code","source":"cmdataset = 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(NUM_VALIDATION_IMAGES))).numpy()\n\ncm_probabilities = model.predict(images_ds, steps = VALIDATION_STEPS)\ncm_predictions = np.argmax(cm_probabilities, axis = -1)\n\nprint(\"Correct Labels : \", cm_correct_labels.shape, cm_correct_labels)\nprint(\"Predicted Labels: \", cm_predictions.shape, cm_predictions)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_ds = get_test_dataset(ordered = True)\n\nprint(\"Computing predictions...\")\n\ntest_images_ds = test_ds.map(lambda image, idnum : image)\nprobabilities = model.predict(test_images_ds, steps = TEST_STEPS)\npredictions = np.argmax(probabilities, axis = -1)\nprint(predictions)\n\n\nprint(\"generating submission file\")\ntest_ids_ds = test_ds.map(lambda image, idnum : idnum).unbatch()\n\ntest_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U')\n\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":"","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Notebook in making"},{"metadata":{},"cell_type":"markdown","source":"##### Additions to be made -> \n          1) Mixed Precision + XLA training\n          2) Custom Training loop for faster training."},{"metadata":{"trusted":true},"cell_type":"code","source":"","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}