{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":21154,"databundleVersionId":1243559,"sourceType":"competition"}],"dockerImageVersionId":30646,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# **Import Libraries and Framework**","metadata":{}},{"cell_type":"code","source":"import warnings\nwarnings.filterwarnings(\"ignore\")\nimport tensorflow as tf\nprint(\"Tensorflow Version: \", tf.__version__)\nimport keras\nfrom tensorflow.keras.metrics import F1Score\nimport re, math\nimport numpy as np\nfrom sklearn.utils.class_weight import compute_class_weight\nfrom tensorflow.keras.applications.densenet import DenseNet201\nfrom tensorflow.keras.applications.efficientnet import EfficientNetB7\nfrom tensorflow.keras.applications.efficientnet_v2 import EfficientNetV2L, EfficientNetV2B3\nfrom tensorflow.keras.applications.xception import Xception\nfrom tensorflow.keras.optimizers import Nadam\nfrom tensorflow.keras import backend as K\nfrom kaggle_datasets import KaggleDatasets\nfrom sklearn.metrics import f1_score, precision_score, recall_score, confusion_matrix\nimport matplotlib.pyplot as plt","metadata":{"execution":{"iopub.status.busy":"2024-03-15T01:22:28.046513Z","iopub.execute_input":"2024-03-15T01:22:28.047208Z","iopub.status.idle":"2024-03-15T01:22:42.722545Z","shell.execute_reply.started":"2024-03-15T01:22:28.047172Z","shell.execute_reply":"2024-03-15T01:22:42.721629Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Distribution Strategy**","metadata":{}},{"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    gpus = tf.config.experimental.list_physical_devices('GPU')\n    for gpu in gpus:\n        tf.config.experimental.set_memory_growth(gpu, True)\n        print(gpu)\n    if gpus:\n        strategy = tf.distribute.MirroredStrategy()\n    else:\n        strategy = tf.distribute.get_strategy() # default distribution strategy in Tensorflow. Works on CPU and single GPU.\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","metadata":{"execution":{"iopub.status.busy":"2024-03-15T01:22:42.724119Z","iopub.execute_input":"2024-03-15T01:22:42.724758Z","iopub.status.idle":"2024-03-15T01:22:43.064821Z","shell.execute_reply.started":"2024-03-15T01:22:42.724730Z","shell.execute_reply":"2024-03-15T01:22:43.063687Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Understanding TFRecord Data Structure**","metadata":{}},{"cell_type":"code","source":"# Understanding TFRecord files structure\n\nraw_dataset = tf.data.TFRecordDataset(\"/kaggle/input/tpu-getting-started/tfrecords-jpeg-192x192/val/05-192x192-232.tfrec\")\n\nfor raw_record in raw_dataset.take(1):\n    example = tf.train.Example()\n    example.ParseFromString(raw_record.numpy())\n    print(example)\n    \n# Each records contain several features like class, id, and image.","metadata":{"execution":{"iopub.status.busy":"2024-03-15T01:22:43.066191Z","iopub.execute_input":"2024-03-15T01:22:43.066519Z","iopub.status.idle":"2024-03-15T01:22:43.210019Z","shell.execute_reply.started":"2024-03-15T01:22:43.066493Z","shell.execute_reply":"2024-03-15T01:22:43.209009Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Loading the Comptetion Data**","metadata":{}},{"cell_type":"code","source":"# Get Google Clooud Storage path\nGCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started') # it's like /kaggle/input/tpu-getting-started\nprint(GCS_DS_PATH)","metadata":{"execution":{"iopub.status.busy":"2024-03-15T01:22:43.212838Z","iopub.execute_input":"2024-03-15T01:22:43.213287Z","iopub.status.idle":"2024-03-15T01:22:43.527694Z","shell.execute_reply.started":"2024-03-15T01:22:43.213255Z","shell.execute_reply":"2024-03-15T01:22:43.526763Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMAGE_SIZE = [224, 224]\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\nGCS_PATH = GCS_DS_PATH + '/tfrecords-jpeg-224x224'\n\n# AUTOTUNE automatically chooses the optimal parallelism \n# for tf.data operations like map, batch, prefetch based on runtime hardware.\nAUTO = tf.data.experimental.AUTOTUNE\n\n# Dataset Path\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')\n\n# Flower Classes\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","metadata":{"execution":{"iopub.status.busy":"2024-03-15T01:22:43.529515Z","iopub.execute_input":"2024-03-15T01:22:43.529884Z","iopub.status.idle":"2024-03-15T01:22:43.982707Z","shell.execute_reply.started":"2024-03-15T01:22:43.529851Z","shell.execute_reply":"2024-03-15T01:22:43.981820Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Data Preprocessing Function Definition\n\ndef decode_img(img_data):\n    image = tf.image.decode_jpeg(img_data, channels=3)\n    image = tf.cast(image, tf.float32) / 255.0 # cast image to float32 in range [0, 1]\n    image = tf.reshape(image, [*IMAGE_SIZE, 3]) # reshape image to size 512x512x3, explicit size needed for TPU\n    return image\n    \ndef parse_labeled_data(example_proto):\n    feature_desc = {\n        'class': tf.io.FixedLenFeature([], tf.int64),\n        'image': tf.io.FixedLenFeature([], tf.string)\n    }\n    example = tf.io.parse_single_example(example_proto, feature_desc)\n    image = decode_img(example['image'])\n    label = tf.cast(example['class'], tf.int32)\n    label = tf.one_hot(label, 104)\n    return image, label\n    \ndef parse_unlabeled_data(example_proto):\n    feature_desc = {\n        'id': tf.io.FixedLenFeature([], tf.string),\n        'image': tf.io.FixedLenFeature([], tf.string)\n    }\n    example = tf.io.parse_single_example(example_proto, feature_desc)\n    idnum = example['id']\n    image = decode_img(example['image'])\n    return image, idnum\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    ignore_order = tf.data.Options()\n    if not ordered:\n        # This will make the interleave order non-deterministic, increase speed\n        ignore_order.deterministic = False\n    \n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO) # num_parallel_calls for parallelism\n    dataset = dataset.with_options(ignore_order)\n    dataset = dataset.map(parse_labeled_data if labeled else parse_unlabeled_data, num_parallel_calls=AUTO)\n    # returns (image, class) pair if labeled=True or (image, id) pair if labeled=False\n    return dataset","metadata":{"execution":{"iopub.status.busy":"2024-03-15T01:22:43.984117Z","iopub.execute_input":"2024-03-15T01:22:43.984519Z","iopub.status.idle":"2024-03-15T01:22:43.996553Z","shell.execute_reply.started":"2024-03-15T01:22:43.984479Z","shell.execute_reply":"2024-03-15T01:22:43.995528Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Create Data Pipeline**","metadata":{}},{"cell_type":"code","source":"# Data Augmentation Function\ndef data_augment(label, image):\n    image = tf.image.random_flip_left_right(image)\n    #image = tf.image.random_crop(image, size=[512, 512, 3])\n    image = tf.image.random_contrast(image, lower=0.7, upper=1.4)\n    return image, label \n\n# Training Dataset Loading Function\ndef get_training_dataset():\n    dataset = load_dataset(TRAINING_FILENAMES)\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\n# Validation Dataset Loading Function\ndef get_validation_dataset():\n    dataset = load_dataset(VALIDATION_FILENAMES)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache()\n    dataset = dataset.prefetch(AUTO)\n    return dataset\n\n# Test Dataset Loading Function\ndef get_test_dataset():\n    dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=True)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO)\n    return dataset","metadata":{"execution":{"iopub.status.busy":"2024-03-15T01:22:43.997945Z","iopub.execute_input":"2024-03-15T01:22:43.998319Z","iopub.status.idle":"2024-03-15T01:22:44.011800Z","shell.execute_reply.started":"2024-03-15T01:22:43.998285Z","shell.execute_reply":"2024-03-15T01:22:44.010970Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def count_data_items(filenames):\n    # the number of data items is written in the name of the .tfrec\n    # 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)\nprint('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))","metadata":{"execution":{"iopub.status.busy":"2024-03-15T01:22:44.013055Z","iopub.execute_input":"2024-03-15T01:22:44.013361Z","iopub.status.idle":"2024-03-15T01:22:44.028764Z","shell.execute_reply.started":"2024-03-15T01:22:44.013337Z","shell.execute_reply":"2024-03-15T01:22:44.027934Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    train_ds = get_training_dataset()\n    valid_ds = get_validation_dataset()\n    test_ds = get_test_dataset()\n    \nprint(\"Training:\", train_ds)\nprint(\"Validation:\", valid_ds)\nprint(\"Test:\", test_ds)","metadata":{"execution":{"iopub.status.busy":"2024-03-15T01:22:44.029827Z","iopub.execute_input":"2024-03-15T01:22:44.030128Z","iopub.status.idle":"2024-03-15T01:22:44.577122Z","shell.execute_reply.started":"2024-03-15T01:22:44.030084Z","shell.execute_reply":"2024-03-15T01:22:44.576084Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Explore Data**","metadata":{}},{"cell_type":"markdown","source":"## Checking the Distribution of Each Class","metadata":{}},{"cell_type":"code","source":"count_class = []\nfor i in range(104):\n    count_class.append(0);\n\nds_train = get_training_dataset().unbatch()\ntrain_label = iter(ds_train)\n\nfor i in range(NUM_TRAINING_IMAGES):\n    image, label = next(train_label)\n    count_class[np.argmax(label)] = count_class[np.argmax(label)]+1\n    \nprint(count_class)","metadata":{"execution":{"iopub.status.busy":"2024-03-15T01:22:44.582103Z","iopub.execute_input":"2024-03-15T01:22:44.582410Z","iopub.status.idle":"2024-03-15T01:22:57.697774Z","shell.execute_reply.started":"2024-03-15T01:22:44.582377Z","shell.execute_reply":"2024-03-15T01:22:57.696256Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(sum(count_class) == NUM_TRAINING_IMAGES)","metadata":{"execution":{"iopub.status.busy":"2024-03-15T01:22:57.699505Z","iopub.execute_input":"2024-03-15T01:22:57.700180Z","iopub.status.idle":"2024-03-15T01:22:57.709615Z","shell.execute_reply.started":"2024-03-15T01:22:57.700143Z","shell.execute_reply":"2024-03-15T01:22:57.708605Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Displaying Images ","metadata":{}},{"cell_type":"code","source":"# Convert TensorFlow batch to numpy arrays for labels and images\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: # if it's a byte string (or id)\n        numpy_labels = [None for _ in enumerate(numpy_labels)]\n    return numpy_images, numpy_labels \n\n# Generates a title for display on an image based on the predicted label and the ground truth label\ndef title_from_label_and_target(label, correct_label):\n    if correct_label == None:\n        return CLASSES[label], True\n    correct = (label == correct_label)\n    title = \"{} [{}{}{}]\".format(CLASSES[label], \n                                 'OK' if correct else 'NO', \n                                 u\"\\u2192\" if not correct else '',\n                                 CLASSES[correct_label] if not correct else '')\n    return title, correct\n\n# Displays a single flower image along with its title on a subplot\ndef display_one_flower(image, title, subplot, red=False, titlesize=16):\n    # Set up the subplot\n    plt.subplot(*subplot)\n    plt.axis('off')\n    \n    # Display the flower image\n    plt.imshow(image)\n    \n    # Customize and display the title\n    if len(title) > 0:\n         plt.title(title, \n              fontsize=int(titlesize) if not red else int(titlesize/1.2),\n              color='red' if red else 'black',\n              fontdict={'verticalalignment': 'center'},\n              pad=int(titlesize/1.5))\n    \n    return (subplot[0], subplot[1], subplot[2]+1) # Move to next index\n    \n# Displays every images in databatch\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    # Convert Data\n    images, labels = batch_to_numpy_images_and_labels(databatch)\n    # Data Handling\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 Plot\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    # Getting Titles\n    for i, (image, label) in enumerate(zip(images[:rows*cols], labels[:rows*cols])): # enumerate() returns index and value each element,\n                                                                                     # zip() merge elements of 2 iterable.\n        title = '' if label is None else CLASSES[np.argmax(label)]\n        correct = True\n        if predictions is not None:\n            # Getting title from predicted label and true label\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) # display image and move to next index\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":{"execution":{"iopub.status.busy":"2024-03-15T01:22:57.711072Z","iopub.execute_input":"2024-03-15T01:22:57.711595Z","iopub.status.idle":"2024-03-15T01:22:57.730755Z","shell.execute_reply.started":"2024-03-15T01:22:57.711569Z","shell.execute_reply":"2024-03-15T01:22:57.729912Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Change the batch size for displaying images\nds_iter = iter(train_ds.unbatch().batch(20))","metadata":{"execution":{"iopub.status.busy":"2024-03-15T01:22:57.731872Z","iopub.execute_input":"2024-03-15T01:22:57.732204Z","iopub.status.idle":"2024-03-15T01:22:57.773592Z","shell.execute_reply.started":"2024-03-15T01:22:57.732179Z","shell.execute_reply":"2024-03-15T01:22:57.772434Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Iterating each batch to display every images\none_batch = next(ds_iter)\ndisplay_batch_of_images(one_batch)","metadata":{"execution":{"iopub.status.busy":"2024-03-15T01:22:57.774843Z","iopub.execute_input":"2024-03-15T01:22:57.775141Z","iopub.status.idle":"2024-03-15T01:23:02.148230Z","shell.execute_reply.started":"2024-03-15T01:22:57.775111Z","shell.execute_reply":"2024-03-15T01:23:02.146663Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Displaying Metrics","metadata":{}},{"cell_type":"code","source":"# Displaying accuracy and loss of trained model\ndef display_training_curves(training, validation, title, subplot):\n    # If this is the first call to the function, create a new subplot\n    if subplot % 10 == 1:\n        plt.subplots(figsize=(10, 10), facecolor='#F0F0F0')\n        plt.tight_layout()\n    \n    # Create a subplot with the corresponding number\n    ax = plt.subplot(subplot)\n    \n    # Set the background color of the subplot\n    ax.set_facecolor('#F8F8F8')\n    \n    # Display training and validation curves on the subplot\n    ax.plot(training)\n    ax.plot(validation)\n    \n    # Add information to the subplot\n    ax.set_title('model ' + title)\n    ax.set_ylabel(title)\n    ax.set_xlabel('epoch')\n    \n    # Add a legend for the training and validation curves\n    ax.legend(['train', 'valid'])","metadata":{"execution":{"iopub.status.busy":"2024-03-15T01:23:02.149553Z","iopub.execute_input":"2024-03-15T01:23:02.149870Z","iopub.status.idle":"2024-03-15T01:23:02.157440Z","shell.execute_reply.started":"2024-03-15T01:23:02.149843Z","shell.execute_reply":"2024-03-15T01:23:02.156474Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Defining, Compiling, and Training Model","metadata":{}},{"cell_type":"markdown","source":"## Setting the Class Weight","metadata":{}},{"cell_type":"code","source":"train_label = []\n\nunbatched_data = train_ds.unbatch()\ntrain_iter = iter(unbatched_data)\n\nfor i in range(NUM_TRAINING_IMAGES):\n    image, label = next(train_iter)\n    train_label.append(np.argmax(label))","metadata":{"execution":{"iopub.status.busy":"2024-03-15T01:23:02.158644Z","iopub.execute_input":"2024-03-15T01:23:02.158985Z","iopub.status.idle":"2024-03-15T01:23:13.452953Z","shell.execute_reply.started":"2024-03-15T01:23:02.158957Z","shell.execute_reply":"2024-03-15T01:23:13.451574Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"np.unique(train_label)","metadata":{"execution":{"iopub.status.busy":"2024-03-15T01:23:13.454636Z","iopub.execute_input":"2024-03-15T01:23:13.458204Z","iopub.status.idle":"2024-03-15T01:23:13.483594Z","shell.execute_reply.started":"2024-03-15T01:23:13.458155Z","shell.execute_reply":"2024-03-15T01:23:13.482056Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class_weights = compute_class_weight(class_weight='balanced', classes=np.unique(train_label), y=train_label)","metadata":{"execution":{"iopub.status.busy":"2024-03-15T01:23:13.485105Z","iopub.execute_input":"2024-03-15T01:23:13.486220Z","iopub.status.idle":"2024-03-15T01:23:13.517059Z","shell.execute_reply.started":"2024-03-15T01:23:13.486153Z","shell.execute_reply":"2024-03-15T01:23:13.516047Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Dictionary of Pre-Trained Model","metadata":{}},{"cell_type":"code","source":"# List of Pre-Trained Model\nwith strategy.scope():\n    # Listing pretrained model will be used\n    pretrained = {\n        'DenseNet201': DenseNet201(weights='imagenet', include_top=False, input_shape=[*IMAGE_SIZE, 3]),           # 1\n        'EfficientNetB7': EfficientNetB7(weights='imagenet', include_top=False, input_shape=[*IMAGE_SIZE, 3]),     # 2\n        'EfficientNetV2L': EfficientNetV2L(weights='imagenet', include_top=False, input_shape=[*IMAGE_SIZE, 3]),   # 3\n        'EfficientNetV2B3': EfficientNetV2B3(weights='imagenet', include_top=False, input_shape=[*IMAGE_SIZE, 3]), # 4\n        'Xception': Xception(weights='imagenet', include_top=False, input_shape=[*IMAGE_SIZE, 3])                  # 5\n    }\n    \n    # Setting pre-trained model to un-trainable\n    for pre_model in pretrained:\n        pretrained[pre_model].trainable = False","metadata":{"execution":{"iopub.status.busy":"2024-03-15T01:23:13.518415Z","iopub.execute_input":"2024-03-15T01:23:13.519231Z","iopub.status.idle":"2024-03-15T01:24:07.229267Z","shell.execute_reply.started":"2024-03-15T01:23:13.519187Z","shell.execute_reply":"2024-03-15T01:24:07.228398Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for i in pretrained:\n    print(i)","metadata":{"execution":{"iopub.status.busy":"2024-03-15T01:24:07.230507Z","iopub.execute_input":"2024-03-15T01:24:07.230825Z","iopub.status.idle":"2024-03-15T01:24:07.237385Z","shell.execute_reply.started":"2024-03-15T01:24:07.230785Z","shell.execute_reply":"2024-03-15T01:24:07.234922Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Learning Rate Scheduler","metadata":{}},{"cell_type":"code","source":"# Learning Rate Schedule for Fine Tuning #\n\n# Function to calculate learning rate based on an exponential schedule\ndef exponential_lr(epoch,\n                   start_lr = 0.00001, min_lr = 0.00001, max_lr = 0.00005 * strategy.num_replicas_in_sync,\n                   rampup_epochs = 5, sustain_epochs = 1,\n                   exp_decay = 0.8):\n\n    # Internal function to compute learning rate at each epoch\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\n    # Call the internal function with specified parameters for the current epoch\n    return lr(epoch,\n              start_lr,\n              min_lr,\n              max_lr,\n              rampup_epochs,\n              sustain_epochs,\n              exp_decay)\n\n# Define callback for model training\nlr_callback = tf.keras.callbacks.LearningRateScheduler(exponential_lr, verbose=1)\n\nEPOCHS = 20\nrng = [i for i in range(EPOCHS)]\ny = [exponential_lr(x) for x in rng]\nplt.plot(rng, y)\nprint(\"Learning rate schedule: {:.3} to {:.3} to {:.3}\".format(y[0], max(y), y[-1]))","metadata":{"execution":{"iopub.status.busy":"2024-03-15T01:24:07.238792Z","iopub.execute_input":"2024-03-15T01:24:07.239509Z","iopub.status.idle":"2024-03-15T01:24:07.627971Z","shell.execute_reply.started":"2024-03-15T01:24:07.239473Z","shell.execute_reply":"2024-03-15T01:24:07.626969Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath='model_checkpoint-{epoch:02d}-{val_loss:.2f}.weights.h5',\n                                                 save_weights_only=True,\n                                                 monitor='val_f1_score',\n                                                 mode='max',\n                                                 save_best_only=True,\n                                                 verbose=1)","metadata":{"execution":{"iopub.status.busy":"2024-03-15T01:24:07.629077Z","iopub.execute_input":"2024-03-15T01:24:07.629372Z","iopub.status.idle":"2024-03-15T01:24:07.634544Z","shell.execute_reply.started":"2024-03-15T01:24:07.629348Z","shell.execute_reply":"2024-03-15T01:24:07.633565Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Training Model","metadata":{}},{"cell_type":"code","source":"# Define training epochs\nEPOCHS = 12\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE","metadata":{"execution":{"iopub.status.busy":"2024-03-15T01:24:07.635666Z","iopub.execute_input":"2024-03-15T01:24:07.635939Z","iopub.status.idle":"2024-03-15T01:24:07.646691Z","shell.execute_reply.started":"2024-03-15T01:24:07.635916Z","shell.execute_reply":"2024-03-15T01:24:07.645820Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_history = []\n# Fit Model with Training Data and Validation Data\nwith strategy.scope():\n    model = tf.keras.Sequential([\n        # To a base pretrained on ImageNet to extract features from images...\n        pretrained['DenseNet201'],\n        # ... attach a new head to act as a classifier.\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    ])\n\n    model.compile(\n        optimizer = Nadam(),\n        loss = 'categorical_crossentropy', \n        metrics = ['categorical_accuracy', F1Score(average='macro')]\n    )\n\n    model.summary()\n\n    history = model.fit(\n        train_ds,\n        validation_data = valid_ds,\n        epochs = EPOCHS,\n        steps_per_epoch = STEPS_PER_EPOCH,\n        callbacks = [lr_callback, cp_callback],\n        class_weight=dict(enumerate(class_weights))\n    )\n\n    train_history.append(history)","metadata":{"execution":{"iopub.status.busy":"2024-03-15T01:24:07.647710Z","iopub.execute_input":"2024-03-15T01:24:07.647954Z","iopub.status.idle":"2024-03-15T01:37:25.907750Z","shell.execute_reply.started":"2024-03-15T01:24:07.647933Z","shell.execute_reply":"2024-03-15T01:37:25.906772Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Evaluate Model Predictions","metadata":{}},{"cell_type":"markdown","source":"## Displaying Confusion Matrix","metadata":{}},{"cell_type":"code","source":"from sklearn.metrics import f1_score, precision_score, recall_score, confusion_matrix\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()","metadata":{"execution":{"iopub.status.busy":"2024-03-15T01:37:25.910316Z","iopub.execute_input":"2024-03-15T01:37:25.910629Z","iopub.status.idle":"2024-03-15T01:37:25.920948Z","shell.execute_reply.started":"2024-03-15T01:37:25.910604Z","shell.execute_reply":"2024-03-15T01:37:25.919942Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cmdataset = get_validation_dataset()\nimages_ds = cmdataset.map(lambda image, label: image)\nlabels_ds = cmdataset.map(lambda image, label: label).unbatch()\n\ncm_iter = iter(cmdataset.unbatch().batch(1))\ncm_iter = iter(cmdataset.unbatch().batch(NUM_VALIDATION_IMAGES))\ncm_data = next(cm_iter)\n\ncm_correct_labels = next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES))).numpy()\ncm_target = np.argmax(cm_correct_labels, axis=-1)\ncm_probabilities = model.predict(images_ds)\ncm_predictions = np.argmax(cm_probabilities, axis=-1)\n\nlabels = range(len(CLASSES))\ncmat = confusion_matrix(\n    cm_target,\n    cm_predictions,\n    labels=labels,\n)\ncmat = (cmat.T / cmat.sum(axis=1)).T # normalize","metadata":{"execution":{"iopub.status.busy":"2024-03-15T01:37:25.922510Z","iopub.execute_input":"2024-03-15T01:37:25.923163Z","iopub.status.idle":"2024-03-15T01:37:48.911337Z","shell.execute_reply.started":"2024-03-15T01:37:25.923127Z","shell.execute_reply":"2024-03-15T01:37:48.910257Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cm_predictions","metadata":{"execution":{"iopub.status.busy":"2024-03-15T01:37:48.912805Z","iopub.execute_input":"2024-03-15T01:37:48.913213Z","iopub.status.idle":"2024-03-15T01:37:48.921118Z","shell.execute_reply.started":"2024-03-15T01:37:48.913183Z","shell.execute_reply":"2024-03-15T01:37:48.920122Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cm_target","metadata":{"execution":{"iopub.status.busy":"2024-03-15T01:37:48.927480Z","iopub.execute_input":"2024-03-15T01:37:48.927811Z","iopub.status.idle":"2024-03-15T01:37:48.934939Z","shell.execute_reply.started":"2024-03-15T01:37:48.927785Z","shell.execute_reply":"2024-03-15T01:37:48.933738Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"score = f1_score(\n    cm_target,\n    cm_predictions,\n    labels=labels,\n    average='macro',\n)\nprint(score)\n\nprecision = precision_score(\n    cm_target,\n    cm_predictions,\n    labels=labels,\n    average='macro',\n)\nprint(precision)\n\nrecall = recall_score(\n    cm_target,\n    cm_predictions,\n    labels=labels,\n    average='macro',\n)\nprint(recall)\n\ndisplay_confusion_matrix(cmat, score, precision, recall)","metadata":{"execution":{"iopub.status.busy":"2024-03-15T01:37:48.936589Z","iopub.execute_input":"2024-03-15T01:37:48.936973Z","iopub.status.idle":"2024-03-15T01:37:51.293828Z","shell.execute_reply.started":"2024-03-15T01:37:48.936939Z","shell.execute_reply":"2024-03-15T01:37:51.292767Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.evaluate(valid_ds)","metadata":{"execution":{"iopub.status.busy":"2024-03-15T01:37:51.295407Z","iopub.execute_input":"2024-03-15T01:37:51.295736Z","iopub.status.idle":"2024-03-15T01:38:05.279153Z","shell.execute_reply.started":"2024-03-15T01:37:51.295708Z","shell.execute_reply":"2024-03-15T01:38:05.278143Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Second Pre-Trained Model: Xception","metadata":{}},{"cell_type":"code","source":"with strategy.scope():\n    model2 = tf.keras.Sequential([\n        # To a base pretrained on ImageNet to extract features from images...\n        pretrained['Xception'],\n        # ... attach a new head to act as a classifier.\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    ])\n\n    model2.compile(\n        optimizer = Nadam(),\n        loss = 'categorical_crossentropy', \n        metrics = ['categorical_accuracy', F1Score(average='macro')]\n    )\n\n    model2.summary()\n\n    history = model2.fit(\n        train_ds,\n        validation_data = valid_ds,\n        epochs = EPOCHS,\n        steps_per_epoch = STEPS_PER_EPOCH,\n        callbacks = [lr_callback, cp_callback],\n        class_weight=dict(enumerate(class_weights))\n    )\n\n    train_history.append(history)","metadata":{"execution":{"iopub.status.busy":"2024-03-15T01:38:05.280376Z","iopub.execute_input":"2024-03-15T01:38:05.280690Z","iopub.status.idle":"2024-03-15T01:46:53.384496Z","shell.execute_reply.started":"2024-03-15T01:38:05.280663Z","shell.execute_reply":"2024-03-15T01:46:53.383187Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model2.evaluate(valid_ds)","metadata":{"execution":{"iopub.status.busy":"2024-03-15T01:46:53.386915Z","iopub.execute_input":"2024-03-15T01:46:53.387792Z","iopub.status.idle":"2024-03-15T01:47:03.397134Z","shell.execute_reply.started":"2024-03-15T01:46:53.387754Z","shell.execute_reply":"2024-03-15T01:47:03.396240Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Ensemble Model: DenseNet201 + Xception","metadata":{}},{"cell_type":"code","source":"probabilities_ens = (model.predict(images_ds) + model2.predict(images_ds)) / 2\npredictions_ens = np.argmax(probabilities_ens, axis=-1)","metadata":{"execution":{"iopub.status.busy":"2024-03-15T01:47:03.418458Z","iopub.execute_input":"2024-03-15T01:47:03.419012Z","iopub.status.idle":"2024-03-15T01:47:25.977383Z","shell.execute_reply.started":"2024-03-15T01:47:03.418983Z","shell.execute_reply":"2024-03-15T01:47:25.976146Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"score = f1_score(\n    cm_target,\n    predictions_ens,\n    labels=labels,\n    average='macro',\n)\nprint(score)","metadata":{"execution":{"iopub.status.busy":"2024-03-15T01:47:25.979041Z","iopub.execute_input":"2024-03-15T01:47:25.980398Z","iopub.status.idle":"2024-03-15T01:47:25.991707Z","shell.execute_reply.started":"2024-03-15T01:47:25.980367Z","shell.execute_reply":"2024-03-15T01:47:25.990592Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Displaying How Loss and Metrics Progressed During Training","metadata":{}},{"cell_type":"code","source":"for i in range(1):\n    # Displaying model loss\n    display_training_curves(\n        train_history[i].history['loss'],\n        train_history[i].history['val_loss'],\n        'loss',\n        311,\n    )\n\n    # Displaying model accuracy\n    display_training_curves(\n        train_history[i].history['categorical_accuracy'],\n        train_history[i].history['val_categorical_accuracy'],\n        'accuracy',\n        312,\n    )\n    \n    display_training_curves(\n        train_history[i].history['f1_score'],\n        train_history[i].history['val_f1_score'],\n        'f1 score',\n        313,\n    )","metadata":{"execution":{"iopub.status.busy":"2024-03-15T01:47:25.993138Z","iopub.execute_input":"2024-03-15T01:47:25.993790Z","iopub.status.idle":"2024-03-15T01:47:26.970716Z","shell.execute_reply.started":"2024-03-15T01:47:25.993749Z","shell.execute_reply":"2024-03-15T01:47:26.969624Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Make Test Prediction","metadata":{}},{"cell_type":"code","source":"\"\"\"test_ds = get_test_dataset()\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)\"\"\"","metadata":{"execution":{"iopub.status.busy":"2024-03-15T01:47:26.972218Z","iopub.execute_input":"2024-03-15T01:47:26.972940Z","iopub.status.idle":"2024-03-15T01:47:56.960588Z","shell.execute_reply.started":"2024-03-15T01:47:26.972900Z","shell.execute_reply":"2024-03-15T01:47:56.959314Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_ds = get_test_dataset()\n\nprint('Computing predictions...')\ntest_images_ds = test_ds.map(lambda image, idnum: image)\nprobabilities = (model.predict(test_images_ds) + model2.predict(test_images_ds)) / 2\npredictions = np.argmax(probabilities, axis=-1)\nprint(predictions)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('Generating submission.csv file...')\n\n# Get image ids from test set and convert to unicode\ntest_ids_ds = test_ds.map(lambda image, idnum: idnum).unbatch()\ntest_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U')\n\n# Write the submission file\nnp.savetxt(\n    'submission.csv',\n    np.rec.fromarrays([test_ids, predictions]),\n    fmt=['%s', '%d'],\n    delimiter=',',\n    header='id,label',\n    comments='',\n)\n\n# Look at the first few predictions\n!head submission.csv","metadata":{"execution":{"iopub.status.busy":"2024-03-15T01:47:56.962031Z","iopub.execute_input":"2024-03-15T01:47:56.962375Z","iopub.status.idle":"2024-03-15T01:48:02.374977Z","shell.execute_reply.started":"2024-03-15T01:47:56.962346Z","shell.execute_reply":"2024-03-15T01:48:02.373426Z"},"trusted":true},"execution_count":null,"outputs":[]}]}