{"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":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-07-21T13:44:31.311476Z","iopub.execute_input":"2022-07-21T13:44:31.312195Z","iopub.status.idle":"2022-07-21T13:44:31.443171Z","shell.execute_reply.started":"2022-07-21T13:44:31.31203Z","shell.execute_reply":"2022-07-21T13:44:31.441901Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns","metadata":{"execution":{"iopub.status.busy":"2022-07-21T13:44:31.477753Z","iopub.execute_input":"2022-07-21T13:44:31.478318Z","iopub.status.idle":"2022-07-21T13:44:32.842557Z","shell.execute_reply.started":"2022-07-21T13:44:31.478273Z","shell.execute_reply":"2022-07-21T13:44:32.841328Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import re,os","metadata":{"execution":{"iopub.status.busy":"2022-07-21T13:44:32.844851Z","iopub.execute_input":"2022-07-21T13:44:32.846131Z","iopub.status.idle":"2022-07-21T13:44:32.853423Z","shell.execute_reply.started":"2022-07-21T13:44:32.846072Z","shell.execute_reply":"2022-07-21T13:44:32.851745Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import math","metadata":{"execution":{"iopub.status.busy":"2022-07-21T13:44:32.855295Z","iopub.execute_input":"2022-07-21T13:44:32.855858Z","iopub.status.idle":"2022-07-21T13:44:32.869343Z","shell.execute_reply.started":"2022-07-21T13:44:32.855806Z","shell.execute_reply":"2022-07-21T13:44:32.867591Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf","metadata":{"execution":{"iopub.status.busy":"2022-07-21T13:44:32.872884Z","iopub.execute_input":"2022-07-21T13:44:32.87368Z","iopub.status.idle":"2022-07-21T13:44:37.776077Z","shell.execute_reply.started":"2022-07-21T13:44:32.873569Z","shell.execute_reply":"2022-07-21T13:44:37.774577Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping\nfrom tensorflow.keras.layers import AveragePooling2D, GlobalAveragePooling2D,GlobalMaxPooling2D\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.layers import Dropout\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.applications import ResNet50,DenseNet201,EfficientNetB6\nfrom tensorflow.keras.layers import Input,Concatenate\nfrom tensorflow.keras.layers import Flatten\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.models import Model","metadata":{"execution":{"iopub.status.busy":"2022-07-21T13:44:37.777911Z","iopub.execute_input":"2022-07-21T13:44:37.77876Z","iopub.status.idle":"2022-07-21T13:44:38.533263Z","shell.execute_reply.started":"2022-07-21T13:44:37.778719Z","shell.execute_reply":"2022-07-21T13:44:38.532078Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import glob","metadata":{"execution":{"iopub.status.busy":"2022-07-21T13:44:38.53551Z","iopub.execute_input":"2022-07-21T13:44:38.536556Z","iopub.status.idle":"2022-07-21T13:44:38.543565Z","shell.execute_reply.started":"2022-07-21T13:44:38.536499Z","shell.execute_reply":"2022-07-21T13:44:38.541963Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n!pip install -q efficientnet\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__)\nAUTO = tf.data.experimental.AUTOTUNE","metadata":{"execution":{"iopub.status.busy":"2022-07-21T13:44:38.546598Z","iopub.execute_input":"2022-07-21T13:44:38.548532Z","iopub.status.idle":"2022-07-21T13:44:53.071015Z","shell.execute_reply.started":"2022-07-21T13:44:38.54847Z","shell.execute_reply":"2022-07-21T13:44:53.069357Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# This is basically -1\nAUTO = tf.data.experimental.AUTOTUNE\n# Detect hardware, return appropriate distribution strategy\ntry:\n    # Cluster Resolver for Google Cloud TPUs.\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    print('Running on TPU ', tpu.master())\nexcept ValueError:\n    tpu = None\n    \nif tpu:\n    # Connects to the given cluster.\n    tf.config.experimental_connect_to_cluster(tpu)\n    # Initialize the TPU devices.\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    # TPU distribution strategy implementation.\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nelse:\n    strategy = tf.distribute.get_strategy()\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","metadata":{"execution":{"iopub.status.busy":"2022-07-21T13:44:53.072993Z","iopub.execute_input":"2022-07-21T13:44:53.073562Z","iopub.status.idle":"2022-07-21T13:44:53.092888Z","shell.execute_reply.started":"2022-07-21T13:44:53.073518Z","shell.execute_reply":"2022-07-21T13:44:53.091621Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Configuration\n#BATCH_SIZE = 8 * strategy.num_replicas_in_sync\nWARMUP_EPOCHS = 3\nWARMUP_LEARNING_RATE = 1e-4 * strategy.num_replicas_in_sync\n#EPOCHS = 20\nLEARNING_RATE = 3e-5 * strategy.num_replicas_in_sync\nIMAGE_SIZE = [512, 512] #--- input to the neural network\nEPOCHS = 20\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\nprint('> Batch Size : ', BATCH_SIZE)","metadata":{"execution":{"iopub.status.busy":"2022-07-21T13:44:53.094566Z","iopub.execute_input":"2022-07-21T13:44:53.095254Z","iopub.status.idle":"2022-07-21T13:44:53.10284Z","shell.execute_reply.started":"2022-07-21T13:44:53.095211Z","shell.execute_reply":"2022-07-21T13:44:53.10145Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Data access\nGCS_DS_PATH = KaggleDatasets().get_gcs_path()\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\n\nprint('> No of Classes : ', len(CLASSES))","metadata":{"execution":{"iopub.status.busy":"2022-07-21T13:44:53.109508Z","iopub.execute_input":"2022-07-21T13:44:53.110475Z","iopub.status.idle":"2022-07-21T13:44:55.843595Z","shell.execute_reply.started":"2022-07-21T13:44:53.110412Z","shell.execute_reply":"2022-07-21T13:44:55.842002Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def decode_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3)\n    image = tf.cast(image, tf.float32) / 255.0  # convert image to floats in [0, 1] range\n    image = tf.reshape(image, [*IMAGE_SIZE, 3]) # explicit size needed for TPU\n    return image\n\ndef read_labeled_tfrecord(example):\n    LABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"class\": tf.io.FixedLenFeature([], tf.int64),  # shape [] means single element\n    }\n    example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    label = tf.cast(example['class'], tf.int32)\n    return image, label # returns a dataset of (image, label) pairs\n\ndef read_unlabeled_tfrecord(example):\n    UNLABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"id\": tf.io.FixedLenFeature([], tf.string),  # shape [] means single element\n        # class is missing, this competitions's challenge is to predict flower classes for the test dataset\n    }\n    example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    idnum = example['id']\n    return image, idnum # returns a dataset of image(s)\n\ndef load_dataset(filenames, labeled=True, ordered=False):\n    # Read from TFRecords. For optimal performance, reading from multiple files at once and\n    # disregarding data order. Order does not matter since we will be shuffling the data anyway.\n\n    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False # disable order, increase speed\n\n    dataset = tf.data.TFRecordDataset(filenames, 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() # the training dataset must repeat for several epochs\n    dataset = dataset.shuffle(2048)\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 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)","metadata":{"execution":{"iopub.status.busy":"2022-07-21T13:44:55.84599Z","iopub.execute_input":"2022-07-21T13:44:55.846963Z","iopub.status.idle":"2022-07-21T13:44:55.870451Z","shell.execute_reply.started":"2022-07-21T13:44:55.846894Z","shell.execute_reply":"2022-07-21T13:44:55.86887Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Visualization utility functions\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    \n# Visualize model predictions\ndef dataset_to_numpy_util(dataset, N):\n    dataset = dataset.unbatch().batch(N)\n    for images, labels in dataset:\n        numpy_images = images.numpy()\n        numpy_labels = labels.numpy()\n        break;  \n    return numpy_images, numpy_labels\n\ndef title_from_label_and_target(label, correct_label):\n    label = np.argmax(label, axis=-1)\n    correct = (label == correct_label)\n    return \"{} [{}{}{}]\".format(CLASSES[label], str(correct), ', shoud be ' if not correct else '',\n                                CLASSES[correct_label] if not correct else ''), correct\n\ndef display_one_flower_eval(image, title, subplot, red=False):\n    plt.subplot(subplot)\n    plt.axis('off')\n    plt.imshow(image)\n    plt.title(title, fontsize=14, color='red' if red else 'black')\n    return subplot+1\n\ndef display_9_images_with_predictions(images, predictions, labels):\n    subplot=331\n    plt.figure(figsize=(13,13))\n    for i, image in enumerate(images):\n        title, correct = title_from_label_and_target(predictions[i], labels[i])\n        subplot = display_one_flower_eval(image, title, subplot, not correct)\n        if i >= 8:\n            break;\n              \n    plt.tight_layout()\n    plt.subplots_adjust(wspace=0.1, hspace=0.1)\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2022-07-21T13:44:55.872969Z","iopub.execute_input":"2022-07-21T13:44:55.873792Z","iopub.status.idle":"2022-07-21T13:44:55.906274Z","shell.execute_reply.started":"2022-07-21T13:44:55.87374Z","shell.execute_reply":"2022-07-21T13:44:55.90476Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)\n\nNUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)\n\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\n\nprint('Dataset: \\n training images : {}, \\n validation images : {}, \\n unlabeled test images : {}'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))\nprint('Steps per Epoch : ',STEPS_PER_EPOCH)","metadata":{"execution":{"iopub.status.busy":"2022-07-21T13:44:55.908815Z","iopub.execute_input":"2022-07-21T13:44:55.909345Z","iopub.status.idle":"2022-07-21T13:44:55.926956Z","shell.execute_reply.started":"2022-07-21T13:44:55.909295Z","shell.execute_reply":"2022-07-21T13:44:55.925585Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Training data shapes:\")\nfor image, label in get_training_dataset().take(3):\n    print(image.numpy().shape, label.numpy().shape)\nprint(\"Validation data shapes:\")\nfor image, label in get_validation_dataset().take(3):\n    print(image.numpy().shape, label.numpy().shape)\nprint(\"Testing data shapes:\")\nfor image, label in get_test_dataset().take(3):\n    print(image.numpy().shape, label.numpy().shape)","metadata":{"execution":{"iopub.status.busy":"2022-07-21T13:44:55.928729Z","iopub.execute_input":"2022-07-21T13:44:55.930058Z","iopub.status.idle":"2022-07-21T13:45:09.745073Z","shell.execute_reply.started":"2022-07-21T13:44:55.929996Z","shell.execute_reply":"2022-07-21T13:45:09.742886Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Peek at training data\ntraining_dataset = get_training_dataset()\ntrn_dataset = training_dataset.unbatch().batch(20)\ntrain_batch = iter(trn_dataset)\ndisplay_batch_of_images(next(train_batch))","metadata":{"execution":{"iopub.status.busy":"2022-07-21T13:45:09.74742Z","iopub.execute_input":"2022-07-21T13:45:09.748975Z","iopub.status.idle":"2022-07-21T13:45:20.607021Z","shell.execute_reply.started":"2022-07-21T13:45:09.748873Z","shell.execute_reply":"2022-07-21T13:45:20.604885Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Peek at Validation data\nvalidation_dataset = get_validation_dataset()\nval_dataset = validation_dataset.unbatch().batch(20)\nval_batch = iter(val_dataset)\ndisplay_batch_of_images(next(val_batch))","metadata":{"execution":{"iopub.status.busy":"2022-07-21T13:45:20.609431Z","iopub.execute_input":"2022-07-21T13:45:20.610465Z","iopub.status.idle":"2022-07-21T13:45:24.889843Z","shell.execute_reply.started":"2022-07-21T13:45:20.610406Z","shell.execute_reply":"2022-07-21T13:45:24.887968Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Peek at Test data\ntest_dataset = get_test_dataset()\ntst_dataset = test_dataset.unbatch().batch(20)\ntst_batch = iter(tst_dataset)\ndisplay_batch_of_images(next(tst_batch))","metadata":{"execution":{"iopub.status.busy":"2022-07-21T13:45:24.892096Z","iopub.execute_input":"2022-07-21T13:45:24.892579Z","iopub.status.idle":"2022-07-21T13:45:29.018602Z","shell.execute_reply.started":"2022-07-21T13:45:24.892536Z","shell.execute_reply":"2022-07-21T13:45:29.017532Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Learning rate schedule for TPU, GPU and CPU.\n# Using an LR ramp up because fine-tuning a pre-trained model.\n# Starting with a high LR would break the pre-trained weights.\n\nLR_START = 0.00001\nLR_MAX = 0.00005 * strategy.num_replicas_in_sync\nLR_MIN = 0.00001\nLR_RAMPUP_EPOCHS = 5\nLR_SUSTAIN_EPOCHS = 0\nLR_EXP_DECAY = .8\n\ndef lrfn(epoch):\n    if epoch < LR_RAMPUP_EPOCHS:\n        lr = (LR_MAX - LR_START) / LR_RAMPUP_EPOCHS * epoch + LR_START\n    elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:\n        lr = LR_MAX\n    else:\n        lr = (LR_MAX - LR_MIN) * LR_EXP_DECAY**(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]))\n","metadata":{"execution":{"iopub.status.busy":"2022-07-21T13:45:29.020081Z","iopub.execute_input":"2022-07-21T13:45:29.020967Z","iopub.status.idle":"2022-07-21T13:45:29.234727Z","shell.execute_reply.started":"2022-07-21T13:45:29.020914Z","shell.execute_reply":"2022-07-21T13:45:29.232972Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n\nfrom tensorflow.keras.applications import DenseNet201\n\nwith strategy.scope():\n    rnet = DenseNet201(\n        input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3),\n        weights='imagenet',\n        include_top=False\n    )\nrnet.trainable = True\n\nmodel = tf.keras.Sequential([\n        rnet,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    ])\n        \nmodel.compile(\n    optimizer=tf.keras.optimizers.Adam(lr=0.0001),\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy']\n)\n\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2022-07-21T13:45:29.236701Z","iopub.execute_input":"2022-07-21T13:45:29.237294Z","iopub.status.idle":"2022-07-21T13:45:38.600445Z","shell.execute_reply.started":"2022-07-21T13:45:29.237242Z","shell.execute_reply":"2022-07-21T13:45:38.598745Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\nimport efficientnet.tfkeras as efn\n\n# Need this line so Google will recite some incantations\n# for Turing to magically load the model onto the TPU\nwith strategy.scope():\n    enet = efn.EfficientNetB7(\n        input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3),\n        weights='imagenet',\n        include_top=False\n    )\n    \n    enet.trainable = True\n\n    model = tf.keras.Sequential([\n        enet,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    ])\n            \nmodel.compile(\n    optimizer=tf.keras.optimizers.Adam(lr=0.0001),\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy']\n)\n\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2022-07-21T13:45:38.602522Z","iopub.execute_input":"2022-07-21T13:45:38.602968Z","iopub.status.idle":"2022-07-21T13:45:52.418087Z","shell.execute_reply.started":"2022-07-21T13:45:38.602931Z","shell.execute_reply":"2022-07-21T13:45:52.41625Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tf.keras.utils.plot_model(model, show_shapes=True)\n","metadata":{"execution":{"iopub.status.busy":"2022-07-21T13:45:52.420099Z","iopub.execute_input":"2022-07-21T13:45:52.42103Z","iopub.status.idle":"2022-07-21T13:45:53.216754Z","shell.execute_reply.started":"2022-07-21T13:45:52.420982Z","shell.execute_reply":"2022-07-21T13:45:53.214513Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"EPOCHS = 16\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\n\nhistory = model.fit(\n    training_dataset,\n    validation_data=validation_dataset,\n    epochs=EPOCHS,\n    steps_per_epoch=STEPS_PER_EPOCH,\n    callbacks=[lr_callback],\n)","metadata":{"execution":{"iopub.status.busy":"2022-07-21T13:45:53.2196Z","iopub.execute_input":"2022-07-21T13:45:53.220272Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}