{"cells":[{"metadata":{"_uuid":"39e98a97-9cf0-4785-8f21-4cc9ff45f5f2","_cell_guid":"ccd32cff-b633-4333-9115-f8a0eea36a8a","trusted":true},"cell_type":"code","source":"import random, math, re, os\nimport tensorflow as tf, tensorflow.keras.backend as K\nimport numpy as np, pandas as pd\nimport h5py\nfrom matplotlib import pyplot as plt\nfrom kaggle_datasets import KaggleDatasets\nfrom sklearn.metrics import f1_score, precision_score, recall_score, confusion_matrix\nfrom sklearn.model_selection import KFold\nprint(\"Tensorflow version \" + tf.__version__)\nAUTO = tf.data.experimental.AUTOTUNE","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"98785aa0-242b-4153-991f-bf66d279676f","_cell_guid":"4953ca32-e9ed-415f-bd4e-67d9f257c910","trusted":true},"cell_type":"code","source":"try:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()  # TPU detection. No parameters necessary if TPU_NAME environment variable is set. On Kaggle this is always the case.\n    print('Running on TPU ', tpu.master())\nexcept ValueError:\n    tpu = None\n\nif tpu:\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nelse:\n    strategy = tf.distribute.get_strategy() # default distribution strategy in Tensorflow. Works on CPU and single GPU.\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"910aa034-b4b0-450b-acb6-804c53399c0d","_cell_guid":"9b00febb-a46d-44ab-bd1e-25066ee1f39f","trusted":true},"cell_type":"markdown","source":"# **Competition data access**\nTPUs read data directly from Google Cloud Storage (GCS). This Kaggle utility will copy the dataset to a GCS bucket co-located with the TPU. If you have multiple datasets attached to the notebook, you can pass the name of a specific dataset to the get_gcs_path function. The name of the dataset is the name of the directory it is mounted in.","execution_count":null},{"metadata":{"_uuid":"9e73551e-e2dc-479e-b650-353e40cd10f2","_cell_guid":"b0b16582-838d-44aa-a464-0eeac1e18685","trusted":true},"cell_type":"code","source":"!ls /kaggle/input/\nGCS_DS_PATH = KaggleDatasets().get_gcs_path()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"ec1b6e82-e485-413b-ac95-4e897e3aff34","_cell_guid":"b06d6d06-7136-4866-b4ce-56ba7b001eea","trusted":true},"cell_type":"markdown","source":"# **Configuration**","execution_count":null},{"metadata":{"_uuid":"8708f736-b651-4bb6-b01b-79539b34c910","_cell_guid":"e8a948ea-64a0-4a02-89e5-9b9ff6c34027","trusted":true},"cell_type":"code","source":"IMAGE_SIZE = [224, 224] # At this size, a GPU will run out of memory. Use the TPU.\n                        # For GPU training, please select 224 x 224 px image size.\nEPOCHS = 30\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\nFOLDS = 3\ncross_validation=True\n\nGCS_PATH_SELECT = { # available image sizes\n    192: GCS_DS_PATH + '/tfrecords-jpeg-192x192',\n    224: GCS_DS_PATH + '/tfrecords-jpeg-224x224',\n    331: GCS_DS_PATH + '/tfrecords-jpeg-331x331',\n    512: GCS_DS_PATH + '/tfrecords-jpeg-512x512'\n}\nGCS_PATH = GCS_PATH_SELECT[IMAGE_SIZE[0]]\n\nif cross_validation:\n    TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec') + tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')\n    TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec') # predictions on this dataset should be submitted for the competition\nelse:\n    TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec')\n    VALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')\n    TEST_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']","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"f4480caf-1130-4ddc-b224-ed075a9b27e5","_cell_guid":"96c69356-cf86-419f-a136-3d0313987d8c","trusted":true},"cell_type":"markdown","source":"# **Visualization utilities**","execution_count":null},{"metadata":{"_uuid":"3bc2a8a8-c4c1-4831-b8da-3dede3b69bde","_cell_guid":"a2a9b1ac-ee5d-448f-a910-1c01232af144","trusted":true},"cell_type":"code","source":"# numpy and matplotlib defaults\nnp.set_printoptions(threshold=15, linewidth=80)\n\ndef batch_to_numpy_images_and_labels(data):\n    images, labels = data\n    numpy_images = images.numpy()\n    numpy_labels = labels.numpy()\n    if numpy_labels.dtype == object: # binary string in this case, these are image ID strings\n        numpy_labels = [None for _ in enumerate(numpy_images)]\n    # If no labels, only image IDs, return None for labels (this is the case for test data)\n    return numpy_images, numpy_labels\n\ndef title_from_label_and_target(label, correct_label):\n    if correct_label is None:\n        return CLASSES[label], True\n    correct = (label == correct_label)\n    return \"{} [{}{}{}]\".format(CLASSES[label], 'OK' if correct else 'NO', u\"\\u2192\" if not correct else '',\n                                CLASSES[correct_label] if not correct else ''), correct\n\ndef display_one_flower(image, title, subplot, red=False, titlesize=16):\n    plt.subplot(*subplot)\n    plt.axis('off')\n    plt.imshow(image)\n    if len(title) > 0:\n        plt.title(title, fontsize=int(titlesize) if not red else int(titlesize/1.2), color='red' if red else 'black', fontdict={'verticalalignment':'center'}, pad=int(titlesize/1.5))\n    return (subplot[0], subplot[1], subplot[2]+1)\n    \ndef display_batch_of_images(databatch, predictions=None, convert=True):\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    if convert: images, labels = batch_to_numpy_images_and_labels(databatch)\n    else: images, labels = databatch\n    if labels is None:\n        labels = [None for _ in enumerate(images)]\n        \n    # auto-squaring: this will drop data that does not fit into square or square-ish rectangle\n    rows = int(math.sqrt(len(images)))\n    cols = len(images)//rows\n        \n    # size and spacing\n    FIGSIZE = 13.0\n    SPACING = 0.1\n    subplot=(rows,cols,1)\n    if rows < cols:\n        plt.figure(figsize=(FIGSIZE,FIGSIZE/cols*rows))\n    else:\n        plt.figure(figsize=(FIGSIZE/rows*cols,FIGSIZE))\n    \n    # display\n    for i, (image, label) in enumerate(zip(images[:rows*cols], labels[:rows*cols])):\n        title = '' if label is None else CLASSES[label]\n        correct = True\n        if predictions is not None:\n            title, correct = title_from_label_and_target(predictions[i], label)\n        dynamic_titlesize = FIGSIZE*SPACING/max(rows,cols)*40+3 # magic formula tested to work from 1x1 to 10x10 images\n        subplot = display_one_flower(image, title, subplot, not correct, titlesize=dynamic_titlesize)\n    \n    #layout\n    plt.tight_layout()\n    if label is None and predictions is None:\n        plt.subplots_adjust(wspace=0, hspace=0)\n    else:\n        plt.subplots_adjust(wspace=SPACING, hspace=SPACING)\n    plt.show()\n\ndef display_confusion_matrix(cmat, score, precision, recall):\n    plt.figure(figsize=(15,15))\n    ax = plt.gca()\n    ax.matshow(cmat, cmap='Reds')\n    ax.set_xticks(range(len(CLASSES)))\n    ax.set_xticklabels(CLASSES, fontdict={'fontsize': 7})\n    plt.setp(ax.get_xticklabels(), rotation=45, ha=\"left\", rotation_mode=\"anchor\")\n    ax.set_yticks(range(len(CLASSES)))\n    ax.set_yticklabels(CLASSES, fontdict={'fontsize': 7})\n    plt.setp(ax.get_yticklabels(), rotation=45, ha=\"right\", rotation_mode=\"anchor\")\n    titlestring = \"\"\n    if score is not None:\n        titlestring += 'f1 = {:.3f} '.format(score)\n    if precision is not None:\n        titlestring += '\\nprecision = {:.3f} '.format(precision)\n    if recall is not None:\n        titlestring += '\\nrecall = {:.3f} '.format(recall)\n    if len(titlestring) > 0:\n        ax.text(101, 1, titlestring, fontdict={'fontsize': 18, 'horizontalalignment':'right', 'verticalalignment':'top', 'color':'#804040'})\n    plt.show()\n    \ndef display_training_curves(training, validation, title, subplot):\n    if subplot%10==1: # set up the subplots on the first call\n        plt.subplots(figsize=(10,10), facecolor='#F0F0F0')\n        plt.tight_layout()\n    ax = plt.subplot(subplot)\n    ax.set_facecolor('#F8F8F8')\n    ax.plot(training)\n    ax.plot(validation)\n    ax.set_title('model '+ title)\n    ax.set_ylabel(title)\n    #ax.set_ylim(0.28,1.05)\n    ax.set_xlabel('epoch')\n    ax.legend(['train', 'valid.'])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Data Augmentation\nHelper functions for implementing data augmentation","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def flip_image_horizontally(image, label):\n    flipped_image = tf.image.flip_left_right(image)\n    return flipped_image, label\n\ndef flip_image_vertically(image, label):\n    flipped_image = tf.image.flip_up_down(image)\n    return flipped_image, label\n\ndef rotate_image(image, label, k=1):\n    rotated_image = tf.image.rot90(image, k) # k=1 --> 90 degree, k=3 --> 270 degree\n    return rotated_image, label\n\ndef zoom_in_image_20(image, label):\n    datagen = tf.keras.preprocessing.image.ImageDataGenerator(\n        zoom_range = [0.8, 0.8]\n    )\n    #print(len(image))\n    #print(image.shape())    \n    #image_tensor = tf.convert_to_tensor(image.numpy())\n    zoom_augmented = datagen.flow(image)\n    zoom_image,label=next(zoom_augmented)\n    return zoom_image, label\n\ndef zoom_in_image_30(image, label):\n    datagen = tf.keras.preprocessing.image.ImageDataGenerator(\n        zoom_range = [0.7, 0.7]\n    )\n    zoom_augmented = datagen.flow(image.numpy(), label, shuffle=False, batch_size=1)\n    zoom_image,label=next(zoom_augmented)\n    return zoom_image, label\n\ndef zoom_in_image_40(image, label):\n    datagen = tf.keras.preprocessing.image.ImageDataGenerator(\n        zoom_range = [0.6, 0.6]\n    )\n    zoom_augmented = datagen.flow(image.numpy(), label, shuffle=False, batch_size=1)\n    zoom_image,label=next(zoom_augmented)\n    return zoom_image, label\n","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"1bc29c7d-be05-4a34-9814-6b342a173a61","_cell_guid":"d7edbf38-bd81-46ea-be10-015600be7ed1","trusted":true},"cell_type":"markdown","source":"# **Datasets**\nHelper functions for dataset manipulation","execution_count":null},{"metadata":{"_uuid":"845057d0-93ab-49be-ba39-a8627e6c1b30","_cell_guid":"25079097-a1be-44d2-892d-e0a78049e653","trusted":true},"cell_type":"code","source":"def decode_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3)\n    image = tf.cast(image, tf.float32) / 255.0  # convert image to floats in [0, 1] range\n    image = tf.reshape(image, [*IMAGE_SIZE, 3]) # explicit size needed for TPU\n    return image\n\ndef read_labeled_tfrecord(example):\n    LABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"class\": tf.io.FixedLenFeature([], tf.int64),  # shape [] means single element\n    }\n    example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    label = tf.cast(example['class'], tf.int32)\n    return image, label # returns a dataset of (image, label) pairs\n\ndef read_unlabeled_tfrecord(example):\n    UNLABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"id\": tf.io.FixedLenFeature([], tf.string),  # shape [] means single element\n        # class is missing, this competitions's challenge is to predict flower classes for the test dataset\n    }\n    example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    idnum = example['id']\n    return image, idnum # returns a dataset of image(s)\n\ndef load_dataset(filenames, labeled=True, ordered=False):\n    # Read from TFRecords. For optimal performance, reading from multiple files at once and\n    # disregarding data order. Order does not matter since we will be shuffling the data anyway.\n\n    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False # disable order, increase speed\n\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO) # automatically interleaves reads from multiple files\n    dataset = dataset.with_options(ignore_order) # uses data as soon as it streams in, rather than in its original order\n    dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)\n    # returns a dataset of (image, label) pairs if labeled=True or (image, id) pairs if labeled=False\n    return dataset\n\ndef count_records(dataset):\n    c = 0\n    for record in dataset:\n        c += 1\n    return c\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(datasize, dataset, augment=False):\n    if not cross_validation:\n        dataset = load_dataset(TRAINING_FILENAMES, labeled=True)\n    if not augment:\n        dataset = dataset.map(data_augment, num_parallel_calls=AUTO)\n    else:\n        h_flipped_dataset = dataset.map(flip_image_horizontally, num_parallel_calls=AUTO)\n        v_flipped_dataset = dataset.map(flip_image_vertically, num_parallel_calls=AUTO)\n        rotated_dataset = dataset.map(rotate_image, num_parallel_calls=AUTO)\n        #zoomed_dataset_20percent = dataset.map(zoom_in_image_20, num_parallel_calls=AUTO)\n        #zoomed_dataset_30percent = dataset.map(zoom_in_image_30, num_parallel_calls=AUTO)\n        #zoomed_dataset_40percent = dataset.map(zoom_in_image_40, num_parallel_calls=AUTO)\n        # concatenate all datasets\n        dataset = dataset.concatenate(h_flipped_dataset)\n        dataset = dataset.concatenate(v_flipped_dataset)\n        dataset = dataset.concatenate(rotated_dataset)\n        #dataset = dataset.concatenate(zoomed_dataset_20percent)\n        #dataset = dataset.concatenate(zoomed_dataset_30percent)\n        #dataset = dataset.concatenate(zoomed_dataset_40percent)        \n        #datasize[0] = count_records(dataset)\n\n    dataset = dataset.repeat() # the training dataset must repeat for several epochs (to make infinite number of epochs)\n    # https://www.tensorflow.org/api_docs/python/tf/data/Dataset#shuffle\n    dataset = dataset.shuffle(2048) # shuffle the data by choosing random samples from a buffer of len 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(dataset, ordered=False):\n    if not cross_validation:\n        dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache()\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef get_test_dataset(ordered=False):\n    dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef count_data_items(filenames):\n    # the number of data items is written in the name of the .tfrec files, i.e. flowers00-230.tfrec = 230 data items\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    return np.sum(n)\n\nif cross_validation:\n    NUM_TRAINING_IMAGES = int( count_data_items(TRAINING_FILENAMES) * (FOLDS-1.)/FOLDS )\n    NUM_VALIDATION_IMAGES = int( count_data_items(TRAINING_FILENAMES) * (1./FOLDS) )\nelse:\n    NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)\n    NUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\nprint('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"96a5cba7-96e0-4953-9eff-c937147e8000","_cell_guid":"1e3aadce-e55d-4866-9735-3b60f55b8f48","trusted":true},"cell_type":"markdown","source":"# Dataset Playground","execution_count":null},{"metadata":{"_uuid":"e5544608-31e7-4fcd-b8f9-96baf62e0a0e","_cell_guid":"659a2cd1-71fa-40c4-b6ab-c21bc5c8e918","trusted":true},"cell_type":"code","source":"train_data = load_dataset(TRAINING_FILENAMES)\n#print(len(list(train_data.as_numpy_iterator()))\n#d = train_data.batch(32)\n#ite = iter(d)\n#images, labels = next(ite)\n#print(labels.numpy())\n\n#dataset = train_data.map(data_augment, num_parallel_calls=AUTO)\nprint(train_data.take(1))\n#print(len(list(dataset)))\n'''\nknown_labels=[]\nfor image,label in train_data:\n    #print(label.numpy())\n    lab = label.numpy() \n    if lab not in known_labels:\n        known_labels.append(lab)\nknown_labels.sort()\nprint(\"Known labels are {}\".format(known_labels))\n'''\nprint(\"Number of Classes = {}\".format(len(CLASSES)))","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"b7e47d8d-3c18-4a92-a158-390d97f3f5c4","_cell_guid":"c575f78e-e135-4499-b377-6322b344fc5f","trusted":true},"cell_type":"markdown","source":"# **Data Augmentation Playground**","execution_count":null},{"metadata":{"_uuid":"190e36d3-237d-4f5e-ae98-1eca9d84b051","_cell_guid":"33235740-de68-4ea3-97dc-3e7d263751f9","trusted":true},"cell_type":"code","source":"tr = load_dataset(TRAINING_FILENAMES, ordered=True)\ntr = tr.batch(2)\ntrain_data_flipped = tr.map(flip_image_horizontally)\ntrain_data_Vflipped = tr.map(flip_image_vertically)\ntrain_data_rotated = tr.map(rotate_image)\n\ntrain_batch = iter(tr)\ntrain_batch_flipped = iter(train_data_flipped)\ntrain_batch_Vflipped = iter(train_data_Vflipped)\ntrain_batch_rotated = iter(train_data_rotated)\n\n# https://keras.io/api/preprocessing/image/\n\"\"\"\ndatagen = tf.keras.preprocessing.image.ImageDataGenerator(\n#    rotation_range=90,\n#    fill_mode=\"constant\",\n#    cval=0,\n#    width_shift_range=0.2,\n#    height_shift_range=0.2,\n    zoom_range = [0.6, 0.6]\n#    horizontal_flip=True,\n#    vertical_flip=True\n  )\n\nbat_size=1\nbatched_data = train_data.batch(bat_size)\nbatched_data = batched_data.prefetch(AUTO)\nbatch_iterator = iter(batched_data)\n\nimages,labels = next(batch_iterator)\n#print(images)\nprint(labels)\n#numpy_images = images.numpy()\n#numpy_labels = labels.numpy()\n#print(numpy_images)\n#print(numpy_labels)\n\n\nimages_augmented = datagen.flow(images, labels, shuffle=False, batch_size=bat_size)\nprint(images_augmented)\ndisplay_batch_of_images((images,labels), convert=False)\nprint(\"After Zooming in\")\nimage,label=next(images_augmented)\ndisplay_batch_of_images((image,label), convert=False)\n\"\"\"","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"29922c87-92ea-400f-ace5-e9c99240df98","_cell_guid":"865a4d93-56c8-4425-ae51-5a1f5374edd4","trusted":true},"cell_type":"code","source":"#display_batch_of_images(next(train_batch))\n#print(\"After Horizontal Flipping:\")\n#display_batch_of_images(next(train_batch_flipped))\n#print(\"After Vertical Flipping:\")\n#display_batch_of_images(next(train_batch_Vflipped))\n#print(\"After Rotating:\")\n#display_batch_of_images(next(train_batch_rotated))","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"4c23bb07-4d74-4c9f-95ad-c32be5673848","_cell_guid":"40ea6abd-3329-4f54-84e3-d3b8bb3be3df","trusted":true},"cell_type":"markdown","source":"# **Load Data**","execution_count":null},{"metadata":{"_uuid":"10df8fd9-7906-4294-b9c6-4d9531fad909","_cell_guid":"f60bca58-2b43-4b09-bfad-015b006464ff","trusted":true},"cell_type":"code","source":"if not cross_validation:\n    print(\"*** Training data shapes: ***\")\n    ds = [NUM_TRAINING_IMAGES]\n    train_data = get_training_dataset(ds, augment=True)\n    print(\"Number of training data after augmentation: {}\".format(ds[0]))\n    for image,label in train_data.take(1):\n        print(\"Batch Size = {}\".format(image.numpy().shape[0]))\n        print(\"Images shape per batch = {0}, Labels shape per batch = {1}\".format(image.numpy().shape, label.numpy().shape))\n\n    print(\"*** Validation data shapes: ***\")\n    val_data = get_validation_dataset()\n    for image,label in val_data.take(1):\n        print(\"Batch Size = {}\".format(image.numpy().shape[0]))\n        print(\"Images shape per batch = {0}, Labels shape per batch = {1}\".format(image.numpy().shape, label.numpy().shape))\n\n    print(\"*** Test data shapes: ***\")\n    test_data = get_test_dataset()\n    for image,idnum in test_data.take(1):\n        print(\"Batch Size = {}\".format(image.numpy().shape[0]))\n        print(\"Images shape per batch = {0}, ID shape per batch = {1}\".format(image.numpy().shape, label.numpy().shape))","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"026721d5-be26-425e-bd69-b637e9c98a3e","_cell_guid":"1cc83844-6157-4c6c-a2bc-5b93cde02a77","trusted":true},"cell_type":"code","source":"# peek at the dataset\n#train_batch = iter(train_data)\n#test_batch = iter(test_data)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"aa7e097b-a46d-46c5-942c-af3262a20867","_cell_guid":"2b89fea3-b663-49d5-9af5-ac5d21a917b8","trusted":true},"cell_type":"code","source":"# run this cell again for next set of images\n#display_batch_of_images(next(train_batch))","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"74a19b37-6561-449d-84d6-95720838f067","_cell_guid":"24952cce-6e91-4eb1-8e9b-703f604daa11","trusted":true},"cell_type":"code","source":"# run this cell again for next set of images\n#display_batch_of_images(next(test_batch))","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"03f2a9b2-b7ce-4745-8f9f-9b92eb8a5578","_cell_guid":"ea99319f-4f29-4a36-9333-ee2980091923","trusted":true},"cell_type":"markdown","source":"# **Transfer Learning**\n> Try well known architecutres in the problem\nTODO:\n1- Pre-trained model as a Feature Extractor (transfer learning + cusstom network with regularizers)\n2- Pre-trained model with fine-tuning (partial fine tuninig (disable training of some layers))\n3- Pre-trained model with fine-tuning (complete fine tuning + addition of the supported regularizers in the model)","execution_count":null},{"metadata":{"_uuid":"90925725-ed96-4e3c-ab57-fdce2fafef2f","_cell_guid":"c9310bbe-67b9-4534-968e-c321e7cb7be5","trusted":true},"cell_type":"code","source":"Training_strategies = ['Feature_Extractor','Partial_Fine_tuninig','Complete_Fine_Tuning']\ntrain_strategy = Training_strategies[2]\nprint('train strategy is {}'.format(train_strategy))\nif train_strategy == Training_strategies[0]:\n    with strategy.scope():\n        #pretrained_model = tf.keras.applications.DenseNet201(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])\n        #pretrained_model = tf.keras.applications.Xception(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])\n        pretrained_model = tf.keras.applications.VGG16(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])\n        pretrained_model.trainable = False # False = transfer learning, True = fine-tuning\n    \n        model = tf.keras.Sequential([\n            pretrained_model,\n            tf.keras.layers.Flatten(),\n            tf.keras.layers.Dense(512, activation='relu'),\n            tf.keras.layers.Dropout(0.3),\n            tf.keras.layers.Dense(512, activation='relu'),\n            tf.keras.layers.Dropout(0.1),\n            #tf.keras.layers.GlobalAveragePooling2D(),\n            tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n        ])\n        opt = tf.keras.optimizers.Adam(learning_rate=0.00001)\n\nelif train_strategy == Training_strategies[1]:\n    with strategy.scope():\n        #pretrained_model = tf.keras.applications.DenseNet201(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])\n        #pretrained_model = tf.keras.applications.Xception(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])\n        pretrained_model = tf.keras.applications.VGG16(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])\n        pretrained_model.trainable = True # False = transfer learning, True = fine-tuning\n        \n        for layer in pretrained_model.layers:\n            if 'block5' in layer.name or 'block4' in layer.name:\n                layer.trainable = True\n            else:\n                layer.trainable = False\n            print(\"{0} is trainable: {1}\".format(layer.name, layer.trainable))\n        \n        model = tf.keras.Sequential([\n            pretrained_model,\n            tf.keras.layers.Flatten(),\n            tf.keras.layers.Dense(512, activation='relu'),\n            tf.keras.layers.Dropout(0.4),\n            tf.keras.layers.Dense(512, activation='relu'),\n            tf.keras.layers.Dropout(0.1),\n            tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n        ])\n        \n        # optimizer\n        opt = tf.keras.optimizers.Adam(learning_rate=0.00001)\n        \nelif train_strategy == Training_strategies[2]:\n    with strategy.scope():\n        pretrained_model = tf.keras.applications.DenseNet201(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])\n        #pretrained_model = tf.keras.applications.Xception(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])\n        #pretrained_model = tf.keras.applications.VGG16(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])\n        pretrained_model.trainable = True # False = transfer learning, True = fine-tuning\n    \n        model = tf.keras.Sequential([\n            pretrained_model,\n            #tf.keras.layers.Flatten(),\n            tf.keras.layers.GlobalAveragePooling2D(),\n            tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n        ])\n        # optimizer\n        opt = tf.keras.optimizers.Adam(learning_rate=0.00001)\n\nmodel.compile(\n    optimizer=opt,\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy']\n)\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"a1e88ed3-5e45-43e6-ac4b-9cfd66d1e1db","_cell_guid":"805397d0-51da-4931-9f1b-09d724d2a2cd","trusted":true},"cell_type":"markdown","source":"# **Training**","execution_count":null},{"metadata":{"_uuid":"43981080-bb37-4afd-848a-189485fb6871","_cell_guid":"d737ea2d-2d99-409d-8fa1-05c67efcfacd","trusted":true},"cell_type":"code","source":"if not cross_validation:\n    EPOCHS=150   #15\n    es = tf.keras.callbacks.EarlyStopping(monitor='val_loss',verbose=1, patience=14)\n    mc = tf.keras.callbacks.ModelCheckpoint('best_model.h5', monitor='val_loss', save_best_only=True, save_weights_only=True, verbose=1)\n    history = model.fit(train_data, steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS, validation_data=val_data, verbose=2, callbacks=[es, mc])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"EPOCHS=150\nFOLDS=3\ndef get_model():\n    with strategy.scope():\n        rnet = tf.keras.applications.DenseNet201(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])\n        # trainable rnet\n        rnet.trainable = True\n        model = tf.keras.Sequential([\n            rnet,\n            tf.keras.layers.GlobalAveragePooling2D(),\n            tf.keras.layers.Dense(len(CLASSES), activation='softmax',dtype='float32')\n        ])\n        opt = tf.keras.optimizers.Adam(learning_rate=0.00001)\n    model.compile(\n        optimizer=opt,\n        loss = 'sparse_categorical_crossentropy',\n        metrics=['sparse_categorical_accuracy']\n    )\n    return model\n\ndef train_cross_validate(folds = 5):\n    histories = []\n    models = []\n    early_stopping = tf.keras.callbacks.EarlyStopping(monitor = 'val_loss', patience = 14)\n    kfold = KFold(folds, shuffle = True, random_state = 42)\n    for f, (trn_ind, val_ind) in enumerate(kfold.split(TRAINING_FILENAMES)):\n        print(); print('#'*25)\n        print('### FOLD',f+1)\n        print('#'*25)\n        train_dataset = load_dataset(list(pd.DataFrame({'TRAINING_FILENAMES': TRAINING_FILENAMES}).loc[trn_ind]['TRAINING_FILENAMES']), labeled = True)\n        val_dataset = load_dataset(list(pd.DataFrame({'TRAINING_FILENAMES': TRAINING_FILENAMES}).loc[val_ind]['TRAINING_FILENAMES']), labeled = True, ordered = True)\n        checkpoint_name = f'model_fold_{folds + 1}' + '.h5'\n        mc = tf.keras.callbacks.ModelCheckpoint(checkpoint_name, monitor='val_loss', save_best_only=True, save_weights_only=True, verbose=1)\n        model = get_model()\n        ds = [NUM_TRAINING_IMAGES]\n        model.summary()\n        train_data = get_training_dataset(ds, train_dataset, augment=True)\n        val_data = get_validation_dataset(val_dataset)\n        history = model.fit(\n            train_data, \n            steps_per_epoch = STEPS_PER_EPOCH,\n            epochs = EPOCHS,\n            callbacks = [early_stopping, mc],\n            validation_data = val_data,\n            verbose=2\n        )\n        model.load_weights(checkpoint_name)\n        models.append(model)\n        histories.append(history)\n    return histories, models\n\ndef train_and_predict(folds = 5):\n    test_ds = get_test_dataset(ordered=True) # since we are splitting the dataset and iterating separately on images and ids, order matters.\n    test_images_ds = test_ds.map(lambda image, idnum: image)\n    print('Start training %i folds'%folds)\n    histories, models = train_cross_validate(folds = folds)\n    \n    print('Computing predictions...')\n    # get the mean probability of the folds models\n    probabilities = np.average([models[i].predict(test_images_ds) for i in range(folds)], axis = 0)\n    predictions = np.argmax(probabilities, axis=-1)\n    print('Generating submission.csv file...')\n    test_ids_ds = test_ds.map(lambda image, idnum: idnum).unbatch()\n    test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U') # all in one batch\n    np.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')\n    return histories, models\n    \n# run train and predict\nif cross_validation:\n    histories, models = train_and_predict(folds = FOLDS)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"a70b5aef-447e-462c-a701-7c9169da725d","_cell_guid":"cedcf31d-de75-4129-ba92-735d77372020","trusted":true},"cell_type":"code","source":"if not cross_validation:\n    display_training_curves(history.history['loss'], history.history['val_loss'], 'loss', 211)\n    display_training_curves(history.history['sparse_categorical_accuracy'], history.history['val_sparse_categorical_accuracy'], 'accuracy', 212)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"5188cc70-0ba1-4571-946c-0f8c1adeaa55","_cell_guid":"60cb427d-8a38-40f2-b51a-6acf2934a9ae","trusted":true},"cell_type":"markdown","source":"# **Predictions**","execution_count":null},{"metadata":{"_uuid":"9c9215d1-53af-4407-8569-66cd0c9b5fb6","_cell_guid":"a468fb4a-cf27-4b07-9c29-ed69b52fe9dc","trusted":true},"cell_type":"code","source":"# Load the best model\nif not cross_validation:\n    model.load_weights('best_model.h5')\n\n    test_ds = get_test_dataset(ordered=True) # since we are splitting the dataset and iterating separately on images and ids, order matters.\n\n    print('Computing predictions...')\n    test_images_ds = test_ds.map(lambda image, idnum: image)\n    probabilities = model.predict(test_images_ds)\n    predictions = np.argmax(probabilities, axis=-1)\n    print(predictions)\n\n    print('Generating submission.csv file...')\n    test_ids_ds = test_ds.map(lambda image, idnum: idnum).unbatch()\n    test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U') # all in one batch\n    np.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')\n    !head submission.csv","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"2c4cd28e-9d7b-40e0-a696-865b3bae702d","_cell_guid":"450b9ae7-8d8c-40ae-9733-966208f2948e","trusted":true},"cell_type":"markdown","source":"# **Visual validation**","execution_count":null},{"metadata":{"_uuid":"018818c1-6e7e-45d1-8595-fb97ce739217","_cell_guid":"8d6a335d-d213-4cfb-91ba-4aee86f20d5b","trusted":true},"cell_type":"code","source":"if not cross_validation:\n    dataset = get_validation_dataset()\n    dataset = dataset.unbatch().batch(20)\n    batch = iter(dataset)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"18045fe2-196b-4932-b75a-1c2a194838af","_cell_guid":"53bf4e06-18d3-453f-af56-6c97049bcf9c","trusted":true},"cell_type":"code","source":"if not cross_validation:\n    # run this cell again for next set of images\n    images, labels = next(batch)\n    probabilities = model.predict(images)\n    predictions = np.argmax(probabilities, axis=-1)\n    display_batch_of_images((images, labels), predictions)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Confusion Matrix","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def 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()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nall_labels = []; all_prob = []; all_pred = []\nkfold = KFold(FOLDS, shuffle = True, random_state = 42)\nfor j, (trn_ind, val_ind) in enumerate( kfold.split(TRAINING_FILENAMES) ):\n    print('Inferring fold',j+1,'validation images...')\n    VAL_FILES = list(pd.DataFrame({'TRAINING_FILENAMES': TRAINING_FILENAMES}).loc[val_ind]['TRAINING_FILENAMES'])\n    NUM_VALIDATION_IMAGES = count_data_items(VAL_FILES)\n    cmdataset = get_validation_dataset(load_dataset(VAL_FILES, labeled = True, ordered = True))\n    images_ds = cmdataset.map(lambda image, label: image)\n    labels_ds = cmdataset.map(lambda image, label: label).unbatch()\n    all_labels.append( next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES))).numpy() ) # get everything as one batch\n    prob = models[j].predict(images_ds)\n    all_prob.append( prob )\n    all_pred.append( np.argmax(prob, axis=-1) )\ncm_correct_labels = np.concatenate(all_labels)\ncm_probabilities = np.concatenate(all_prob)\ncm_predictions = np.concatenate(all_pred)\n\nprint(\"Correct   labels: \", cm_correct_labels.shape, cm_correct_labels)\nprint(\"Predicted labels: \", cm_predictions.shape, cm_predictions); print()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cmat = confusion_matrix(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)))\nscore = f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)), average='macro')\nprecision = precision_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)), average='macro')\nrecall = recall_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)), average='macro')\ndisplay_confusion_matrix(cmat, score, precision, recall)\nprint('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall)); print()","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}