{"cells":[{"metadata":{},"cell_type":"markdown","source":"# About this kernel\n\n* Implement CutMix, MixUp and GridMask in batch.\n* Comparing timings - Batch operations are about 5x - 10x faster.\n* The batch implemention for GridMask is kind partial. For a batch, grid width are fixed in that batch, but rotation angle can be random.\n* References: \n\n    * [CutMix and MixUp on GPU/TPU (by Chris Deotte)](https://www.kaggle.com/cdeotte/cutmix-and-mixup-on-gpu-tpu)\n    * [GridMask data augmentation with tensorflow (by Xie29)](https://www.kaggle.com/xiejialun/gridmask-data-augmentation-with-tensorflow)\n","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"# Common","execution_count":null},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import tensorflow as tf\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport re\nimport math\nimport datetime\nfrom kaggle_datasets import KaggleDatasets\nimport tensorflow.keras.backend as K\nAUTO = tf.data.experimental.AUTOTUNE","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image_size = 192\nIMAGE_SIZE = [image_size, image_size]\nBATCH_SIZE = 64\nAUG_BATCH = BATCH_SIZE\n\n# Data access\nGCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')\n\n\nGCS_PATH_SELECT = { # available image sizes\n    192: GCS_DS_PATH + '/tfrecords-jpeg-192x192'\n\n}\nGCS_PATH = GCS_PATH_SELECT[IMAGE_SIZE[0]]\n\nTRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec')\n\ndef 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 load_dataset(filenames, labeled = True, ordered = False):\n    # Read from TFRecords. For optimal performance, reading from multiple files at once and\n    # Diregarding 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) # use 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) # returns a dataset of (image, label) pairs if labeled = True or (image, id) pair if labeld = False\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\nNUM_TRAINING_IMAGES = int(count_data_items(TRAINING_FILENAMES))\n\nprint('Dataset: {} training images'.format(NUM_TRAINING_IMAGES))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def batch_to_numpy_images_and_labels(data):\n    \n    images = data\n    numpy_images = images.numpy()\n\n    # If no labels, only image IDs, return None for labels (this is the case for test data)\n    return numpy_images\n\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\n\ndef display_batch_of_images(databatch, predictions=None):\n    \n    \"\"\"This will work with:\n    display_batch_of_images(images)\n    \"\"\"\n    \n    # data\n    images = batch_to_numpy_images_and_labels(databatch)\n    labels = None\n    \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()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_training_dataset(dataset, batch_size=None, advanced_aug=True, repeat=True, with_labels=True, drop_remainder=False):\n    \n    if not with_labels:\n        dataset = dataset.map(lambda image, label: image, num_parallel_calls=AUTO)\n    \n    if advanced_aug:\n        dataset = dataset.map(transform, num_parallel_calls=AUTO)\n    \n    if type(repeat) == bool and repeat:\n        dataset = dataset.repeat() # the training dataset must repeat for several epochs\n    elif type(repeat) == int and repeat > 0:\n        dataset = dataset.repeat(repeat)\n    \n    dataset = dataset.shuffle(2048)\n    \n    if batch_size is None:\n        batch_size = BATCH_SIZE\n    \n    dataset = dataset.batch(batch_size, drop_remainder=drop_remainder)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    \n    return dataset","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dataset = load_dataset(TRAINING_FILENAMES, labeled=True)\ntraining_dataset = get_training_dataset(dataset, advanced_aug=False, repeat=1, with_labels=True)\n\nimages, labels = next(iter(training_dataset.take(1)))\nprint(images.shape)\n\ndisplay_batch_of_images(images)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Original CutMix","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def cutmix(images, label, PROBABILITY = 1.0):\n    \n    # input images - is a batch of imagess of size [n,dim,dim,3] not a single images of [dim,dim,3]\n    # output - a batch of imagess with cutmix applied\n    DIM = IMAGE_SIZE[0]\n    CLASSES = 104\n    \n    imgs = []; labs = []\n    for j in range(AUG_BATCH):\n        # DO CUTMIX WITH PROBABILITY DEFINED ABOVE\n        P = tf.cast( tf.random.uniform([],0,1)<=PROBABILITY, tf.int32)\n        # CHOOSE RANDOM images TO CUTMIX WITH\n        k = tf.cast( tf.random.uniform([],0,AUG_BATCH),tf.int32)\n        # CHOOSE RANDOM LOCATION\n        x = tf.cast( tf.random.uniform([],0,DIM),tf.int32)\n        y = tf.cast( tf.random.uniform([],0,DIM),tf.int32)\n        b = tf.random.uniform([],0,1) # this is beta dist with alpha=1.0\n        WIDTH = tf.cast( DIM * tf.math.sqrt(1-b),tf.int32) * P\n        ya = tf.math.maximum(0,y-WIDTH//2)\n        yb = tf.math.minimum(DIM,y+WIDTH//2)\n        xa = tf.math.maximum(0,x-WIDTH//2)\n        xb = tf.math.minimum(DIM,x+WIDTH//2)\n        # MAKE CUTMIX images\n        one = images[j,ya:yb,0:xa,:]\n        two = images[k,ya:yb,xa:xb,:]\n        three = images[j,ya:yb,xb:DIM,:]\n        middle = tf.concat([one,two,three],axis=1)\n        img = tf.concat([images[j,0:ya,:,:],middle,images[j,yb:DIM,:,:]],axis=0)\n        imgs.append(img)\n        # MAKE CUTMIX LABEL\n        a = tf.cast(WIDTH*WIDTH/DIM/DIM,tf.float32)\n        if len(label.shape)==1:\n            lab1 = tf.one_hot(label[j],CLASSES)\n            lab2 = tf.one_hot(label[k],CLASSES)\n        else:\n            lab1 = label[j,]\n            lab2 = label[k,]\n        labs.append((1-a)*lab1 + a*lab2)\n            \n    # RESHAPE HACK SO TPU COMPILER KNOWS SHAPE OF OUTPUT TENSOR (maybe use Python typing instead?)\n    images2 = tf.reshape(tf.stack(imgs),(AUG_BATCH,DIM,DIM,3))\n    label2 = tf.reshape(tf.stack(labs),(AUG_BATCH,CLASSES))\n    return images2,label2","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"new_images, new_labels = cutmix(images, labels, PROBABILITY=1.0)\ndisplay_batch_of_images(new_images)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Batch CutMix","execution_count":null},{"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 = BATCH_SIZE\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":"new_images, new_labels = batch_cutmix(images, labels, PROBABILITY=1.0)\ndisplay_batch_of_images(new_images)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Compare timing for CutMix","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"n_iter = 1000\n\nstart = datetime.datetime.now()\nfor i in range(n_iter):\n    batch_cutmix(images, labels, PROBABILITY=1.0) \nend = datetime.datetime.now()\ntiming = (end - start).total_seconds() / n_iter\nprint(f\"batch_cutmix: {timing}\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"start = datetime.datetime.now()\nfor i in range(n_iter):\n    cutmix(images, labels, PROBABILITY=1.0) \nend = datetime.datetime.now()\ntiming = (end - start).total_seconds() / n_iter\nprint(f\"cutmix: {timing}\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Original MixUP","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def mixup(image, label, PROBABILITY = 1.0):\n    # input image - is a batch of images of size [n,dim,dim,3] not a single image of [dim,dim,3]\n    # output - a batch of images with mixup applied\n    DIM = IMAGE_SIZE[0]\n    CLASSES = 104\n    \n    imgs = []; labs = []\n    for j in range(AUG_BATCH):\n        # DO MIXUP WITH PROBABILITY DEFINED ABOVE\n        P = tf.cast( tf.random.uniform([],0,1)<=PROBABILITY, tf.float32)\n        # CHOOSE RANDOM\n        k = tf.cast( tf.random.uniform([],0,AUG_BATCH),tf.int32)\n        a = tf.random.uniform([],0,1)*P # this is beta dist with alpha=1.0\n        # MAKE MIXUP IMAGE\n        img1 = image[j,]\n        img2 = image[k,]\n        imgs.append((1-a)*img1 + a*img2)\n        # MAKE CUTMIX LABEL\n        if len(label.shape)==1:\n            lab1 = tf.one_hot(label[j],CLASSES)\n            lab2 = tf.one_hot(label[k],CLASSES)\n        else:\n            lab1 = label[j,]\n            lab2 = label[k,]\n        labs.append((1-a)*lab1 + a*lab2)\n            \n    # RESHAPE HACK SO TPU COMPILER KNOWS SHAPE OF OUTPUT TENSOR (maybe use Python typing instead?)\n    image2 = tf.reshape(tf.stack(imgs),(AUG_BATCH,DIM,DIM,3))\n    label2 = tf.reshape(tf.stack(labs),(AUG_BATCH,CLASSES))\n    return image2,label2","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"new_images, new_labels = mixup(images, labels, PROBABILITY=1.0)\ndisplay_batch_of_images(new_images)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Batch MixUP","execution_count":null},{"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 = BATCH_SIZE\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":"new_images, new_labels = batch_mixup(images, labels, PROBABILITY=1.0)\ndisplay_batch_of_images(new_images)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Compare timing for MixUp","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"start = datetime.datetime.now()\nfor i in range(n_iter):\n    batch_mixup(images, labels, PROBABILITY=1.0) \nend = datetime.datetime.now()\ntiming = (end - start).total_seconds() / n_iter\nprint(f\"batch_mixup: {timing}\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"start = datetime.datetime.now()\nfor i in range(n_iter):\n    mixup(images, labels, PROBABILITY=1.0) \nend = datetime.datetime.now()\ntiming = (end - start).total_seconds() / n_iter\nprint(f\"mixup: {timing}\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Original GridMask","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def transform(image, inv_mat, image_shape):\n\n    h, w, c = image_shape\n    cx, cy = w//2, h//2\n\n    new_xs = tf.repeat( tf.range(-cx, cx, 1), h)\n    new_ys = tf.tile( tf.range(-cy, cy, 1), [w])\n    new_zs = tf.ones([h*w], dtype=tf.int32)\n\n    old_coords = tf.matmul(inv_mat, tf.cast(tf.stack([new_xs, new_ys, new_zs]), tf.float32))\n    old_coords_x, old_coords_y = tf.round(old_coords[0, :] + w//2), tf.round(old_coords[1, :] + h//2)\n\n    clip_mask_x = tf.logical_or(old_coords_x<0, old_coords_x>w-1)\n    clip_mask_y = tf.logical_or(old_coords_y<0, old_coords_y>h-1)\n    clip_mask = tf.logical_or(clip_mask_x, clip_mask_y)\n\n    old_coords_x = tf.boolean_mask(old_coords_x, tf.logical_not(clip_mask))\n    old_coords_y = tf.boolean_mask(old_coords_y, tf.logical_not(clip_mask))\n    new_coords_x = tf.boolean_mask(new_xs+cx, tf.logical_not(clip_mask))\n    new_coords_y = tf.boolean_mask(new_ys+cy, tf.logical_not(clip_mask))\n\n    old_coords = tf.cast(tf.stack([old_coords_y, old_coords_x]), tf.int32)\n    new_coords = tf.cast(tf.stack([new_coords_y, new_coords_x]), tf.int64)\n    rotated_image_values = tf.gather_nd(image, tf.transpose(old_coords))\n    rotated_image_channel = list()\n    for i in range(c):\n        vals = rotated_image_values[:,i]\n        sparse_channel = tf.SparseTensor(tf.transpose(new_coords), vals, [h, w])\n        rotated_image_channel.append(tf.sparse.to_dense(sparse_channel, default_value=0, validate_indices=False))\n\n    return tf.transpose(tf.stack(rotated_image_channel), [1,2,0])\n\ndef random_rotate(image, angle, image_shape):\n\n    def get_rotation_mat_inv(angle):\n          #transform to radian\n        angle = math.pi * angle / 180\n\n        cos_val = tf.math.cos(angle)\n        sin_val = tf.math.sin(angle)\n        one = tf.constant([1], tf.float32)\n        zero = tf.constant([0], tf.float32)\n\n        rot_mat_inv = tf.concat([cos_val, sin_val, zero,\n                                     -sin_val, cos_val, zero,\n                                     zero, zero, one], axis=0)\n        rot_mat_inv = tf.reshape(rot_mat_inv, [3,3])\n\n        return rot_mat_inv\n    angle = float(angle) * tf.constant(1, shape=[1], dtype=tf.float32) # tf.random.normal([1],dtype='float32')\n    rot_mat_inv = get_rotation_mat_inv(angle)\n    return transform(image, rot_mat_inv, image_shape)\n\n\ndef GridMask(image_height, image_width, d1, d2, rotate_angle=1, ratio=0.5):\n\n    h, w = image_height, image_width\n    hh = int(np.ceil(np.sqrt(h*h+w*w)))\n    hh = hh+1 if hh%2==1 else hh\n    d = tf.random.uniform(shape=[], minval=d1, maxval=d2, dtype=tf.int32)\n    l = tf.cast(tf.cast(d,tf.float32)*ratio+0.5, tf.int32)\n\n    st_h = tf.random.uniform(shape=[], minval=0, maxval=d, dtype=tf.int32)\n    st_w = tf.random.uniform(shape=[], minval=0, maxval=d, dtype=tf.int32)\n    \n    st_h = 0\n    st_w = 0\n\n    y_ranges = tf.range(-1 * d + st_h, -1 * d + st_h + l)\n    x_ranges = tf.range(-1 * d + st_w, -1 * d + st_w + l)\n\n    for i in range(0, hh//d+1):\n        s1 = i * d + st_h\n        s2 = i * d + st_w\n        y_ranges = tf.concat([y_ranges, tf.range(s1,s1+l)], axis=0)\n        x_ranges = tf.concat([x_ranges, tf.range(s2,s2+l)], axis=0)\n\n    x_clip_mask = tf.logical_or(x_ranges <0 , x_ranges > hh-1)\n    y_clip_mask = tf.logical_or(y_ranges <0 , y_ranges > hh-1)\n    clip_mask = tf.logical_or(x_clip_mask, y_clip_mask)\n\n    x_ranges = tf.boolean_mask(x_ranges, tf.logical_not(clip_mask))\n    y_ranges = tf.boolean_mask(y_ranges, tf.logical_not(clip_mask))\n\n    hh_ranges = tf.tile(tf.range(0,hh), [tf.cast(tf.reduce_sum(tf.ones_like(x_ranges)), tf.int32)])\n    x_ranges = tf.repeat(x_ranges, hh)\n    y_ranges = tf.repeat(y_ranges, hh)\n\n    y_hh_indices = tf.transpose(tf.stack([y_ranges, hh_ranges]))\n    x_hh_indices = tf.transpose(tf.stack([hh_ranges, x_ranges]))\n\n    y_mask_sparse = tf.SparseTensor(tf.cast(y_hh_indices, tf.int64),  tf.zeros_like(y_ranges), [hh, hh])\n    y_mask = tf.sparse.to_dense(y_mask_sparse, 1, False)\n\n    x_mask_sparse = tf.SparseTensor(tf.cast(x_hh_indices, tf.int64), tf.zeros_like(x_ranges), [hh, hh])\n    x_mask = tf.sparse.to_dense(x_mask_sparse, 1, False)\n\n    mask = tf.expand_dims( tf.clip_by_value(x_mask + y_mask, 0, 1), axis=-1)\n\n    mask = random_rotate(mask, rotate_angle, [hh, hh, 1])\n    mask = tf.image.crop_to_bounding_box(mask, (hh-h)//2, (hh-w)//2, image_height, image_width)\n\n    return mask\n\ndef apply_grid_mask(image, image_shape):\n    mask = GridMask(image_shape[0],\n                    image_shape[1],\n                    AugParams['d1'],\n                    AugParams['d2'],\n                    AugParams['rotate'],\n                    AugParams['ratio'])\n    \n    if image_shape[-1] == 3:\n        mask = tf.concat([mask, mask, mask], axis=-1)\n\n    return image * tf.cast(mask, tf.float32)\n\n\nAugParams = {\n    'd1' : 10,\n    'd2': 40 ,\n    'rotate' : 45,\n    'ratio' : 0.5\n}","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"new_image = apply_grid_mask(images[0], images[0].shape)\nnew_images = tf.convert_to_tensor([new_image])\ndisplay_batch_of_images(new_images)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# (Partial) Batch GridMask","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_batch_rotation_matrix(angles, batch_size=0):\n    \"\"\"Returns a tf.Tensor of shape (batch_size, 3, 3) with each element along the 1st axis being\n       an image rotation matrix (which transforms indicies).\n\n    Args:\n        angles: 1-D Tensor with shape [batch_size].\n        \n    Returns:\n        A 3-D Tensor with shape [batch_size, 3, 3].\n    \"\"\"    \n\n    if batch_size == 0:\n        batch_size = BATCH_SIZE\n    \n    # CONVERT DEGREES TO RADIANS\n    angles = tf.constant(math.pi) * angles / 180.0\n\n    # shape = (batch_size,)\n    one = tf.ones_like(angles, dtype=tf.float32)\n    zero = tf.zeros_like(angles, dtype=tf.float32)\n    \n    # ROTATION MATRIX\n    c1 = tf.math.cos(angles) # shape = (batch_size,)\n    s1 = tf.math.sin(angles) # 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    return rotation_matrix\n\n\ndef batch_random_rotate(images, max_angles, batch_size=0):\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    if batch_size == 0:\n        batch_size = BATCH_SIZE\n    \n    angles = max_angles * tf.random.normal([batch_size], dtype='float32')\n\n  \n    # GET TRANSFORMATION MATRIX\n    # shape = (batch_size, 3, 3)\n    m = get_batch_rotation_matrix(angles, batch_size) \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\n\n\ndef batch_get_grid_mask(d1, d2, ratio=0.5, max_angle=90, batch_size=0):\n        \n    # ratio: the ratio of black region\n\n    DIM = IMAGE_SIZE[0]\n    CLASSES = 104\n    \n    if batch_size == 0:\n        batch_size = BATCH_SIZE\n\n    # Length of diagonal\n    hh = tf.cast((tf.math.ceil(tf.math.sqrt(2.0) * DIM)), tf.int64)\n    hh = hh + tf.math.floormod(hh, 2)\n    \n    # We look squares of size dxd inside each image\n    d = tf.random.uniform(shape=[], minval=d1, maxval=d2, dtype=tf.int64)\n    \n    # Inside each square of size dxd, we mask a square of size LxL (L <= d)\n    l = tf.cast(tf.cast(d, tf.float32) * ratio + 0.5, tf.int64)\n\n    lower_limit = -1\n    upper_limit = tf.math.floordiv(hh, d) + 1\n    indices = tf.range(lower_limit, upper_limit)  # shape = [upper_limit + 1]\n    \n    # The 1st component has shape [upper_limit + 1, 1]\n    # The 2nd component has shae [1: L]\n    # The addition has shape [upper_limit + 1: L]\n    # The final output has sahpe [upper_limit + 1 * L]\n    ranges = tf.reshape((d * indices)[:, tf.newaxis] + tf.range(l, dtype=tf.int64)[tf.newaxis, :], shape=[-1])\n    shift = tf.random.uniform(shape=[], minval=0, maxval=d, dtype=tf.int64)\n    \n    ranges = shift + ranges\n\n    clip_mask = tf.logical_or(ranges < 0 , ranges > hh - 1)\n    ranges = tf.boolean_mask(ranges, tf.logical_not(clip_mask))\n\n    hh_ranges = tf.tile(tf.range(0,hh), [tf.cast(tf.reduce_sum(tf.ones_like(ranges)), tf.int64)])\n    \n    ranges = tf.repeat(ranges, hh)\n\n    y_hh_indices = tf.transpose(tf.stack([ranges, hh_ranges]))\n    x_hh_indices = tf.transpose(tf.stack([hh_ranges, ranges]))\n\n    y_mask_sparse = tf.SparseTensor(tf.cast(y_hh_indices, tf.int64),  tf.zeros_like(ranges), [hh, hh])\n    y_mask = tf.sparse.to_dense(y_mask_sparse, 1, False)\n\n    x_mask_sparse = tf.SparseTensor(tf.cast(x_hh_indices, tf.int64), tf.zeros_like(ranges), [hh, hh])\n    x_mask = tf.sparse.to_dense(x_mask_sparse, 1, False)\n    \n    mask = tf.expand_dims( tf.clip_by_value(x_mask + y_mask, 0, 1), axis=-1)\n    \n    mask = batch_random_rotate(tf.broadcast_to(mask[tf.newaxis, :, :, :], shape=[batch_size, mask.shape[0], mask.shape[1], 3]), max_angle, batch_size)\n    \n    mask = tf.image.crop_to_bounding_box(mask, (hh - DIM) // 2, (hh - DIM) // 2, tf.cast(DIM, dtype=tf.int64), tf.cast(DIM, dtype=tf.int64))\n\n    return mask\n\n\ndef batch_grid_mask(images, batch_size=0):\n    \n    if batch_size == 0:\n        batch_size = BATCH_SIZE\n    \n    # d1, d2 determined the width of the grid\n    d1 = 35\n    d2 = d1 + 1 + tf.cast(35 * tf.random.uniform(shape=[]), dtype=tf.int64)\n    ratio = 0.25 + 0.25 * tf.random.uniform(shape=[])\n    max_angle = 90\n        \n    mask = batch_get_grid_mask(d1, d2, ratio, max_angle, batch_size)\n    \n    return images * tf.cast(mask, tf.float32)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nnew_images = batch_grid_mask(images)\ndisplay_batch_of_images(new_images)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Compare timing for GridMask","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"n_iter = 100\n\nstart = datetime.datetime.now()\nfor i in range(n_iter):\n    batch_grid_mask(images) \nend = datetime.datetime.now()\ntiming = (end - start).total_seconds() / n_iter\nprint(f\"batch_grid_mask: {timing}\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"start = datetime.datetime.now()\nfor i in range(n_iter):\n    for image in images:\n        apply_grid_mask(image, image.shape) \nend = datetime.datetime.now()\ntiming = (end - start).total_seconds() / n_iter\nprint(f\"grid_mask: {timing}\")","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}