{"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 Dependencies\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nimport math, re, os\nimport pandas as pd\nimport numpy as np\nimport random\nimport tensorflow as tf\nimport tensorflow_addons as tfa\n\nprint(\"Tensorflow version \" + tf.__version__)","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","id":"ymb3ZtWLr_ad","outputId":"3d0e7df3-f63b-42df-b733-a2a3a8fbd942","execution":{"iopub.status.busy":"2022-05-05T01:29:40.096934Z","iopub.execute_input":"2022-05-05T01:29:40.097429Z","iopub.status.idle":"2022-05-05T01:29:48.502181Z","shell.execute_reply.started":"2022-05-05T01:29:40.097315Z","shell.execute_reply":"2022-05-05T01:29:48.500651Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Find number of TPU cores for setup --> determines batch size\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\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    tpu_strat = tf.distribute.experimental.TPUStrategy(tpu)\nelse:\n    tpu_strat = tf.distribute.get_strategy() \n    \nREPLICAS = tpu_strat.num_replicas_in_sync\n\nprint(\"REPLICAS: \", REPLICAS) #Number of TPU cores available for use","metadata":{"id":"ZZcXFKx3r_ag","outputId":"eb1eaa1c-8605-41c1-e7d6-5616cbb08070","execution":{"iopub.status.busy":"2022-05-05T01:29:52.583149Z","iopub.execute_input":"2022-05-05T01:29:52.583509Z","iopub.status.idle":"2022-05-05T01:29:58.702233Z","shell.execute_reply.started":"2022-05-05T01:29:52.583472Z","shell.execute_reply":"2022-05-05T01:29:58.701179Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Getting Path for Kaggle Dataset\nfrom kaggle_datasets import KaggleDatasets\n\ninitial_path = KaggleDatasets().get_gcs_path('tpu-getting-started')\nprint(initial_path)","metadata":{"id":"LLxiHFB4r_ah","outputId":"a2b99c20-a61d-4d62-807e-b92dabc54ed1","execution":{"iopub.status.busy":"2022-05-05T01:30:04.482826Z","iopub.execute_input":"2022-05-05T01:30:04.483731Z","iopub.status.idle":"2022-05-05T01:30:04.942728Z","shell.execute_reply.started":"2022-05-05T01:30:04.483679Z","shell.execute_reply":"2022-05-05T01:30:04.941679Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Reading Training, Validation and Testing Images\n\nIMAGE_SIZE = [512, 512] #size of image\nWIDTH = IMAGE_SIZE[0]\nHEIGHT = IMAGE_SIZE[1]\nCHANNELS = 3 # RGB colors\nBATCH_SIZE = 16 * REPLICAS #Some Number Multiplied with # of TPU Cores so all of them can be at use\n                           #Batch Size = 128 --> each TPU core will work with 16 images at a time\n\nfile_path = initial_path + '/tfrecords-jpeg-512x512'\nAUTO = tf.data.experimental.AUTOTUNE\n\ntrain_file = tf.io.gfile.glob(file_path + '/train/*.tfrec')\nvalid_file = tf.io.gfile.glob(file_path + '/val/*.tfrec')\ntest_file = tf.io.gfile.glob(file_path + '/test/*.tfrec') \n\n# target/types of flowers in dataset --> 104 total\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 - 103\n\n# Helper Functions to Read Data\ndef decode_image(data_image):\n    image = tf.image.decode_jpeg(data_image, channels=CHANNELS)\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 \n\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO)\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","metadata":{"id":"YKob3ivXr_ah","execution":{"iopub.status.busy":"2022-05-05T01:31:14.109492Z","iopub.execute_input":"2022-05-05T01:31:14.109854Z","iopub.status.idle":"2022-05-05T01:31:14.378006Z","shell.execute_reply.started":"2022-05-05T01:31:14.109814Z","shell.execute_reply":"2022-05-05T01:31:14.377012Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Functions for Data Augmentation Techniques\n\n#random seed\nseed = 123\n\ndef random_flip_lr(image, label):\n    # Random flip left right\n    image = tf.image.random_flip_left_right(image)\n    return image, label\n\ndef random_brightness(image, label):\n    # Change Brightness\n    image = tf.image.random_brightness(image, 0.6, seed = seed)\n    return image, label\n\ndef random_saturation(image, label):\n    # Change Saturation\n    image = tf.image.random_saturation(image, 3, 5, seed = seed)\n    return image, label\n    \ndef random_contrast(image, label):\n    # Change Constrast\n    image = tf.image.random_contrast(image, 0.3, 0.5, seed = seed)\n    return image, label\n\ndef random_hue(image, label):\n    # Change Hue\n    image = tf.image.random_hue(image, 0.5, seed = seed)\n    return image, label\n    \ndef make_blur(image, label):\n    # Blur Image\n    image = tfa.image.mean_filter2d(image, filter_shape = 10)\n    return image, label\n\ndef random_flip_all(image, label):\n    # Random flip in all directions (left right up down)\n    image = tf.image.random_flip_left_right(image, seed = seed)\n    image = tf.image.random_flip_up_down(image, seed = seed)\n    return image, label\n\n# Randomly Blockout Parts of Some Images (images to have blockouts are chosen at random)\ndef random_blockout(image, label, sw=0.1, sh=0.2, rl=0.4):\n    decider=random.random()\n    if decider>=0.3:\n        \n        total_area = tf.cast(HEGHT*WIDTH, tf.float32)\n\n        erase_width = tf.cast(tf.round(tf.sqrt(total_area * sw * rl)), tf.int32)\n        erase_height = tf.cast(tf.round(tf.sqrt(total_area * sh / rl)), tf.int32)\n\n        erase_height_2 = tf.minimum(erase_height, HEIGHT)\n        erase_width_2 = tf.minimum(erase_length,WIDTH)\n\n        erase_height_3 = tf.random.uniform(shape=[], minval=erase_height, maxval=erase_height_2, dtype=tf.int32)\n        erase_width_3 = tf.random.uniform(shape=[], minval=erase_width, maxval=erase_width_2, dtype=tf.int32)\n\n        erase_area = tf.zeros(shape=[erase_height_3, erase_width_3, CHANNELS])\n        erase_area = tf.cast(erase_area, tf.uint8)\n\n        pad_height = HEIGHT - erase_height_3\n        pad_top = tf.random.uniform(shape=[], minval=0, maxval=pad_height, dtype=tf.int32)\n        pad_bottom = pad_height - pad_top\n\n        pad_width = WIDTH - erase_width_3\n        pad_left = tf.random.uniform(shape=[], minval=0, maxval=pad_width, dtype=tf.int32)\n        pad_right = pad_width - pad_left\n\n        erase_mask = tf.pad([erase_area], [[0,0],[pad_top, pad_bottom], [pad_left, pad_right], [0,0]], constant_values=1)\n        erase_mask = tf.squeeze(erase_mask, axis=0)\n        erased_image = tf.multiply(tf.cast(image,tf.float32), tf.cast(erase_mask, tf.float32))\n\n        return tf.cast(erased_image, image.dtype), label\n    else:\n        return tf.cast(image, image.dtype), label\n    \n\n# Read in Train Dataset and Apply Augmentation Techniques\ndef generate_train_df():\n    df = load_dataset(train_file, labeled=True)\n    \n    # DATA AUGMENTATION\n    #simple augmentation (random flipping) --> worked best\n    df = df.map(random_flip_lr, num_parallel_calls=AUTO)\n    \n    # tried other augmentation methods -- didn't work out as well\n#     df = df.map(random_brightness, num_parallel_calls=AUTO)\n#     df = df.map(random_saturation, num_parallel_calls=AUTO)\n#     df = df.map(random_contrast, num_parallel_calls=AUTO)\n#     df = df.map(random_hue, num_parallel_calls=AUTO)\n#     df = df.map(make_blur, num_parallel_calls=AUTO)\n#     df = df.map(random_blockout, num_parallel_calls=AUTO)\n    \n    df = df.repeat()\n    df = df.shuffle(2048)\n    df = df.batch(BATCH_SIZE)\n    df = df.prefetch(AUTO)\n    return df\n\n# Read in Original Train Dataset for EDA & Visualization purposes\ndef get_original_train(ordered=True):\n    df = load_dataset(train_file, labeled=True, ordered=ordered)\n    df = df.batch(BATCH_SIZE)\n    df = df.cache()\n    df = df.prefetch(AUTO)\n    return df\n\n# Read in Validation Dataset\ndef generate_valid_df(ordered=False):\n    df = load_dataset(valid_file, labeled=True, ordered=ordered)\n    df = df.batch(BATCH_SIZE)\n    df = df.cache()\n    df = df.prefetch(AUTO)\n    return df\n\n# Read in Test Dataset\ndef generate_test_df(ordered=False):\n    df = load_dataset(test_file, labeled=False, ordered=ordered)\n    df = df.batch(BATCH_SIZE)\n    df = df.prefetch(AUTO)\n    return df","metadata":{"id":"GEOY8CPYr_aj","execution":{"iopub.status.busy":"2022-05-05T01:35:30.514574Z","iopub.execute_input":"2022-05-05T01:35:30.515185Z","iopub.status.idle":"2022-05-05T01:35:30.545754Z","shell.execute_reply.started":"2022-05-05T01:35:30.515126Z","shell.execute_reply":"2022-05-05T01:35:30.544740Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Exploratory Data Analysis & Data Visualization","metadata":{"id":"gTOud5w4r_ak"}},{"cell_type":"code","source":"# Print Size (Image Count) of Each Dataset\n\n# Train data\noriginal_train = get_original_train()\ntrain_count = np.sum([int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in train_file])\ntrain_labels = next(iter(original_train.unbatch().map(lambda image, label: label).batch(train_count))).numpy()\n\n#valid data\nvalid_data = generate_valid_df()\nvalid_count = np.sum([int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in valid_file])\nvalid_labels = next(iter(valid_data.unbatch().map(lambda image, label: label).batch(valid_count))).numpy()\n\n#test data\ntest_data = generate_test_df()\ntest_count = np.sum([int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in test_file])\n\nprint('Train Images Count:', train_count)\nprint('Validation Images Count:', valid_count)\nprint('Test Images Count:', test_count)","metadata":{"id":"RSCbkECjr_al","execution":{"iopub.status.busy":"2022-05-05T01:36:17.358363Z","iopub.execute_input":"2022-05-05T01:36:17.359162Z","iopub.status.idle":"2022-05-05T01:36:30.825472Z","shell.execute_reply.started":"2022-05-05T01:36:17.359119Z","shell.execute_reply":"2022-05-05T01:36:30.824105Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Visualization Utility Functions\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,\n                                     # 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\n    # 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\n    # 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()","metadata":{"id":"TRXmItYvr_al","execution":{"iopub.status.busy":"2022-05-05T01:36:49.748617Z","iopub.execute_input":"2022-05-05T01:36:49.749177Z","iopub.status.idle":"2022-05-05T01:36:49.768940Z","shell.execute_reply.started":"2022-05-05T01:36:49.749140Z","shell.execute_reply":"2022-05-05T01:36:49.767064Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Display some training data images\ndisplay_batch_of_images(next(iter(original_train.unbatch().batch(9))))","metadata":{"id":"SZm4ju4fr_am","execution":{"iopub.status.busy":"2022-05-05T01:39:01.233032Z","iopub.execute_input":"2022-05-05T01:39:01.233444Z","iopub.status.idle":"2022-05-05T01:39:03.398600Z","shell.execute_reply.started":"2022-05-05T01:39:01.233402Z","shell.execute_reply":"2022-05-05T01:39:03.397249Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Display some validation data images\ndisplay_batch_of_images(next(iter(valid_data.unbatch().batch(9))))","metadata":{"id":"8M82R5tEr_am","execution":{"iopub.status.busy":"2022-05-05T01:39:35.220581Z","iopub.execute_input":"2022-05-05T01:39:35.220922Z","iopub.status.idle":"2022-05-05T01:39:37.125798Z","shell.execute_reply.started":"2022-05-05T01:39:35.220890Z","shell.execute_reply":"2022-05-05T01:39:37.123883Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Display some test data images\ndisplay_batch_of_images(next(iter(test_data.unbatch().batch(9))))","metadata":{"id":"DvLrWJtnr_an","execution":{"iopub.status.busy":"2022-05-05T01:39:44.095600Z","iopub.execute_input":"2022-05-05T01:39:44.095950Z","iopub.status.idle":"2022-05-05T01:39:55.298526Z","shell.execute_reply.started":"2022-05-05T01:39:44.095913Z","shell.execute_reply":"2022-05-05T01:39:55.297304Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Display some training data images after augmentation (flip left/right)\nnew_train = generate_train_df()\ndisplay_batch_of_images(next(iter(new_train.unbatch().batch(9))))","metadata":{"id":"uK1JPchJr_an","execution":{"iopub.status.busy":"2022-05-05T01:39:59.519499Z","iopub.execute_input":"2022-05-05T01:39:59.519878Z","iopub.status.idle":"2022-05-05T01:40:03.490880Z","shell.execute_reply.started":"2022-05-05T01:39:59.519832Z","shell.execute_reply":"2022-05-05T01:40:03.489425Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# See Frequency of Classes in Dataset - Checking for Class Balance/Imbalance\ntrain_label_counter = np.asarray([[label, (train_labels == index).sum()] for index, label in enumerate(CLASSES)])\nvalid_label_counter = np.asarray([[label, (valid_labels == index).sum()] for index, label in enumerate(CLASSES)])\n\ntrain_label_counter = pd.DataFrame(train_label_counter)\nvalid_label_counter = pd.DataFrame(valid_label_counter)\n\ntrain_label_counter[1] = train_label_counter[1].astype('float')\nvalid_label_counter[1] = valid_label_counter[1].astype('float')\n\n\nfig, (ax1, ax2) = plt.subplots(2, 1, figsize=(20, 60))\n\nax1 = sns.barplot(x=train_label_counter[1], y=train_label_counter[0], order=CLASSES, ax=ax1, palette='coolwarm')\nax1.set_title('Train', fontsize=25)\nax1.tick_params(labelsize=16)\n\nax2 = sns.barplot(x=valid_label_counter[1], y=valid_label_counter[0], order=CLASSES, ax=ax2, palette='YlOrBr')\nax2.set_title('Validation', fontsize=25)\nax2.tick_params(labelsize=16)\n\nplt.show()","metadata":{"id":"IGzrqVAfr_an","execution":{"iopub.status.busy":"2022-05-05T01:40:16.991415Z","iopub.execute_input":"2022-05-05T01:40:16.991737Z","iopub.status.idle":"2022-05-05T01:40:21.626969Z","shell.execute_reply.started":"2022-05-05T01:40:16.991704Z","shell.execute_reply":"2022-05-05T01:40:21.626112Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Building the Model","metadata":{"id":"yyIaDDqOr_an"}},{"cell_type":"code","source":"EPOCHS = 30 \n# Learning Rate Schedule for Fine Tuning #\ndef exponential_lr(epoch,\n                   start_lr = 0.00001, min_lr = 0.00001, max_lr = 0.00005,\n                   rampup_epochs = 5, sustain_epochs = 0,\n                   exp_decay = 0.8):\n\n    def lr(epoch, start_lr, min_lr, max_lr, rampup_epochs, sustain_epochs, exp_decay):\n        # linear increase from start to rampup_epochs\n        if epoch < rampup_epochs:\n            lr = ((max_lr - start_lr) /\n                  rampup_epochs * epoch + start_lr)\n        # constant max_lr during sustain_epochs\n        elif epoch < rampup_epochs + sustain_epochs:\n            lr = max_lr\n        # exponential decay towards min_lr\n        else:\n            lr = ((max_lr - min_lr) *\n                  exp_decay**(epoch - rampup_epochs - sustain_epochs) +\n                  min_lr)\n        return lr\n    return lr(epoch,\n              start_lr,\n              min_lr,\n              max_lr,\n              rampup_epochs,\n              sustain_epochs,\n              exp_decay)\n\nlr_callback = tf.keras.callbacks.LearningRateScheduler(exponential_lr, verbose=True)\n\nrng = [i for i in range(EPOCHS)]\ny = [exponential_lr(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":{"id":"N3oMyJW6r_ao","execution":{"iopub.status.busy":"2022-05-05T01:41:54.668278Z","iopub.execute_input":"2022-05-05T01:41:54.668600Z","iopub.status.idle":"2022-05-05T01:41:54.917146Z","shell.execute_reply.started":"2022-05-05T01:41:54.668565Z","shell.execute_reply":"2022-05-05T01:41:54.916177Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Creating the Model\nwith tpu_strat.scope(): \n    # Models we tested\n    #pretrained_model = tf.keras.applications.VGG16\n    #pretrained_model = tf.keras.applications.MobileNetV2\n    #pretrained_model = tf.keras.applications.InceptionResNetV2\n        \n    #best performing model\n    pretrained_model = tf.keras.applications.ResNet101V2(\n        include_top=False , # remove top layer\n        weights='imagenet', # pre-trained weights on imagenet dataset\n        input_shape=[*IMAGE_SIZE, CHANNELS]\n    )\n    \n    pretrained_model.trainable = True # if True retrain the weights\n    \n    model = tf.keras.Sequential([\n        pretrained_model, #Base pretrained on ImageNet to extract features from images\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax') #softmax for multiple classification\n    ])","metadata":{"id":"wwN9Wy6Gr_ao","execution":{"iopub.status.busy":"2022-05-05T01:43:15.782970Z","iopub.execute_input":"2022-05-05T01:43:15.783950Z","iopub.status.idle":"2022-05-05T01:43:39.006578Z","shell.execute_reply.started":"2022-05-05T01:43:15.783895Z","shell.execute_reply":"2022-05-05T01:43:39.005456Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(\n    optimizer='nadam', #compared with adam optimizer --> nadam performed better\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy'],\n)\n\n# Visualizing Model\nmodel.summary()\n\ntf.keras.utils.plot_model(model, show_shapes=True)","metadata":{"id":"bxT6I9sJr_ap","execution":{"iopub.status.busy":"2022-05-05T01:43:52.412083Z","iopub.execute_input":"2022-05-05T01:43:52.412815Z","iopub.status.idle":"2022-05-05T01:43:53.886367Z","shell.execute_reply.started":"2022-05-05T01:43:52.412767Z","shell.execute_reply":"2022-05-05T01:43:53.884891Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Print Data Shapes\nprint(\"Training:\", new_train)\nprint (\"Validation:\", valid_data)\nprint(\"Test:\", test_data)","metadata":{"id":"WERLYBpxr_ap","execution":{"iopub.status.busy":"2022-05-05T01:44:20.456187Z","iopub.execute_input":"2022-05-05T01:44:20.456554Z","iopub.status.idle":"2022-05-05T01:44:20.466487Z","shell.execute_reply.started":"2022-05-05T01:44:20.456511Z","shell.execute_reply":"2022-05-05T01:44:20.465251Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Fit Model","metadata":{"id":"t8lyAixAr_ap"}},{"cell_type":"code","source":"# fitting the model\nearly_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=3)\nSTEPS_PER_EPOCH = train_count // BATCH_SIZE\n\nhistory = model.fit(\n    new_train,\n    validation_data=valid_data,\n    epochs=EPOCHS,\n    steps_per_epoch=STEPS_PER_EPOCH,\n    callbacks=[lr_callback, early_stopping],\n)","metadata":{"id":"KRXcDgMSr_ap","execution":{"iopub.status.busy":"2022-05-05T01:44:30.328960Z","iopub.execute_input":"2022-05-05T01:44:30.330091Z","iopub.status.idle":"2022-05-05T01:51:42.417101Z","shell.execute_reply.started":"2022-05-05T01:44:30.330006Z","shell.execute_reply":"2022-05-05T01:51:42.416236Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Helper Function to Display Model Results\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.'])","metadata":{"id":"BkB9cWqWr_aq","execution":{"iopub.status.busy":"2022-05-05T01:51:52.092066Z","iopub.execute_input":"2022-05-05T01:51:52.093337Z","iopub.status.idle":"2022-05-05T01:51:52.101596Z","shell.execute_reply.started":"2022-05-05T01:51:52.093268Z","shell.execute_reply":"2022-05-05T01:51:52.100220Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Plot Model Accuracy and Loss with respect to Train and Validation Datasets\ndisplay_training_curves(\n    history.history['loss'],\n    history.history['val_loss'],\n    'loss',\n    211,\n)\ndisplay_training_curves(\n    history.history['sparse_categorical_accuracy'],\n    history.history['val_sparse_categorical_accuracy'],\n    'accuracy',\n    212,\n)","metadata":{"id":"MV39Fcm_r_aq","execution":{"iopub.status.busy":"2022-05-05T01:51:56.529199Z","iopub.execute_input":"2022-05-05T01:51:56.529542Z","iopub.status.idle":"2022-05-05T01:51:57.134488Z","shell.execute_reply.started":"2022-05-05T01:51:56.529504Z","shell.execute_reply":"2022-05-05T01:51:57.133280Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Make predictions and submission to Kaggle\ntest_ds = generate_test_df(ordered=True) # since we are splitting the dataset and iterating separately on images and ids, order matters.\n\nprint('Computing predictions...')\ntest_images_ds = test_ds.map(lambda image, idnum: image)\nprobabilities = model.predict(test_images_ds)\npredictions = np.argmax(probabilities, axis=-1)\nprint(predictions)\n\nprint('Generating submission.csv file...')\ntest_ids_ds = test_ds.map(lambda image, idnum: idnum).unbatch()\ntest_ids = next(iter(test_ids_ds.batch(test_count))).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","metadata":{"id":"B_IVzVier_aq","execution":{"iopub.status.busy":"2022-05-05T02:01:31.232822Z","iopub.execute_input":"2022-05-05T02:01:31.233182Z","iopub.status.idle":"2022-05-05T02:02:03.416434Z","shell.execute_reply.started":"2022-05-05T02:01:31.233149Z","shell.execute_reply":"2022-05-05T02:02:03.415657Z"},"trusted":true},"execution_count":null,"outputs":[]}]}