{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Introduction\n\n#### This is my final model I built in my last week of competition. It's little different than my first public model I shared [here](https://www.kaggle.com/datafan07/analysis-of-melanoma-metadata-and-effnet-ensemble). Basically this model includes meta as well as image, attention layers and progressive sprinkles augmentation. It gave me pretty stable cv and lb so I used them on my final ensembles. I explained how did I come up with this idea [here](https://www.kaggle.com/c/siim-isic-melanoma-classification/discussion/175361).\n\n#### Thanks to all who shared their work and ideas to the community. I tried to reference every single work helped me on this work so you can find the links in comments at relevant code cells...\n\n#### I'm going to keep this notebook simple without many markdowns unlike my old public notebooks, since I shared my analysis about the competition before I thought sharing code only model at final notebook would be better.\n\n### This is light version the model I used in my ensembles, this one uses 256x images and lower EfficientNet B's...\n#### In actual competition I ensembled different image sizes with different EfficientNet's..."},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true,"_kg_hide-input":false,"_kg_hide-output":true},"cell_type":"code","source":"!pip install tensorflow~=2.2.0 tensorflow_gcs_config~=2.2.0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-output":true},"cell_type":"code","source":"!pip install -q efficientnet\n!pip install pandas_summary\n!pip install tensorflow-addons","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# loading packages\n\nimport os\nimport re\nimport numpy as np\nimport pandas as pd\nimport random\nimport math\nimport matplotlib.pyplot as plt\nfrom sklearn import metrics\nfrom sklearn.model_selection import KFold, StratifiedKFold\nimport tensorflow as tf\nfrom kaggle_datasets import KaggleDatasets\nimport efficientnet.tfkeras as efn\nfrom tensorflow.keras import backend as K\nimport tensorflow_addons as tfa","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def seed_all(seed):\n    \n    ''' A function to seed everything for getting reproducible results. '''\n    \n    random.seed(seed)\n    np.random.seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    os.environ['TF_DETERMINISTIC_OPS'] = str(seed)\n    os.environ['TF_KERAS'] = str(seed)\n    tf.random.set_seed(seed)\n    \nseed_all(42)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"DEVICE = 'TPU'\nMIXED_PRECISION = True\nXLA_ACCELERATE = True\n\n# We set our TPU settings here mixed_precision let's us bigger batches\n\nif DEVICE == 'TPU':\n    print('Connecting to TPU...')\n    try:\n        tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n        print('Running on TPU ', tpu.master())\n    except ValueError:\n        print('Could not connect to TPU')\n        tpu = None\n\n    if tpu:\n        try:\n            print('initializing  TPU ...')\n            tf.config.experimental_connect_to_cluster(tpu)\n            tf.tpu.experimental.initialize_tpu_system(tpu)\n            strategy = tf.distribute.experimental.TPUStrategy(tpu)            \n            print('TPU initialized')\n            if MIXED_PRECISION:\n                from tensorflow.keras.mixed_precision import experimental as mixed_precision\n                policy = tf.keras.mixed_precision.experimental.Policy('mixed_bfloat16')\n                mixed_precision.set_policy(policy)\n                print('Mixed precision enabled')\n            if XLA_ACCELERATE:\n                    tf.config.optimizer.set_jit(True)\n                    print('Accelerated Linear Algebra enabled')\n                 \n        except _:\n            print('failed to initialize TPU')\n    else:\n        DEVICE = 'GPU'\n\nif DEVICE != 'TPU':\n    print('Using default strategy for CPU and single GPU')\n    strategy = tf.distribute.get_strategy()\n\nif DEVICE == 'GPU':\n    print('Num GPUs Available: ', len(tf.config.experimental.list_physical_devices('GPU')))\n    if MIXED_PRECISION:\n        from tensorflow.keras.mixed_precision import experimental as mixed_precision\n        policy = tf.keras.mixed_precision.experimental.Policy('mixed_float16')\n        mixed_precision.set_policy(policy)\n        print('Mixed precision enabled')\n    if XLA_ACCELERATE:\n        tf.config.optimizer.set_jit(True)\n        print('Accelerated Linear Algebra enabled')\n    \n\nAUTO     = tf.data.experimental.AUTOTUNE\nREPLICAS = strategy.num_replicas_in_sync\nprint(f'REPLICAS: {REPLICAS}')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Config"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Some modelling and augmentation parameters\n\nCFG = dict(\n    epochs = 30,\n    batch_size = 128,\n    lr = 0.00032,  # learning rate  \n    inp_size = 256, # input image size\n\n    \n    eff_B = 0, #effnet to choose eg. B1-B2-...-B7\n    \n    \n    sprinkles_mode    = 'normal',\n    sprinkles_prob    =   1, # probability to spawn a box (between 0-1)\n    num_holes         =   5, # number of boxes to drop\n    side_length       =   256//10   #dropout box size\n)\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Loading Data"},{"metadata":{"trusted":true},"cell_type":"code","source":"BASEPATH = '../input/siim-isic-melanoma-classification'\ndf_train = pd.read_csv(os.path.join(BASEPATH, 'train.csv'))\ndf_test  = pd.read_csv(os.path.join(BASEPATH, 'test.csv'))\ndf_sub   = pd.read_csv(os.path.join(BASEPATH, 'sample_submission.csv'))\n\n# Data from Chris' tfrecords\n\nGCS_PATH = KaggleDatasets().get_gcs_path('melanoma-%ix%i'%(CFG['inp_size'],CFG['inp_size'])) # main train data\nGCS_PATHE = KaggleDatasets().get_gcs_path('isic2019-%ix%i'%(CFG['inp_size'],CFG['inp_size'])) # external data\n\n\n# Training files directory\ntraining_files = tf.io.gfile.glob(GCS_PATH + '/train*.tfrec')\ntraining_files_2018 = tf.io.gfile.glob(GCS_PATHE + '/train%.2i*.tfrec'%(2*x) for x in range(15))\n\ntraining_files += training_files_2018\n\n\n\n# test files directory\ntest_files = tf.io.gfile.glob(GCS_PATH + '/test*.tfrec') # test data","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Augmentations"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Progressive sprinkles implementation from here:\n# https://www.kaggle.com/benboren/tfrecord-progressive-sprinkles\n\ndef make_mask(num_holes,side_length,rows, cols, num_channels):\n        '''Builds the mask for all sprinkles.'''\n        row_range = tf.tile(tf.range(rows)[..., tf.newaxis], [1, num_holes])\n        col_range = tf.tile(tf.range(cols)[..., tf.newaxis], [1, num_holes])\n        r_idx = tf.random.uniform([num_holes], minval=0, maxval=rows-1,\n                                  dtype=tf.int32)\n        c_idx = tf.random.uniform([num_holes], minval=0, maxval=cols-1,\n                                  dtype=tf.int32)\n        r1 = tf.clip_by_value(r_idx - side_length // 2, 0, rows)\n        r2 = tf.clip_by_value(r_idx + side_length // 2, 0, rows)\n        c1 = tf.clip_by_value(c_idx - side_length // 2, 0, cols)\n        c2 = tf.clip_by_value(c_idx + side_length // 2, 0, cols)\n        row_mask = (row_range > r1) & (row_range < r2)\n        col_mask = (col_range > c1) & (col_range < c2)\n\n        # Combine masks into one layer and duplicate over channels.\n        mask = row_mask[:, tf.newaxis] & col_mask\n        mask = tf.reduce_any(mask, axis=-1)\n        mask = mask[..., tf.newaxis]\n        mask = tf.tile(mask, [1, 1, num_channels])\n        return mask\n    \ndef sprinkles(image, cfg = CFG): \n    \n    '''Applies all sprinkles.'''\n    \n    num_holes = cfg['num_holes']\n    side_length = cfg['side_length']\n    mode = cfg['sprinkles_mode']\n    PROBABILITY = cfg['sprinkles_prob']\n    \n    RandProb = tf.cast( tf.random.uniform([],0,1) < PROBABILITY, tf.int32)\n    if (RandProb == 0)|(num_holes == 0): return image\n    \n    img_shape = tf.shape(image)\n    if mode is 'normal':\n        rejected = tf.zeros_like(image)\n    elif mode is 'salt_pepper':\n        num_holes = num_holes // 2\n        rejected_high = tf.ones_like(image)\n        rejected_low = tf.zeros_like(image)\n    elif mode is 'gaussian':\n        rejected = tf.random.normal(img_shape, dtype=tf.float32)\n    else:\n        raise ValueError(f'Unknown mode \"{mode}\" given.')\n        \n    rows = img_shape[0]\n    cols = img_shape[1]\n    num_channels = img_shape[-1]\n    if mode is 'salt_pepper':\n        mask1 = make_mask(num_holes,side_length,rows, cols, num_channels)\n        mask2 = make_mask(num_holes,side_length,rows, cols, num_channels)\n        filtered_image = tf.where(mask1, rejected_high, image)\n        filtered_image = tf.where(mask2, rejected_low, filtered_image)\n    else:\n        mask = make_mask(num_holes,side_length,rows, cols, num_channels)\n        filtered_image = tf.where(mask, rejected, image)\n    return filtered_image","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_mat(rotation, shear, height_zoom, width_zoom, height_shift, width_shift):\n    \n    # Most of the augmentations and transforms from here:\n    # https://www.kaggle.com/cdeotte/rotation-augmentation-gpu-tpu-0-96\n        \n    # CONVERT DEGREES TO RADIANS\n    rotation = math.pi * rotation / 180.\n    shear    = math.pi * shear    / 180.\n\n    def get_3x3_mat(lst):\n        return tf.reshape(tf.concat([lst],axis=0), [3,3])\n    \n    # ROTATION MATRIX\n    c1   = tf.math.cos(rotation)\n    s1   = tf.math.sin(rotation)\n    one  = tf.constant([1],dtype='float32')\n    zero = tf.constant([0],dtype='float32')\n    \n    rotation_matrix = get_3x3_mat([c1,   s1,   zero, \n                                   -s1,  c1,   zero, \n                                   zero, zero, one])    \n    # SHEAR MATRIX\n    c2 = tf.math.cos(shear)\n    s2 = tf.math.sin(shear)    \n    \n    shear_matrix = get_3x3_mat([one,  s2,   zero, \n                                zero, c2,   zero, \n                                zero, zero, one])        \n    # ZOOM MATRIX\n    zoom_matrix = get_3x3_mat([one/height_zoom, zero,           zero, \n                               zero,            one/width_zoom, zero, \n                               zero,            zero,           one])    \n    # SHIFT MATRIX\n    shift_matrix = get_3x3_mat([one,  zero, height_shift, \n                                zero, one,  width_shift, \n                                zero, zero, one])\n    \n    return K.dot(K.dot(rotation_matrix, shear_matrix), \n                 K.dot(zoom_matrix,     shift_matrix))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def transform(image, label):\n    # input image - is one image of size [dim,dim,3] not a batch of [b,dim,dim,3]\n    # output - image randomly rotated, sheared, zoomed, and shifted\n    DIM = CFG['inp_size']\n    XDIM = DIM%2 #fix for size 331\n    \n    if 0.5 > tf.random.uniform([1], minval = 0, maxval = 1):\n        rot = 15. * tf.random.normal([1],dtype='float32')\n    else:\n        rot = 180. * tf.random.normal([1],dtype='float32')\n    shr = 5. * tf.random.normal([1],dtype='float32') \n    h_zoom = 1.0 + tf.random.normal([1],dtype='float32')/10.\n    w_zoom = 1.0 + tf.random.normal([1],dtype='float32')/10.\n    h_shift = 16. * tf.random.normal([1],dtype='float32') \n    w_shift = 16. * tf.random.normal([1],dtype='float32') \n  \n    # GET TRANSFORMATION MATRIX\n    m = get_mat(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 )\n    y = tf.tile( tf.range(-DIM//2,DIM//2),[DIM] )\n    z = tf.ones([DIM*DIM],dtype='int32')\n    idx = tf.stack( [x,y,z] )\n    \n    # ROTATE DESTINATION PIXELS ONTO ORIGIN PIXELS\n    idx2 = K.dot(m,tf.cast(idx,dtype='float32'))\n    idx2 = K.cast(idx2,dtype='int32')\n    idx2 = K.clip(idx2,-DIM//2+XDIM+1,DIM//2)\n    \n    # FIND ORIGIN PIXEL VALUES           \n    idx3 = tf.stack( [DIM//2-idx2[0,], DIM//2-1+idx2[1,]] )\n    d = tf.gather_nd(image['img_inp'],tf.transpose(idx3))\n        \n    return {'img_inp': tf.reshape(d,[DIM,DIM,3]), 'meta_inp': image['meta_inp']}, label","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def decode_image(image_data):\n    \n    '''A function for loading image, decode and reshape'''\n    \n    image = tf.image.decode_jpeg(image_data, channels=3)\n    # normalizing image\n    image = tf.cast(image, tf.float32) / 255.0 \n    # explicit input size for TPU\n    image = tf.reshape(image, [CFG['inp_size'], CFG['inp_size'], 3])\n    return image","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def data_augment(data, label):\n    # data augmentation. Thanks to the dataset.prefetch(AUTO) statement \n    # in the next function (below), this happens essentially for free on TPU. \n    # Data pipeline code is executed on the 'CPU' part\n    # of the TPU while the TPU itself is computing gradients.\n    # https://www.kaggle.com/cdeotte/rotation-augmentation-gpu-tpu-0-96\n    \n    data['img_inp'] = tf.image.random_flip_left_right(data['img_inp'])\n    data['img_inp'] = tf.image.random_flip_up_down(data['img_inp'])\n    data['img_inp'] = tf.image.random_hue(data['img_inp'], 0.01)\n    data['img_inp'] = tf.image.random_saturation(data['img_inp'], 0.7, 1.3)\n    data['img_inp'] = tf.image.random_contrast(data['img_inp'], 0.8, 1.2)\n    data['img_inp'] = tf.image.random_brightness(data['img_inp'], 0.1)\n    data['img_inp'] = sprinkles(data['img_inp']) \n\n    \n    \n    return data, label","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Read Data"},{"metadata":{"trusted":true},"cell_type":"code","source":"def read_labeled_tfrecord(example):\n    \n    '''A function to parse images and returns targets together'''\n    \n    LABELED_TFREC_FORMAT = {\n        # tf.string means bytestring\n        'image': tf.io.FixedLenFeature([], tf.string), \n        # shape [] means single element\n        'target': tf.io.FixedLenFeature([], tf.int64),\n        # meta features\n        'age_approx': tf.io.FixedLenFeature([], tf.int64),\n        'sex': tf.io.FixedLenFeature([], tf.int64),\n        'anatom_site_general_challenge': tf.io.FixedLenFeature([], tf.int64)\n        \n    }\n    example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    label = tf.cast(example['target'], tf.int32)\n    # dictionary for meta images\n    data = {}\n    data['age_approx'] = tf.cast(example['age_approx'], tf.int32)\n    data['sex'] = tf.cast(example['sex'], tf.int32)\n    data['anatom_site_general_challenge'] = tf.cast(tf.one_hot(example['anatom_site_general_challenge'], 7), tf.int32)\n    # returns a dataset of (image, label, data)\n    return image, label, data","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def read_unlabeled_tfrecord(example):\n    \n    '''A function to parse images and returns image ids together'''\n    \n    UNLABELED_TFREC_FORMAT = {\n        # tf.string means bytestring\n        'image': tf.io.FixedLenFeature([], tf.string), \n        # shape [] means single element\n        'image_name': tf.io.FixedLenFeature([], tf.string),\n        # meta features\n        'age_approx': tf.io.FixedLenFeature([], tf.int64),\n        'sex': tf.io.FixedLenFeature([], tf.int64),\n        'anatom_site_general_challenge': tf.io.FixedLenFeature([], tf.int64)\n    }\n    example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    image_name = example['image_name']\n    # dictionary for meta images\n    data = {}\n    data['age_approx'] = tf.cast(example['age_approx'], tf.int32)\n    data['sex'] = tf.cast(example['sex'], tf.int32)\n    data['anatom_site_general_challenge'] = tf.cast(tf.one_hot(example['anatom_site_general_challenge'], 7), tf.int32)\n    # returns a dataset of (image, key, data)\n    return image, image_name, data","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def read_complete_tfrecord(example):\n    \n    '''A function to parse images and returns image ids as well as targets together'''\n    \n    LABELED_TFREC_FORMAT = {\n        'image': tf.io.FixedLenFeature([], tf.string), \n        'image_name': tf.io.FixedLenFeature([], tf.string), \n        'target': tf.io.FixedLenFeature([], tf.int64), \n        # meta features\n        'age_approx': tf.io.FixedLenFeature([], tf.int64),\n        'sex': tf.io.FixedLenFeature([], tf.int64),\n        'anatom_site_general_challenge': tf.io.FixedLenFeature([], tf.int64)\n    }\n    example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    image_name = example['image_name']\n    target = tf.cast(example['target'], tf.int32)\n    # dictionary for meta images\n    data = {}\n    data['age_approx'] = tf.cast(example['age_approx'], tf.int32)\n    data['sex'] = tf.cast(example['sex'], tf.int32)\n    data['anatom_site_general_challenge'] = tf.cast(tf.one_hot(example['anatom_site_general_challenge'], 7), tf.int32)\n    return image, image_name, target, data","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def 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        # disable order, increase speed\n        ignore_order.experimental_deterministic = False \n        \n    # automatically interleaves reads from multiple files\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads = AUTO)\n    # use data as soon as it streams in, rather than in its original order\n    dataset = dataset.with_options(ignore_order)\n    # returns a dataset of (image, label) pairs if labeled = True or (image, id) pair if labeld = False\n    dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls = AUTO) \n    return dataset\n\ndef load_complete_dataset(filenames):        \n    # automatically interleaves reads from multiple files\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads = AUTO)\n    # returns a dataset of (image_name, target)\n    dataset = dataset.map(read_complete_tfrecord, num_parallel_calls = AUTO) \n    return dataset","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def training_input(image, label, data):\n    \n    ''' A function for extracing metadata as well as images for train'''\n    \n    anatom = [tf.cast(data['anatom_site_general_challenge'][i], dtype = tf.float32) for i in range(7)]\n    \n    tab_data = [tf.cast(data[tfeat], dtype = tf.float32) for tfeat in ['age_approx', 'sex']]\n    \n    tabular = tf.stack(tab_data + anatom)\n    \n    return {'img_inp': image, 'meta_inp':  tabular}, label","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def test_input(image, image_name, data):\n    \n    ''' A function for extracing metadata as well as images for test'''\n    \n\n    anatom = [tf.cast(data['anatom_site_general_challenge'][i], dtype = tf.float32) for i in range(7)]\n    \n    tab_data = [tf.cast(data[tfeat], dtype = tf.float32) for tfeat in ['age_approx', 'sex']]\n    \n    tabular = tf.stack(tab_data + anatom)\n    \n    return {'img_inp': image, 'meta_inp':  tabular}, image_name\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def validation_input(image, image_name, target, data):\n    \n    ''' A function for extracing metadata as well as images for validation'''    \n\n    anatom = [tf.cast(data['anatom_site_general_challenge'][i], dtype = tf.float32) for i in range(7)]\n    \n    tab_data = [tf.cast(data[tfeat], dtype = tf.float32) for tfeat in ['age_approx', 'sex']]\n    \n    tabular = tf.stack(tab_data + anatom)\n    \n    return {'img_inp': image, 'meta_inp':  tabular}, image_name, target","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_training_dataset(filenames, labeled = True, ordered = False):\n    \n    '''Gets the data for training phrase, applies augment, transformation and shuffle'''\n    \n    dataset = load_dataset(filenames, labeled = labeled, ordered = ordered)\n    dataset = dataset.map(training_input, num_parallel_calls = AUTO)\n    dataset = dataset.map(data_augment, num_parallel_calls = AUTO)\n    dataset = dataset.map(transform, num_parallel_calls = AUTO)\n    # the training dataset must repeat for several epochs\n    dataset = dataset.repeat() \n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(CFG['batch_size'])\n    # prefetch next batch while training (autotune prefetch buffer size)\n    dataset = dataset.prefetch(AUTO)\n    return dataset\n\n\ndef get_validation_dataset(filenames, labeled = True, ordered = True):\n    \n    '''Gets the data for validation phrase'''\n    \n    dataset = load_dataset(filenames, labeled = labeled, ordered = ordered)\n    dataset = dataset.map(training_input, num_parallel_calls = AUTO)\n    dataset = dataset.batch(CFG['batch_size'])\n    # prefetch next batch while training (autotune prefetch buffer size)\n    dataset = dataset.prefetch(AUTO) \n    return dataset\n\ndef get_test_dataset(filenames, labeled = False, ordered = True):\n    \n    '''Gets the data for testing phrase, no augmentations since no TTA'''\n    \n    dataset = load_dataset(filenames, labeled = labeled, ordered = ordered)\n    dataset = dataset.map(test_input, num_parallel_calls = AUTO)\n    dataset = dataset.batch(CFG['batch_size'])\n    # prefetch next batch while training (autotune prefetch buffer size)\n    dataset = dataset.prefetch(AUTO) \n    return dataset\n\ndef get_complete_dataset(filenames):\n    dataset = load_complete_dataset(filenames)\n    dataset = dataset.map(validation_input, num_parallel_calls = AUTO)\n    dataset = dataset.batch(CFG['batch_size'])\n    # prefetch next batch while training (autotune prefetch buffer size)\n    dataset = dataset.prefetch(AUTO)\n    return dataset","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def count_data_items(filenames):\n    \n    ''' The number of data items is written in the name of the .tfrec files '''\n    \n    n = [int(re.compile(r'-([0-9]*)\\.').search(filename).group(1)) for filename in filenames]\n    return np.sum(n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"NUM_TRAINING_IMAGES = int(count_data_items(training_files) * 0.8)\n# use validation data for training\nNUM_VALIDATION_IMAGES = int(count_data_items(training_files) * 0.2)\nNUM_TEST_IMAGES = count_data_items(test_files)\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // CFG['batch_size']\n\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":"# Custom Sprinkles"},{"metadata":{"trusted":true},"cell_type":"code","source":"class IncreaseSprinklesHoles(tf.keras.callbacks.Callback):\n    def on_epoch_end(self, epoch, logs={}):\n        \n        ''' Custom callback for progressive sprinkles increases with epoch'''\n      \n        if epoch <= 10:\n            CFG['num_holes'] = epoch  + 5\n            CFG['side_length'] = (CFG['inp_size'] // 10) + (epoch // 2)\n        if epoch >= 10:\n            CFG['num_holes'] = epoch  + 5\n            CFG['side_length'] = (CFG['inp_size'] // 5) + (epoch // 2)\n        if epoch >= 15:\n            CFG['num_holes'] = epoch  + 5\n            CFG['side_length'] = (CFG['inp_size'] // 2) + (epoch // 2)\n        \nsprinkles_cb = IncreaseSprinklesHoles()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Modelling and OOF Predictions"},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_model():\n    \n    ''' Main modelling part with effnet, metadata, effnets, callbacks, optimizers etc.'''\n    \n    with strategy.scope():\n        \n        # meta implementation from here:\n        # https://www.kaggle.com/rajnishe/rc-fork-siim-isic-melanoma-384x384/notebook\n        \n        img_inp = tf.keras.layers.Input(shape = (CFG['inp_size'], CFG['inp_size'], 3), name = 'img_inp')\n        meta_inp = tf.keras.layers.Input(shape = (9), name = 'meta_inp')\n        \n        effs = [0,1,2,3,4,5,6,7]\n        eff = effs[CFG['eff_B']]\n        \n        constructor = getattr(efn, f'EfficientNetB{eff}')\n        efnetb = constructor(weights = 'noisy-student', include_top = False)     \n        \n        # attention implementation from here:\n        # https://www.kaggle.com/kmader/attention-on-pretrained-vgg16-for-bone-age/notebook\n        \n        pt_depth = efnetb.get_output_shape_at(0)[-1]\n        pt_features = efnetb(img_inp)\n        bn_features = tf.keras.layers.BatchNormalization()(pt_features)\n        \n        # here we do an attention mechanism to turn pixels in the GAP on an off\n        attn_layer = tf.keras.layers.Conv2D(64, kernel_size = (1, 1), padding = 'same', activation = 'swish')(tf.keras.layers.Dropout(0.5)(bn_features))\n        attn_layer = tf.keras.layers.Conv2D(16, kernel_size = (1, 1), padding = 'same', activation = 'swish')(attn_layer)\n        attn_layer = tf.keras.layers.Conv2D(8, kernel_size = (1,1), padding = 'same', activation = 'swish')(attn_layer)\n        attn_layer = tf.keras.layers.Conv2D(1, kernel_size = (1, 1), padding = 'valid', activation = 'sigmoid')(attn_layer)\n        \n        # fan it out to all of the channels\n        up_c2_w = np.ones((1, 1, 1, pt_depth))\n        up_c2 = tf.keras.layers.Conv2D(pt_depth, kernel_size = (1, 1), padding = 'same',  activation = 'linear',  use_bias = False,    weights = [up_c2_w]  )\n        up_c2.trainable = False\n        attn_layer = up_c2(attn_layer)\n        mask_features = tf.keras.layers.multiply([attn_layer, bn_features])\n        gap_features = tf.keras.layers.GlobalAveragePooling2D()(mask_features)\n        gap_mask = tf.keras.layers.GlobalAveragePooling2D()(attn_layer)\n        \n         # To account for missing values from the attention model\n        gap = tf.keras.layers.Lambda(lambda x: x[0] / x[1], name = 'RescaleGAP')([gap_features, gap_mask])\n        gap_dr = tf.keras.layers.Dropout(0.5)(gap)\n        dr_steps = tf.keras.layers.Dropout(0.25)(tf.keras.layers.Dense(128, activation = 'swish')(gap_dr))\n        \n        \n        \n        meta_layer = tf.keras.layers.Dense(16)(meta_inp)\n        meta_layer = tf.keras.layers.BatchNormalization()(meta_layer)\n        meta_layer = tf.keras.layers.Activation('swish')(meta_layer)\n        meta_layer = tf.keras.layers.Dropout(0.2)(meta_layer)\n        meta_layer = tf.keras.layers.Dense(8)(meta_inp)\n        meta_layer = tf.keras.layers.BatchNormalization()(meta_layer)\n        meta_layer = tf.keras.layers.Activation('swish')(meta_layer)\n        meta_layer = tf.keras.layers.Dropout(0.2)(meta_layer)\n        \n        concat = tf.keras.layers.concatenate([dr_steps, meta_layer])\n        concat = tf.keras.layers.BatchNormalization()(concat)\n        concat = tf.keras.layers.Dense(512, activation = 'swish')(concat)        \n        concat = tf.keras.layers.Dropout(0.15)(concat)\n        output = tf.keras.layers.Dense(1, activation = 'sigmoid',dtype='float32')(concat)\n\n        model = tf.keras.models.Model(inputs = [img_inp, meta_inp], outputs = [output])\n\n        opt = tf.keras.optimizers.Adam(learning_rate = CFG['lr'])\n\n        model.compile(\n            optimizer = opt,\n            loss = [tfa.losses.SigmoidFocalCrossEntropy(reduction=tf.keras.losses.Reduction.AUTO,gamma = 2.0, alpha = 0.90)],\n            metrics = [tf.keras.metrics.AUC()]\n        )\n\n        return model\n    \ndef train_validate_predict(df_sub, folds = 3):\n    \n    '''Training, validation, oof cv and predictions'''\n    \n    models = []\n    oof_image_name = []\n    oof_target = []\n    oof_prediction = []\n    \n   \n\n    kfold = KFold(folds, shuffle = True, random_state = 42)\n    for fold, (trn_ind, val_ind) in enumerate(kfold.split(training_files)):\n        print('\\n')\n        print('-'*50)\n        print(f'Training fold {fold + 1}')\n        CFG['num_holes'] = 5 \n        CFG['side_length'] = CFG['inp_size']//10\n        train_dataset = get_training_dataset([training_files[x] for x in trn_ind], labeled = True, ordered = False)\n        val_dataset = get_validation_dataset([training_files[x] for x in val_ind], labeled = True, ordered = True)\n        K.clear_session()\n        model = get_model()\n        # early stopping with 5 patience\n        early_stopping = tf.keras.callbacks.EarlyStopping(monitor = 'val_auc', mode = 'max', patience = 5, \n                                                      verbose = 2, min_delta = 0.00025, restore_best_weights = True)\n        # lr scheduler with 2 patience\n        cb_lr_schedule = tf.keras.callbacks.ReduceLROnPlateau(monitor = 'val_auc', factor = 0.6, patience = 2 , verbose = 2, min_delta = 0.0005, min_lr=0.000001, mode = 'max')\n        history = model.fit(train_dataset, \n                            steps_per_epoch = STEPS_PER_EPOCH,\n                            epochs = CFG['epochs'],\n                            callbacks = [sprinkles_cb, cb_lr_schedule, early_stopping],\n                            validation_data = val_dataset,\n                            verbose = 1)\n        models.append(model)\n        \n        # predict the validation set and save them for stacking\n        number_of_files = count_data_items([training_files[x] for x in val_ind])\n        dataset = get_complete_dataset([training_files[x] for x in val_ind])\n        # extracting image names\n        image_name = dataset.map(lambda image, image_name, target: image_name).unbatch()\n        image_name = next(iter(image_name.batch(number_of_files))).numpy().astype('U')\n        # extracting target variables\n        target = dataset.map(lambda image, image_name, target: target).unbatch()\n        target = next(iter(target.batch(number_of_files))).numpy()\n        # predicting validation set\n        image = dataset.map(lambda image, image_name, target: image)\n        probabilities = model.predict(image)\n        oof_image_name.extend(list(image_name))\n        oof_target.extend(list(target))\n        oof_prediction.extend(list(np.concatenate(probabilities)))\n\n\n    \n    print('\\n')\n    print('-'*50)\n    # saving OOF predictions\n    oof_df = pd.DataFrame({'image_name': oof_image_name, 'target': oof_target, 'predictions': oof_prediction})\n    oof_df.to_csv('OOF_EfficientNetB%i_%i.csv'%(CFG['eff_B'],CFG['inp_size']), index = False)\n        \n    # since we are splitting the dataset and iterating separately on images and ids, order matters.\n    test_ds = get_test_dataset(test_files, labeled = False, ordered = True)\n    test_images_ds = test_ds.map(lambda image, image_name: image)\n    \n    print('Computing predictions...')\n    probabilities = np.average([np.concatenate(models[i].predict(test_images_ds)) for i in range(folds)], axis = 0)\n    print('Generating submission.csv file...')\n    test_ids_ds = test_ds.map(lambda image, image_name: image_name).unbatch()\n\n    test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U') \n    pred_df = pd.DataFrame({'image_name': test_ids, 'target': probabilities})\n    df_sub.drop('target', inplace = True, axis = 1)\n    df_sub = df_sub.merge(pred_df, on = 'image_name')\n    df_sub.to_csv('sub_EfficientNetB%i_%i.csv'%(CFG['eff_B'],CFG['inp_size']), index = False)\n    \n    return oof_target, oof_prediction\n    \noof_target, oof_prediction = train_validate_predict(df_sub)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# OOF Score"},{"metadata":{"trusted":true},"cell_type":"code","source":"# calculating oof roc auc score\nroc_auc = metrics.roc_auc_score(oof_target, oof_prediction)\nprint('Final OOF Roc Auc Score: ', roc_auc)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!ls -l .","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Final Words\n\n### It was a great experience for me to be in part of this competition. I learnt a lot from this community, especially people like Chris with their tireless sharings made this work much more easier for me.\n\n### Thanks to all who contributed and thank you for reading, happy coding!"}],"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}