{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install -q efficientnet","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import gc\nimport math, re, os, time\nimport tensorflow as tf, tensorflow.keras.backend as K\n#tf.config.experimental_run_functions_eagerly(True)\nimport numpy as np\nfrom collections import namedtuple\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","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# TPU or GPU detection"},{"metadata":{"trusted":true},"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    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":{},"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. Use `!ls /kaggle/input/` to list attached datasets."},{"metadata":{"trusted":true},"cell_type":"code","source":"GCS_DS_PATH = KaggleDatasets().get_gcs_path('flower-classification') # you can list the bucket with \"!gsutil ls $GCS_DS_PATH\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#EXT_DS_PATH = KaggleDatasets().get_gcs_path('oxford-102-for-tpu-competition')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"EXT_DS_PATH = KaggleDatasets().get_gcs_path('tf-flower-photo-tfrec')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Configuration"},{"metadata":{"trusted":true},"cell_type":"code","source":"USE_EXTERNAL = False\nSKIP_VALIDATION = True\nif tpu:\n    SIZE = 512\nelse:\n    SIZE = 192\nIMAGE_SIZE = [SIZE, SIZE] # 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 = 18\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\nAUG_BATCH = BATCH_SIZE","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"GCS_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}\n#GCS_PATH = GCS_PATH_SELECT[IMAGE_SIZE[0]]\n\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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_filenames(size):\n    path = GCS_PATH_SELECT[size]\n    train_filenames = tf.io.gfile.glob(path + '/train/*.tfrec')\n    valid_filenames = tf.io.gfile.glob(path + '/val/*.tfrec')\n    test_filenames = tf.io.gfile.glob(path + '/test/*.tfrec')\n    \n    return train_filenames, valid_filenames, test_filenames","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"if USE_EXTERNAL:\n    EXT_PATH_SELECT = { # available image sizes\n        192: '/tfrecords-jpeg-192x192',\n        224: '/tfrecords-jpeg-224x224',\n        331: '/tfrecords-jpeg-331x331',\n        512: '/tfrecords-jpeg-512x512'\n    }\n    #EXT_PATH = EXT_PATH_SELECT[IMAGE_SIZE[0]]\n    #EXT_TRAINING_FILENAMES = []\n    #if 1:\n    #    EXT_TRAINING_FILENAMES += tf.io.gfile.glob(EXT_DS_PATH + '/imagenet' + EXT_PATH + '/*.tfrec')\n    #if 2:\n    #    EXT_TRAINING_FILENAMES += tf.io.gfile.glob(EXT_DS_PATH +  '/inaturalist_1' + EXT_PATH + '/*.tfrec')\n    #if 3:\n    #    EXT_TRAINING_FILENAMES += tf.io.gfile.glob(EXT_DS_PATH +  '/openimage' + EXT_PATH + '/*.tfrec')\n    #if 4:\n    #    EXT_TRAINING_FILENAMES += tf.io.gfile.glob(EXT_DS_PATH +  '/oxford_102' + EXT_PATH + '/*.tfrec')\n    #if 5:\n    #    EXT_TRAINING_FILENAMES += tf.io.gfile.glob(EXT_DS_PATH +  '/tf_flowers' + EXT_PATH + '/*.tfrec')\n    \n    #print(EXT_TRAINING_FILENAMES)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_ext_filenames(size, imagenet=False, inaturalist=False, openimage=False, oxford=False, tfflowers=False):\n    path = EXT_PATH_SELECT[size]\n    train_filenames = []\n    if imagenet:\n        train_filenames += tf.io.gfile.glob(EXT_DS_PATH + '/imagenet' + path + '/*.tfrec')\n    if inaturalist:\n        train_filenames += tf.io.gfile.glob(EXT_DS_PATH + '/inaturalist_1' + path + '/*.tfrec')\n    if openimage:\n        train_filenames += tf.io.gfile.glob(EXT_DS_PATH + '/openimage' + path + '/*.tfrec')\n    if oxford:\n        train_filenames += tf.io.gfile.glob(EXT_DS_PATH + '/oxford_102' + path + '/*.tfrec')\n    if tfflowers:\n        train_filenames += tf.io.gfile.glob(EXT_DS_PATH + '/tf_flowers' + path + '/*.tfrec')\n        \n    return train_filenames\n        ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"CLASSES = ['pink primrose',    'hard-leaved pocket orchid', 'canterbury bells', 'sweet pea',     'wild geranium',     'tiger lily',           'moon orchid',              'bird of paradise', 'monkshood',        'globe thistle',         # 00 - 09\n           'snapdragon',       \"colt's foot\",               'king protea',      'spear thistle', 'yellow iris',       'globe-flower',         'purple coneflower',        'peruvian lily',    'balloon flower',   'giant white arum lily', # 10 - 19\n           'fire lily',        'pincushion flower',         'fritillary',       'red ginger',    'grape hyacinth',    'corn poppy',           'prince of wales feathers', 'stemless gentian', 'artichoke',        'sweet william',         # 20 - 29\n           'carnation',        'garden phlox',              'love in the mist', 'cosmos',        'alpine sea holly',  'ruby-lipped cattleya', 'cape flower',              'great masterwort', 'siam tulip',       'lenten rose',           # 30 - 39\n           'barberton daisy',  'daffodil',                  'sword lily',       'poinsettia',    'bolero deep blue',  'wallflower',           'marigold',                 'buttercup',        'daisy',            'common dandelion',      # 40 - 49\n           'petunia',          'wild pansy',                'primula',          'sunflower',     'lilac hibiscus',    'bishop of llandaff',   'gaura',                    'geranium',         'orange dahlia',    'pink-yellow dahlia',    # 50 - 59\n           'cautleya spicata', 'japanese anemone',          'black-eyed susan', 'silverbush',    'californian poppy', 'osteospermum',         'spring crocus',            'iris',             'windflower',       'tree poppy',            # 60 - 69\n           'gazania',          'azalea',                    'water lily',       'rose',          'thorn apple',       'morning glory',        'passion flower',           'lotus',            'toad lily',        'anthurium',             # 70 - 79\n           'frangipani',       'clematis',                  'hibiscus',         'columbine',     'desert-rose',       'tree mallow',          'magnolia',                 'cyclamen ',        'watercress',       'canna lily',            # 80 - 89\n           'hippeastrum ',     'bee balm',                  'pink quill',       'foxglove',      'bougainvillea',     'camellia',             'mallow',                   'mexican petunia',  'bromelia',         'blanket flower',        # 90 - 99\n           'trumpet creeper',  'blackberry lily',           'common tulip',     'wild rose']                                                                                                                                               # 100 - 102","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Visualization utilities\ndata -> pixels, nothing of much interest for the machine learning practitioner in this section."},{"metadata":{"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):\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        if label is None:\n            title = ''\n        elif isinstance(label, int):\n            title = CLASSES[label]\n        else:\n            idx = np.argmax(label, axis=0)\n            title = CLASSES[idx]\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":"# Datasets"},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_batch_transformatioin_matrix(rotation, shear, height_zoom, width_zoom, height_shift, width_shift):\n    \"\"\"Returns a tf.Tensor of shape (batch_size, 3, 3) with each element along the 1st axis being\n       an image transformation matrix (which transforms indicies).\n\n    Args:\n        rotation: 1-D Tensor with shape [batch_size].\n        shear: 1-D Tensor with shape [batch_size].\n        height_zoom: 1-D Tensor with shape [batch_size].\n        width_zoom: 1-D Tensor with shape [batch_size].\n        height_shift: 1-D Tensor with shape [batch_size].\n        width_shift: 1-D Tensor with shape [batch_size].\n        \n    Returns:\n        A 3-D Tensor with shape [batch_size, 3, 3].\n    \"\"\"    \n\n    # A trick to get batch_size\n    batch_size = tf.cast(tf.reduce_sum(tf.ones_like(rotation)), tf.int64)    \n    \n    # CONVERT DEGREES TO RADIANS\n    rotation = tf.constant(math.pi) * rotation / 180.0\n    shear = tf.constant(math.pi) * shear / 180.0\n\n    # shape = (batch_size,)\n    one = tf.ones_like(rotation, dtype=tf.float32)\n    zero = tf.zeros_like(rotation, dtype=tf.float32)\n    \n    # ROTATION MATRIX\n    c1 = tf.math.cos(rotation) # shape = (batch_size,)\n    s1 = tf.math.sin(rotation) # shape = (batch_size,)\n\n    # Intermediate matrix for rotation, shape = (9, batch_size) \n    rotation_matrix_temp = tf.stack([c1, s1, zero, -s1, c1, zero, zero, zero, one], axis=0)\n    # shape = (batch_size, 9)\n    rotation_matrix_temp = tf.transpose(rotation_matrix_temp)\n    # Fianl rotation matrix, shape = (batch_size, 3, 3)\n    rotation_matrix = tf.reshape(rotation_matrix_temp, shape=(batch_size, 3, 3))\n        \n    # SHEAR MATRIX\n    c2 = tf.math.cos(shear) # shape = (batch_size,)\n    s2 = tf.math.sin(shear) # shape = (batch_size,)\n    \n    # Intermediate matrix for shear, shape = (9, batch_size) \n    shear_matrix_temp = tf.stack([one, s2, zero, zero, c2, zero, zero, zero, one], axis=0)\n    # shape = (batch_size, 9)\n    shear_matrix_temp = tf.transpose(shear_matrix_temp)\n    # Fianl shear matrix, shape = (batch_size, 3, 3)\n    shear_matrix = tf.reshape(shear_matrix_temp, shape=(batch_size, 3, 3))    \n    \n\n    # ZOOM MATRIX\n    \n    # Intermediate matrix for zoom, shape = (9, batch_size) \n    zoom_matrix_temp = tf.stack([one / height_zoom, zero, zero, zero, one / width_zoom, zero, zero, zero, one], axis=0)\n    # shape = (batch_size, 9)\n    zoom_matrix_temp = tf.transpose(zoom_matrix_temp)\n    # Fianl zoom matrix, shape = (batch_size, 3, 3)\n    zoom_matrix = tf.reshape(zoom_matrix_temp, shape=(batch_size, 3, 3))\n    \n    # SHIFT MATRIX\n    \n    # Intermediate matrix for shift, shape = (9, batch_size) \n    shift_matrix_temp = tf.stack([one, zero, height_shift, zero, one, width_shift, zero, zero, one], axis=0)\n    # shape = (batch_size, 9)\n    shift_matrix_temp = tf.transpose(shift_matrix_temp)\n    # Fianl shift matrix, shape = (batch_size, 3, 3)\n    shift_matrix = tf.reshape(shift_matrix_temp, shape=(batch_size, 3, 3))    \n        \n    return tf.linalg.matmul(tf.linalg.matmul(rotation_matrix, shear_matrix), tf.linalg.matmul(zoom_matrix, shift_matrix))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def batch_transform(images, labels):\n    \"\"\"Returns a tf.Tensor of the same shape as `images`, represented a batch of randomly transformed images.\n\n    Args:\n        images: 4-D Tensor with shape (batch_size, width, hight, depth).\n            Currently, `depth` can only be 3.\n        \n    Returns:\n        A 4-D Tensor with the same shape as `images`.\n    \"\"\" \n    \n    # input `images`: a batch of images [batch_size, dim, dim, 3]\n    # output: images randomly rotated, sheared, zoomed, and shifted\n    DIM = images.shape[1]\n    XDIM = DIM % 2  # fix for size 331\n    \n    # A trick to get batch_size\n    batch_size = tf.cast(tf.reduce_sum(tf.ones_like(images)) / (images.shape[1] * images.shape[2] * images.shape[3]), tf.int64)\n    \n    rot = 15.0 * tf.random.normal([batch_size], dtype='float32')\n    shr = 5.0 * tf.random.normal([batch_size], dtype='float32') \n    h_zoom = 1.0 + tf.random.normal([batch_size], dtype='float32') / 10.0\n    w_zoom = 1.0 + tf.random.normal([batch_size], dtype='float32') / 10.0\n    h_shift = 16.0 * tf.random.normal([batch_size], dtype='float32') \n    w_shift = 16.0 * tf.random.normal([batch_size], dtype='float32') \n  \n    # GET TRANSFORMATION MATRIX\n    # shape = (batch_size, 3, 3)\n    m = get_batch_transformatioin_matrix(rot, shr, h_zoom, w_zoom, h_shift, w_shift) \n\n    # LIST DESTINATION PIXEL INDICES\n    x = tf.repeat(tf.range(DIM // 2, -DIM // 2, -1), DIM)  # shape = (DIM * DIM,)\n    y = tf.tile(tf.range(-DIM // 2, DIM // 2), [DIM])  # shape = (DIM * DIM,)\n    z = tf.ones([DIM * DIM], dtype='int32')  # shape = (DIM * DIM,)\n    idx = tf.stack([x, y, z])  # shape = (3, DIM * DIM)\n    \n    # ROTATE DESTINATION PIXELS ONTO ORIGIN PIXELS\n    idx2 = tf.linalg.matmul(m, tf.cast(idx, dtype='float32'))  # shape = (batch_size, 3, DIM ** 2)\n    idx2 = K.cast(idx2, dtype='int32')  # shape = (batch_size, 3, DIM ** 2)\n    idx2 = K.clip(idx2, -DIM // 2 + XDIM + 1, DIM // 2)  # shape = (batch_size, 3, DIM ** 2)\n    \n    # FIND ORIGIN PIXEL VALUES\n    # shape = (batch_size, 2, DIM ** 2)\n    idx3 = tf.stack([DIM // 2 - idx2[:, 0, ], DIM // 2 - 1 + idx2[:, 1, ]], axis=1)  \n    \n    # shape = (batch_size, DIM ** 2, 3)\n    d = tf.gather_nd(images, tf.transpose(idx3, perm=[0, 2, 1]), batch_dims=1)\n        \n    # shape = (batch_size, DIM, DIM, 3)\n    new_images = tf.reshape(d, (batch_size, DIM, DIM, 3))\n\n    return new_images, labels","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def onehot(image,label):\n    CLASSES = 104\n    return image,tf.one_hot(label,CLASSES)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def batch_cutmix(images, labels, PROBABILITY=1.0, batch_size=0):\n    \n    DIM = IMAGE_SIZE[0]\n    CLASSES = 104\n    \n    if batch_size == 0:\n        batch_size = AUG_BATCH\n    \n    # DO CUTMIX WITH PROBABILITY DEFINED ABOVE\n    # This is a tensor containing 0 or 1 -- 0: no cutmix.\n    # shape = [batch_size]\n    do_cutmix = tf.cast(tf.random.uniform([batch_size], 0, 1) <= PROBABILITY, tf.int32)\n    \n    # Choose random images in the batch for cutmix\n    # shape = [batch_size]\n    new_image_indices = tf.cast(tf.random.uniform([batch_size], 0, batch_size), tf.int32)\n    \n    # Choose random location in the original image to put the new images\n    # shape = [batch_size]\n    new_x = tf.cast(tf.random.uniform([batch_size], 0, DIM), tf.int32)\n    new_y = tf.cast(tf.random.uniform([batch_size], 0, DIM), tf.int32)\n    \n    # Random width for new images, shape = [batch_size]\n    b = tf.random.uniform([batch_size], 0, 1) # this is beta dist with alpha=1.0\n    new_width = tf.cast(DIM * tf.math.sqrt(1-b), tf.int32) * do_cutmix\n    \n    # shape = [batch_size]\n    new_y0 = tf.math.maximum(0, new_y - new_width // 2)\n    new_y1 = tf.math.minimum(DIM, new_y + new_width // 2)\n    new_x0 = tf.math.maximum(0, new_x - new_width // 2)\n    new_x1 = tf.math.minimum(DIM, new_x + new_width // 2)\n    \n    # shape = [batch_size, DIM]\n    target = tf.broadcast_to(tf.range(DIM), shape=(batch_size, DIM))\n    \n    # shape = [batch_size, DIM]\n    mask_y = tf.math.logical_and(new_y0[:, tf.newaxis] <= target, target <= new_y1[:, tf.newaxis])\n    \n    # shape = [batch_size, DIM]\n    mask_x = tf.math.logical_and(new_x0[:, tf.newaxis] <= target, target <= new_x1[:, tf.newaxis])    \n    \n    # shape = [batch_size, DIM, DIM]\n    mask = tf.cast(tf.math.logical_and(mask_y[:, :, tf.newaxis], mask_x[:, tf.newaxis, :]), tf.float32)\n\n    # All components are of shape [batch_size, DIM, DIM, 3]\n    new_images =  images * tf.broadcast_to(1 - mask[:, :, :, tf.newaxis], [batch_size, DIM, DIM, 3]) + \\\n                    tf.gather(images, new_image_indices) * tf.broadcast_to(mask[:, :, :, tf.newaxis], [batch_size, DIM, DIM, 3])\n\n    a = tf.cast(new_width ** 2 / DIM ** 2, tf.float32)    \n        \n    # Make labels\n    if len(labels.shape) == 1:\n        labels = tf.one_hot(labels, CLASSES)\n        \n    new_labels =  (1-a)[:, tf.newaxis] * labels + a[:, tf.newaxis] * tf.gather(labels, new_image_indices)        \n        \n    return new_images, new_labels","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def batch_mixup(images, labels, PROBABILITY=1.0, batch_size=0):\n\n    DIM = IMAGE_SIZE[0]\n    CLASSES = 104\n    \n    if batch_size == 0:\n        batch_size = AUG_BATCH\n    \n    # Do `batch_mixup` with a probability = `PROBABILITY`\n    # This is a tensor containing 0 or 1 -- 0: no mixup.\n    # shape = [batch_size]\n    do_mixup = tf.cast(tf.random.uniform([batch_size], 0, 1) <= PROBABILITY, tf.int32)\n\n    # Choose random images in the batch for cutmix\n    # shape = [batch_size]\n    new_image_indices = tf.cast(tf.random.uniform([batch_size], 0, batch_size), tf.int32)\n    \n    # ratio of importance of the 2 images to be mixed up\n    # shape = [batch_size]\n    a = tf.random.uniform([batch_size], 0, 1) * tf.cast(do_mixup, tf.float32)  # this is beta dist with alpha=1.0\n                \n    # The second part corresponds to the images to be added to the original images `images`.\n    new_images =  (1-a)[:, tf.newaxis, tf.newaxis, tf.newaxis] * images + a[:, tf.newaxis, tf.newaxis, tf.newaxis] * tf.gather(images, new_image_indices)\n\n    # Make labels\n    if len(labels.shape) == 1:\n        labels = tf.one_hot(labels, CLASSES)\n    new_labels =  (1-a)[:, tf.newaxis] * labels + a[:, tf.newaxis] * tf.gather(labels, new_image_indices)\n\n    return new_images, new_labels","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def transform_cut_mix(image,label):\n    # THIS FUNCTION APPLIES BOTH CUTMIX AND MIXUP\n    DIM = IMAGE_SIZE[0]\n    CLASSES = 104\n    SWITCH = 0.5\n    CUTMIX_PROB = 0.666\n    MIXUP_PROB = 0.666\n    # FOR SWITCH PERCENT OF TIME WE DO CUTMIX AND (1-SWITCH) WE DO MIXUP\n    #image2, label2 = cutmix(image, label, CUTMIX_PROB)\n    image2, label2 = batch_cutmix(image, label, CUTMIX_PROB)\n    #image3, label3 = mixup(image, label, MIXUP_PROB)\n    image3, label3 = batch_mixup(image, label, MIXUP_PROB)\n    imgs = []; labs = []\n    for j in range(AUG_BATCH):\n        P = tf.cast( tf.random.uniform([],0,1)<=SWITCH, tf.float32)\n        imgs.append(P*image2[j,]+(1-P)*image3[j,])\n        labs.append(P*label2[j,]+(1-P)*label3[j,])\n    # RESHAPE HACK SO TPU COMPILER KNOWS SHAPE OF OUTPUT TENSOR (maybe use Python typing instead?)\n    image4 = tf.reshape(tf.stack(imgs),(AUG_BATCH,DIM,DIM,3))\n    label4 = tf.reshape(tf.stack(labs),(AUG_BATCH,CLASSES))\n    return image4,label4","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","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 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, _ = transform_rszs(image, label)\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(dataset, simple_aug=False, advance_aug=False, cut_mix_aug=0):\n    #dataset = load_dataset(TRAINING_FILENAMES, labeled=True)\n    if simple_aug:\n        dataset = dataset.map(data_augment, num_parallel_calls=AUTO)\n    #if advance_aug:\n    #    dataset = dataset.map(transform_rszs, num_parallel_calls=AUTO)\n    dataset = dataset.repeat() # the training dataset must repeat for several epochs\n    dataset = dataset.batch(AUG_BATCH)\n    if advance_aug:\n        dataset = dataset.map(batch_transform, num_parallel_calls=AUTO)\n    if cut_mix_aug==1:\n        dataset = dataset.map(batch_cutmix, num_parallel_calls=AUTO)\n    elif cut_mix_aug==2:\n        dataset = dataset.map(batch_mixup, num_parallel_calls=AUTO)\n    elif cut_mix_aug==3:\n        dataset = dataset.map(transform_cut_mix, num_parallel_calls=AUTO)\n    dataset = dataset.unbatch()\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(dataset, ordered=False, repeated=False):\n    #dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=ordered)\n    if repeated:\n        dataset = dataset.repeat()\n        dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE, drop_remainder=repeated)\n    #dataset = dataset.cache() #remark to avoid socket closed error\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\n\ndef int_div_round_up(a, b):\n    return (a + b - 1) // b\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"SIZE = 512\nIMAGE_SIZE = [SIZE, SIZE]\n\nTRAINING_FILENAMES, VALIDATION_FILENAMES, TEST_FILENAMES = get_filenames(SIZE)\nprint(len(TRAINING_FILENAMES))\n\nif USE_EXTERNAL:\n    EXT_TRAINING_FILENAMES = get_ext_filenames(SIZE, imagenet=True, inaturalist=True, openimage=False, oxford=False, tfflowers=False)\n    print(len(EXT_TRAINING_FILENAMES))\n    \nif USE_EXTERNAL:\n    TRAINING_FILENAMES = TRAINING_FILENAMES + EXT_TRAINING_FILENAMES\n\nif SKIP_VALIDATION:\n    TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES\n    \nNUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)\nNUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES) if not SKIP_VALIDATION else 0\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\nVALIDATION_STEPS = int_div_round_up(NUM_VALIDATION_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":{},"cell_type":"markdown","source":"# Dataset visualizations"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_ds = load_dataset(TRAINING_FILENAMES, labeled=True)\nvalid_ds = load_dataset(VALIDATION_FILENAMES, labeled=True) if not SKIP_VALIDATION else None\ntest_ds = load_dataset(TEST_FILENAMES, labeled=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# data dump\nprint(\"Training data shapes:\")\nfor image, label in get_training_dataset(train_ds).take(3):\n    print(image.numpy().shape, label.numpy().shape)\nprint(\"Training data label examples:\", label.numpy())\nif not SKIP_VALIDATION:\n    print(\"Validation data shapes:\")\n    for image, label in get_validation_dataset(valid_ds).take(3):\n        print(image.numpy().shape, label.numpy().shape)\n    print(\"Validation data label examples:\", label.numpy())\nprint(\"Test data shapes:\")\nfor image, idnum in get_test_dataset(test_ds).take(3):\n    print(image.numpy().shape, idnum.numpy().shape)\nprint(\"Test data IDs:\", idnum.numpy().astype('U')) # U=unicode string","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"if 0:\n    # Peek at training data\n    training_dataset = get_training_dataset(train_ds, simple_aug=True, advance_aug=False, cut_mix_aug=1)\n    training_dataset = training_dataset.unbatch().batch(20)\n    train_batch = iter(training_dataset)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"if 0:\n    # run this cell again for next set of images\n    display_batch_of_images(next(train_batch))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"if 0:\n    # peek at test data\n    test_dataset = get_test_dataset(test_ds)\n    test_dataset = test_dataset.unbatch().batch(20)\n    test_batch = iter(test_dataset)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"if 0:\n    # run this cell again for next set of images\n    display_batch_of_images(next(test_batch))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"if 0:\n    images, labels = next(iter(training_dataset.take(1)))\n    new_images, new_labels = batch_cutmix(images, labels, PROBABILITY=1.0, batch_size=20)\n    display_batch_of_images((new_images, new_labels))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"if 0:\n    images, labels = next(iter(training_dataset.take(1)))\n    new_images, new_labels = batch_mixup(images, labels, PROBABILITY=1.0, batch_size=20)\n    display_batch_of_images((new_images, new_labels))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"LR_START = 0.00003\nLR_MAX = 0.00005 * strategy.num_replicas_in_sync\nLR_MIN = 0.00001\nLR_RAMPUP_EPOCHS = 5\nLR_SUSTAIN_EPOCHS = 3\nLR_EXP_DECAY = .8\n        \n@tf.function\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\nrng = [i for i in range(EPOCHS)]\ny = [lrfn(x) for x in rng]\nplt.plot(rng, y)\nprint(\"Learning rate schedule: {:.3g} to {:.3g} to {:.3g}\".format(y[0], max(y), y[-1]))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**DenseNet**"},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    pretrained_model = tf.keras.applications.DenseNet201(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])\n    pretrained_model.trainable = True # False = transfer learning, True = fine-tuning\n    \n    model1 = tf.keras.Sequential([\n        pretrained_model,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    ])\n        \n    class LRSchedule(tf.keras.optimizers.schedules.LearningRateSchedule):\n        def __call__(self, step):\n            return lrfn(epoch=step//STEPS_PER_EPOCH)\n        \n    optimizer1 = tf.keras.optimizers.Adam(learning_rate=LRSchedule())\n    #optimizer = tfa.optimizers.AdamW(learning_rate=lr, weight_decay=wd)\n\n    model1.compile(\n        #optimizer='adam',\n        optimizer = optimizer1,\n        loss = 'sparse_categorical_crossentropy',\n        metrics=['sparse_categorical_accuracy']\n    )\n    model1.summary()\n        \n    train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()\n    valid_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()\n    train_loss = tf.keras.metrics.Sum()\n    valid_loss = tf.keras.metrics.Sum()\n    \n    loss_fn = lambda a,b: tf.nn.compute_average_loss(tf.keras.losses.sparse_categorical_crossentropy(a,b), global_batch_size=BATCH_SIZE)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"if tpu:\n    STEPS_PER_TPU_CALL = 99\n    VALIDATION_STEPS_PER_TPU_CALL = 29\n\n    @tf.function\n    def train_step(model, optimizer, data_iter):\n        def train_step_fn(images, labels):\n            with tf.GradientTape() as tape:\n                probabilities = model(images, training=True)\n                loss = loss_fn(labels, probabilities)\n            grads = tape.gradient(loss, model.trainable_variables)\n            optimizer.apply_gradients(zip(grads, model.trainable_variables))\n\n            train_accuracy.update_state(labels, probabilities)\n            train_loss.update_state(loss)\n\n        for _ in tf.range(STEPS_PER_TPU_CALL):\n            strategy.experimental_run_v2(train_step_fn, next(data_iter))\n\n    @tf.function\n    def valid_step(model, data_iter):\n        def valid_step_fn(images, labels):\n            probabilities = model(images, training=False)\n            loss = loss_fn(labels, probabilities)\n\n            valid_accuracy.update_state(labels, probabilities)\n            valid_loss.update_state(loss)\n\n        for _ in tf.range(VALIDATION_STEPS_PER_TPU_CALL):\n            strategy.experimental_run_v2(valid_step_fn, next(data_iter))\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Training"},{"metadata":{},"cell_type":"markdown","source":"**Model1 (DenseNet)**"},{"metadata":{"trusted":true},"cell_type":"code","source":"EPOCHS = 24 #override global setting\nstart_time = epoch_start_time = time.time()\n\nif tpu:\n    train_dist_ds = strategy.experimental_distribute_dataset(get_training_dataset(train_ds, simple_aug=True, advance_aug=True, cut_mix_aug=0))\n    valid_dist_ds = strategy.experimental_distribute_dataset(get_validation_dataset(valid_ds, repeated=True)) if not SKIP_VALIDATION else None\n\n    print(\"Training steps per epoch:\", STEPS_PER_EPOCH, \"in increment of:\", STEPS_PER_TPU_CALL)\n    if not SKIP_VALIDATION:\n        print(\"Validation images:\", NUM_VALIDATION_IMAGES,\n              \"Batch size:\", BATCH_SIZE,\n              \"Validation steps:\", NUM_VALIDATION_IMAGES//BATCH_SIZE, \"in increments of\", VALIDATION_STEPS_PER_TPU_CALL)\n        print(\"Repeated validation images:\", int_div_round_up(NUM_VALIDATION_IMAGES, BATCH_SIZE*VALIDATION_STEPS_PER_TPU_CALL)*VALIDATION_STEPS_PER_TPU_CALL*BATCH_SIZE-NUM_VALIDATION_IMAGES)\n\n    History = namedtuple('History', 'history')\n    history = History(history={'loss': [], 'val_loss': [], 'sparse_categorical_accuracy': [], 'val_sparse_categorical_accuracy': []}) if not SKIP_VALIDATION else History(history={'loss': [], 'val_loss': [], 'sparse_categorical_accuracy': []})\n\n    epoch = 0\n    train_data_iter = iter(train_dist_ds)\n    valid_data_iter = iter(valid_dist_ds) if not SKIP_VALIDATION else None\n\n    step = 0\n    epoch_steps = 0\n    while True:\n        train_step(model1, optimizer1, train_data_iter)\n        epoch_steps += STEPS_PER_TPU_CALL\n        step += STEPS_PER_TPU_CALL\n        print('=', end='', flush=True)\n\n        if (step//STEPS_PER_EPOCH) > epoch:\n            print('|', end='', flush=True)\n\n            if not SKIP_VALIDATION:\n                valid_epoch_steps = 0\n            #for _ in range(int_div_round_up(NUM_VALIDATION_IMAGES, BATCH_SIZE*VALIDATION_STEPS_PER_TPU_CALL)):\n            #    valid_step(valid_data_iter)\n            #    valid_epoch_steps += VALIDATION_STEPS_PER_TPU_CALL\n            #    print('=', end='', flush=True)\n\n                valid_step(model1, valid_data_iter)\n                valid_epoch_steps += VALIDATION_STEPS_PER_TPU_CALL\n                print('=', end='', flush=True)\n                \n                history.history['val_sparse_categorical_accuracy'].append(valid_accuracy.result().numpy())\n                history.history['val_loss'].append(valid_loss.result().numpy() / VALIDATION_STEPS)\n            \n            history.history['sparse_categorical_accuracy'].append(train_accuracy.result().numpy())\n            #history.history['val_sparse_categorical_accuracy'].append(valid_accuracy.result().numpy())\n            history.history['loss'].append(train_loss.result().numpy() / STEPS_PER_EPOCH)\n            #history.history['val_loss'].append(valid_loss.result().numpy() / VALIDATION_STEPS)\n\n            epoch_time = time.time() - epoch_start_time\n            print('\\nEPOCH {:d}/{:d}'.format(epoch+1, EPOCHS))\n            if not SKIP_VALIDATION:\n                print('time: {:0.1f}s'.format(epoch_time),\n                        'loss: {:0.4f}'.format(history.history['loss'][-1]),\n                        'accuracy: {:0.4f}'.format(history.history['sparse_categorical_accuracy'][-1]),\n                        'val_loss: {:0.4f}'.format(history.history['val_loss'][-1]),\n                        'val_acc: {:0.4f}'.format(history.history['val_sparse_categorical_accuracy'][-1]),\n                        'lr: {:0.4g}'.format(lrfn(epoch)), flush=True)\n            else:\n                print('time: {:0.1f}s'.format(epoch_time),\n                        'loss: {:0.4f}'.format(history.history['loss'][-1]),\n                        'accuracy: {:0.4f}'.format(history.history['sparse_categorical_accuracy'][-1]),\n                        'lr: {:0.4g}'.format(lrfn(epoch)), flush=True)\n\n\n            epoch = (step+1) // STEPS_PER_EPOCH\n            epoch_start_time = time.time()\n            train_accuracy.reset_states()\n            if not SKIP_VALIDATION:\n                valid_accuracy.reset_states()\n                valid_loss.reset_states()\n            train_loss.reset_states()\n\n            if epoch >= EPOCHS:\n                break\n\nelse:\n    EPOCHS = 15\n    history = model1.fit(\n    get_training_dataset(train_ds), \n    steps_per_epoch=STEPS_PER_EPOCH,\n    epochs=EPOCHS,\n    #callbacks=[lr_callback],\n    validation_data=get_validation_dataset(valid_ds) if not SKIP_VALIDATION else None\n)\n    \nsimple_ctl_training_time = time.time() - start_time\nprint(\"OPTIMIZED CTL TRAINING TIME: {:0.1f}s\".format(simple_ctl_training_time))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model1.save_weights('densenet-flower-tpu.hdf5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"if not SKIP_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)\nelse:\n    display_training_curves(history.history['loss'], history.history['loss'], 'loss', 211)\n    display_training_curves(history.history['sparse_categorical_accuracy'], history.history['sparse_categorical_accuracy'], 'accuracy', 212)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_ds = get_test_dataset(ordered=True)\ntest_images_ds = test_ds.map(lambda image, idnum: image)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print('Computing predictions model1...')\npreds1 = model1.predict(test_images_ds)\ndel model1\ngc.collect()\n\ntf.tpu.experimental.initialize_tpu_system(tpu)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Get different data set for model2"},{"metadata":{"trusted":true},"cell_type":"code","source":"SIZE = 331\nIMAGE_SIZE = [SIZE, SIZE]\n\nTRAINING_FILENAMES, VALIDATION_FILENAMES, TEST_FILENAMES = get_filenames(SIZE)\nprint(len(TRAINING_FILENAMES))\n\nif USE_EXTERNAL:\n    EXT_TRAINING_FILENAMES = get_ext_filenames(SIZE, imagenet=False, inaturalist=False, openimage=True, oxford=True, tfflowers=True)\n    print(len(EXT_TRAINING_FILENAMES))\n    \nif USE_EXTERNAL:\n    TRAINING_FILENAMES = TRAINING_FILENAMES + EXT_TRAINING_FILENAMES\n\nif SKIP_VALIDATION:\n    TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES\n    \nNUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)\nNUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES) if not SKIP_VALIDATION else 0\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\nVALIDATION_STEPS = int_div_round_up(NUM_VALIDATION_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":{"trusted":true},"cell_type":"code","source":"train_ds = load_dataset(TRAINING_FILENAMES, labeled=True)\nvalid_ds = load_dataset(VALIDATION_FILENAMES, labeled=True) if not SKIP_VALIDATION else None","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**EfficientNet**"},{"metadata":{"trusted":true},"cell_type":"code","source":"import efficientnet.tfkeras as efn","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    pretrained_model2 = efn.EfficientNetB7(weights='noisy-student', include_top=False ,input_shape=[*IMAGE_SIZE, 3])\n    pretrained_model2.trainable = True # False = transfer learning, True = fine-tuning\n    \n    model2 = tf.keras.Sequential([\n        pretrained_model2,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    ])\n        \n    class LRSchedule(tf.keras.optimizers.schedules.LearningRateSchedule):\n        def __call__(self, step):\n            return lrfn(epoch=step//STEPS_PER_EPOCH)\n        \n    optimizer2 = tf.keras.optimizers.Adam(learning_rate=LRSchedule())\n    #optimizer = tfa.optimizers.AdamW(learning_rate=lr, weight_decay=wd)\n\n    model2.compile(\n        #optimizer='adam',\n        optimizer = optimizer2,\n        loss = 'sparse_categorical_crossentropy',\n        metrics=['sparse_categorical_accuracy']\n    )\n    model2.summary()\n        \n    train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()\n    valid_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()\n    train_loss = tf.keras.metrics.Sum()\n    valid_loss = tf.keras.metrics.Sum()\n    \n    loss_fn = lambda a,b: tf.nn.compute_average_loss(tf.keras.losses.sparse_categorical_crossentropy(a,b), global_batch_size=BATCH_SIZE)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"if tpu:\n    STEPS_PER_TPU_CALL = 99\n    VALIDATION_STEPS_PER_TPU_CALL = 29\n\n    @tf.function\n    def train_step2(model, optimizer, data_iter):\n        def train_step_fn(images, labels):\n            with tf.GradientTape() as tape:\n                probabilities = model(images, training=True)\n                loss = loss_fn(labels, probabilities)\n            grads = tape.gradient(loss, model.trainable_variables)\n            optimizer.apply_gradients(zip(grads, model.trainable_variables))\n\n            train_accuracy.update_state(labels, probabilities)\n            train_loss.update_state(loss)\n\n        for _ in tf.range(STEPS_PER_TPU_CALL):\n            strategy.experimental_run_v2(train_step_fn, next(data_iter))\n\n    @tf.function\n    def valid_step2(model, data_iter):\n        def valid_step_fn(images, labels):\n            probabilities = model(images, training=False)\n            loss = loss_fn(labels, probabilities)\n\n            valid_accuracy.update_state(labels, probabilities)\n            valid_loss.update_state(loss)\n\n        for _ in tf.range(VALIDATION_STEPS_PER_TPU_CALL):\n            strategy.experimental_run_v2(valid_step_fn, next(data_iter))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"start_time = epoch_start_time = time.time()\n\nif tpu:\n    train_dist_ds = strategy.experimental_distribute_dataset(get_training_dataset(train_ds, simple_aug=True, advance_aug=True, cut_mix_aug=0))\n    valid_dist_ds = strategy.experimental_distribute_dataset(get_validation_dataset(valid_ds, repeated=True)) if not SKIP_VALIDATION else None\n\n    print(\"Training steps per epoch:\", STEPS_PER_EPOCH, \"in increment of:\", STEPS_PER_TPU_CALL)\n    if not SKIP_VALIDATION:\n        print(\"Validation images:\", NUM_VALIDATION_IMAGES,\n              \"Batch size:\", BATCH_SIZE,\n              \"Validation steps:\", NUM_VALIDATION_IMAGES//BATCH_SIZE, \"in increments of\", VALIDATION_STEPS_PER_TPU_CALL)\n        print(\"Repeated validation images:\", int_div_round_up(NUM_VALIDATION_IMAGES, BATCH_SIZE*VALIDATION_STEPS_PER_TPU_CALL)*VALIDATION_STEPS_PER_TPU_CALL*BATCH_SIZE-NUM_VALIDATION_IMAGES)\n\n    History = namedtuple('History', 'history')\n    history = History(history={'loss': [], 'val_loss': [], 'sparse_categorical_accuracy': [], 'val_sparse_categorical_accuracy': []}) if not SKIP_VALIDATION else History(history={'loss': [], 'val_loss': [], 'sparse_categorical_accuracy': []})\n\n    epoch = 0\n    train_data_iter = iter(train_dist_ds)\n    valid_data_iter = iter(valid_dist_ds) if not SKIP_VALIDATION else None\n\n    step = 0\n    epoch_steps = 0\n    while True:\n        train_step2(model2, optimizer2, train_data_iter)\n        epoch_steps += STEPS_PER_TPU_CALL\n        step += STEPS_PER_TPU_CALL\n        print('=', end='', flush=True)\n\n        if (step//STEPS_PER_EPOCH) > epoch:\n            print('|', end='', flush=True)\n\n            if not SKIP_VALIDATION:\n                valid_epoch_steps = 0\n            #for _ in range(int_div_round_up(NUM_VALIDATION_IMAGES, BATCH_SIZE*VALIDATION_STEPS_PER_TPU_CALL)):\n            #    valid_step(valid_data_iter)\n            #    valid_epoch_steps += VALIDATION_STEPS_PER_TPU_CALL\n            #    print('=', end='', flush=True)\n\n                valid_step2(model2, valid_data_iter)\n                valid_epoch_steps += VALIDATION_STEPS_PER_TPU_CALL\n                print('=', end='', flush=True)\n                \n                history.history['val_sparse_categorical_accuracy'].append(valid_accuracy.result().numpy())\n                history.history['val_loss'].append(valid_loss.result().numpy() / VALIDATION_STEPS)\n            \n            history.history['sparse_categorical_accuracy'].append(train_accuracy.result().numpy())\n            #history.history['val_sparse_categorical_accuracy'].append(valid_accuracy.result().numpy())\n            history.history['loss'].append(train_loss.result().numpy() / STEPS_PER_EPOCH)\n            #history.history['val_loss'].append(valid_loss.result().numpy() / VALIDATION_STEPS)\n\n            epoch_time = time.time() - epoch_start_time\n            print('\\nEPOCH {:d}/{:d}'.format(epoch+1, EPOCHS))\n            if not SKIP_VALIDATION:\n                print('time: {:0.1f}s'.format(epoch_time),\n                        'loss: {:0.4f}'.format(history.history['loss'][-1]),\n                        'accuracy: {:0.4f}'.format(history.history['sparse_categorical_accuracy'][-1]),\n                        'val_loss: {:0.4f}'.format(history.history['val_loss'][-1]),\n                        'val_acc: {:0.4f}'.format(history.history['val_sparse_categorical_accuracy'][-1]),\n                        'lr: {:0.4g}'.format(lrfn(epoch)), flush=True)\n            else:\n                print('time: {:0.1f}s'.format(epoch_time),\n                        'loss: {:0.4f}'.format(history.history['loss'][-1]),\n                        'accuracy: {:0.4f}'.format(history.history['sparse_categorical_accuracy'][-1]),\n                        'lr: {:0.4g}'.format(lrfn(epoch)), flush=True)\n\n\n            epoch = (step+1) // STEPS_PER_EPOCH\n            epoch_start_time = time.time()\n            train_accuracy.reset_states()\n            if not SKIP_VALIDATION:\n                valid_accuracy.reset_states()\n                valid_loss.reset_states()\n            train_loss.reset_states()\n\n            if epoch >= EPOCHS:\n                break\n\nelse:\n    EPOCHS = 15\n    history = model2.fit(\n    get_training_dataset(train_ds), \n    steps_per_epoch=STEPS_PER_EPOCH,\n    epochs=EPOCHS,\n    #callbacks=[lr_callback],\n    validation_data=get_validation_dataset(valid_ds) if not SKIP_VALIDATION else None\n)\n    \nsimple_ctl_training_time = time.time() - start_time\nprint(\"OPTIMIZED CTL TRAINING TIME: {:0.1f}s\".format(simple_ctl_training_time))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model2.save_weights('effnetb7-flower-tpu.hdf5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"if not SKIP_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)\nelse:\n    display_training_curves(history.history['loss'], history.history['loss'], 'loss', 211)\n    display_training_curves(history.history['sparse_categorical_accuracy'], history.history['sparse_categorical_accuracy'], 'accuracy', 212)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_ds = get_test_dataset(ordered=True)\ntest_images_ds = test_ds.map(lambda image, idnum: image)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print('Computing predictions model2...')\npreds2 = model2.predict(test_images_ds)\ndel model2\ngc.collect()\n\ntf.tpu.experimental.initialize_tpu_system(tpu)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Use size=512 and some external data for EffNetB6**"},{"metadata":{"trusted":true},"cell_type":"code","source":"SIZE = 512\nIMAGE_SIZE = [SIZE, SIZE]\nSKIP_VALIDATION = True\n\nTRAINING_FILENAMES, VALIDATION_FILENAMES, TEST_FILENAMES = get_filenames(SIZE)\nprint(len(TRAINING_FILENAMES))\n\nif USE_EXTERNAL:\n    EXT_TRAINING_FILENAMES = get_ext_filenames(SIZE, imagenet=False, inaturalist=True, openimage=False, oxford=False, tfflowers=True)\n    print(len(EXT_TRAINING_FILENAMES))\n    \nif USE_EXTERNAL:\n    TRAINING_FILENAMES = TRAINING_FILENAMES + EXT_TRAINING_FILENAMES\n\nif SKIP_VALIDATION:\n    TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES\n    \nNUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)\nNUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES) if not SKIP_VALIDATION else 0\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\nVALIDATION_STEPS = int_div_round_up(NUM_VALIDATION_IMAGES, BATCH_SIZE)\nprint('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))\n\ntrain_ds = load_dataset(TRAINING_FILENAMES, labeled=True)\nvalid_ds = load_dataset(VALIDATION_FILENAMES, labeled=True) if not SKIP_VALIDATION else None","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    pretrained_model3 = efn.EfficientNetB6(weights='noisy-student', include_top=False ,input_shape=[*IMAGE_SIZE, 3])\n    pretrained_model3.trainable = True # False = transfer learning, True = fine-tuning\n    \n    model3 = tf.keras.Sequential([\n        pretrained_model3,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    ])\n        \n    class LRSchedule(tf.keras.optimizers.schedules.LearningRateSchedule):\n        def __call__(self, step):\n            return lrfn(epoch=step//STEPS_PER_EPOCH)\n        \n    optimizer3 = tf.keras.optimizers.Adam(learning_rate=LRSchedule())\n    #optimizer = tfa.optimizers.AdamW(learning_rate=lr, weight_decay=wd)\n\n    model3.compile(\n        #optimizer='adam',\n        optimizer = optimizer3,\n        loss = 'sparse_categorical_crossentropy',\n        metrics=['sparse_categorical_accuracy']\n    )\n    model3.summary()\n        \n    train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()\n    valid_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()\n    train_loss = tf.keras.metrics.Sum()\n    valid_loss = tf.keras.metrics.Sum()\n    \n    loss_fn = lambda a,b: tf.nn.compute_average_loss(tf.keras.losses.sparse_categorical_crossentropy(a,b), global_batch_size=BATCH_SIZE)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"if tpu:\n    STEPS_PER_TPU_CALL = 99\n    VALIDATION_STEPS_PER_TPU_CALL = 29\n\n    @tf.function\n    def train_step3(model, optimizer, data_iter):\n        def train_step_fn(images, labels):\n            with tf.GradientTape() as tape:\n                probabilities = model(images, training=True)\n                loss = loss_fn(labels, probabilities)\n            grads = tape.gradient(loss, model.trainable_variables)\n            optimizer.apply_gradients(zip(grads, model.trainable_variables))\n\n            train_accuracy.update_state(labels, probabilities)\n            train_loss.update_state(loss)\n\n        for _ in tf.range(STEPS_PER_TPU_CALL):\n            strategy.experimental_run_v2(train_step_fn, next(data_iter))\n\n    @tf.function\n    def valid_step3(model, data_iter):\n        def valid_step_fn(images, labels):\n            probabilities = model(images, training=False)\n            loss = loss_fn(labels, probabilities)\n\n            valid_accuracy.update_state(labels, probabilities)\n            valid_loss.update_state(loss)\n\n        for _ in tf.range(VALIDATION_STEPS_PER_TPU_CALL):\n            strategy.experimental_run_v2(valid_step_fn, next(data_iter))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"start_time = epoch_start_time = time.time()\n\nif tpu:\n    train_dist_ds = strategy.experimental_distribute_dataset(get_training_dataset(train_ds, simple_aug=True, advance_aug=True, cut_mix_aug=0))\n    valid_dist_ds = strategy.experimental_distribute_dataset(get_validation_dataset(valid_ds, repeated=True)) if not SKIP_VALIDATION else None\n\n    print(\"Training steps per epoch:\", STEPS_PER_EPOCH, \"in increment of:\", STEPS_PER_TPU_CALL)\n    if not SKIP_VALIDATION:\n        print(\"Validation images:\", NUM_VALIDATION_IMAGES,\n              \"Batch size:\", BATCH_SIZE,\n              \"Validation steps:\", NUM_VALIDATION_IMAGES//BATCH_SIZE, \"in increments of\", VALIDATION_STEPS_PER_TPU_CALL)\n        print(\"Repeated validation images:\", int_div_round_up(NUM_VALIDATION_IMAGES, BATCH_SIZE*VALIDATION_STEPS_PER_TPU_CALL)*VALIDATION_STEPS_PER_TPU_CALL*BATCH_SIZE-NUM_VALIDATION_IMAGES)\n\n    History = namedtuple('History', 'history')\n    history = History(history={'loss': [], 'val_loss': [], 'sparse_categorical_accuracy': [], 'val_sparse_categorical_accuracy': []}) if not SKIP_VALIDATION else History(history={'loss': [], 'val_loss': [], 'sparse_categorical_accuracy': []})\n\n    epoch = 0\n    train_data_iter = iter(train_dist_ds)\n    valid_data_iter = iter(valid_dist_ds) if not SKIP_VALIDATION else None\n\n    step = 0\n    epoch_steps = 0\n    while True:\n        train_step3(model3, optimizer3, train_data_iter)\n        epoch_steps += STEPS_PER_TPU_CALL\n        step += STEPS_PER_TPU_CALL\n        print('=', end='', flush=True)\n\n        if (step//STEPS_PER_EPOCH) > epoch:\n            print('|', end='', flush=True)\n\n            if not SKIP_VALIDATION:\n                valid_epoch_steps = 0\n                valid_step3(model3, valid_data_iter)\n                valid_epoch_steps += VALIDATION_STEPS_PER_TPU_CALL\n                print('=', end='', flush=True)\n                \n                history.history['val_sparse_categorical_accuracy'].append(valid_accuracy.result().numpy())\n                history.history['val_loss'].append(valid_loss.result().numpy() / VALIDATION_STEPS)\n            \n            history.history['sparse_categorical_accuracy'].append(train_accuracy.result().numpy())\n            #history.history['val_sparse_categorical_accuracy'].append(valid_accuracy.result().numpy())\n            history.history['loss'].append(train_loss.result().numpy() / STEPS_PER_EPOCH)\n            #history.history['val_loss'].append(valid_loss.result().numpy() / VALIDATION_STEPS)\n\n            epoch_time = time.time() - epoch_start_time\n            print('\\nEPOCH {:d}/{:d}'.format(epoch+1, EPOCHS))\n            if not SKIP_VALIDATION:\n                print('time: {:0.1f}s'.format(epoch_time),\n                        'loss: {:0.4f}'.format(history.history['loss'][-1]),\n                        'accuracy: {:0.4f}'.format(history.history['sparse_categorical_accuracy'][-1]),\n                        'val_loss: {:0.4f}'.format(history.history['val_loss'][-1]),\n                        'val_acc: {:0.4f}'.format(history.history['val_sparse_categorical_accuracy'][-1]),\n                        'lr: {:0.4g}'.format(lrfn(epoch)), flush=True)\n            else:\n                print('time: {:0.1f}s'.format(epoch_time),\n                        'loss: {:0.4f}'.format(history.history['loss'][-1]),\n                        'accuracy: {:0.4f}'.format(history.history['sparse_categorical_accuracy'][-1]),\n                        'lr: {:0.4g}'.format(lrfn(epoch)), flush=True)\n\n\n            epoch = (step+1) // STEPS_PER_EPOCH\n            epoch_start_time = time.time()\n            train_accuracy.reset_states()\n            if not SKIP_VALIDATION:\n                valid_accuracy.reset_states()\n                valid_loss.reset_states()\n            train_loss.reset_states()\n\n            if epoch >= EPOCHS:\n                break\n\nelse:\n    EPOCHS = 15\n    history = model3.fit(\n    get_training_dataset(train_ds), \n    steps_per_epoch=STEPS_PER_EPOCH,\n    epochs=EPOCHS,\n    #callbacks=[lr_callback],\n    validation_data=get_validation_dataset(valid_ds) if not SKIP_VALIDATION else None\n)\n    \nsimple_ctl_training_time = time.time() - start_time\nprint(\"OPTIMIZED CTL TRAINING TIME: {:0.1f}s\".format(simple_ctl_training_time))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model3.save_weights('effnetb6-flower-tpu.hdf5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"if not SKIP_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)\nelse:\n    display_training_curves(history.history['loss'], history.history['loss'], 'loss', 211)\n    display_training_curves(history.history['sparse_categorical_accuracy'], history.history['sparse_categorical_accuracy'], 'accuracy', 212)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_ds = get_test_dataset(ordered=True)\ntest_images_ds = test_ds.map(lambda image, idnum: image)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print('Computing predictions model3...')\npreds3 = model3.predict(test_images_ds)\ndel model3\ngc.collect()\n\ntf.tpu.experimental.initialize_tpu_system(tpu)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Confusion matrix"},{"metadata":{"trusted":true},"cell_type":"code","source":"if 0 and not SKIP_VALIDATION:\n    cmdataset = get_validation_dataset(load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=True), ordered=True) # since we are splitting the dataset and iterating separately on images and labels, order matters.\n    images_ds = cmdataset.map(lambda image, label: image)\n    labels_ds = cmdataset.map(lambda image, label: label).unbatch()\n    cm_correct_labels = next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES))).numpy() # get everything as one batch\n    cm_probabilities = (model1.predict(images_ds)+model2.predict(images_ds))/2\n    cm_predictions = np.argmax(cm_probabilities, axis=-1)\n    print(\"Correct   labels: \", cm_correct_labels.shape, cm_correct_labels)\n    print(\"Predicted labels: \", cm_predictions.shape, cm_predictions)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"if 0 and not SKIP_VALIDATION:\n    cmat = confusion_matrix(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)))\n    score = f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)), average='macro')\n    precision = precision_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)), average='macro')\n    recall = recall_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)), average='macro')\n    cmat = (cmat.T / cmat.sum(axis=1)).T # normalized\n    display_confusion_matrix(cmat, score, precision, recall)\n    print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Predictions"},{"metadata":{"trusted":true},"cell_type":"code","source":"alpha = 0.55","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#test_ds = get_test_dataset(ordered=True) # since we are splitting the dataset and iterating separately on images and ids, order matters.\n\nprint('Computing predictions...')\n#test_images_ds = test_ds.map(lambda image, idnum: image)\n#probabilities = alpha * model1.predict(test_images_ds) + (1-alpha) * model2.predict(test_images_ds)\nprobabilities = 0.45 * (alpha * preds1 + (1-alpha) * preds2) + 0.55 * preds3\npredictions = np.argmax(probabilities, axis=-1)\nprint(predictions)\n\nprint('Generating submission.csv file...')\ntest_ids_ds = test_ds.map(lambda image, idnum: idnum).unbatch()\ntest_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U') # all in one batch\nnp.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')\n!head submission.csv","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Visual validation"},{"metadata":{"trusted":true},"cell_type":"code","source":"if 0 and not SKIP_VALIDATION:\n    dataset = get_validation_dataset(valid_ds)\n    dataset = dataset.unbatch().batch(20)\n    batch = iter(dataset)\n    \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":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}