{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install -q efficientnet","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\n\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 stable 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":"train_fold = [[1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 13, 14, 15, 16, 17,\n  18,\n  19,\n  20,\n  21,\n  22,\n  23,\n  24,\n  25,\n  26,\n  27,\n  28,\n  29,\n  30,\n  31,\n  32,\n  33,\n  34,\n  35,\n  36,\n  37,\n  38,\n  39,\n  40,\n  41,\n  42,\n  43,\n  44],\n [0,\n  1,\n  2,\n  3,\n  4,\n  6,\n  7,\n  9,\n  10,\n  11,\n  12,\n  14,\n  15,\n  16,\n  17,\n  18,\n  19,\n  20,\n  21,\n  22,\n  23,\n  24,\n  25,\n  26,\n  27,\n  28,\n  29,\n  30,\n  31,\n  32,\n  33,\n  34,\n  35,\n  36,\n  37,\n  38,\n  39,\n  40,\n  41,\n  42,\n  43,\n  44],\n [0,\n  3,\n  4,\n  5,\n  6,\n  7,\n  8,\n  9,\n  10,\n  11,\n  12,\n  13,\n  15,\n  16,\n  17,\n  18,\n  19,\n  20,\n  21,\n  22,\n  23,\n  24,\n  25,\n  26,\n  27,\n  28,\n  29,\n  30,\n  31,\n  32,\n  33,\n  34,\n  35,\n  36,\n  37,\n  38,\n  39,\n  40,\n  41,\n  42,\n  43,\n  44],\n [0,\n  1,\n  2,\n  3,\n  5,\n  6,\n  8,\n  9,\n  11,\n  12,\n  13,\n  14,\n  15,\n  16,\n  17,\n  18,\n  19,\n  20,\n  21,\n  22,\n  23,\n  24,\n  25,\n  26,\n  27,\n  28,\n  29,\n  30,\n  31,\n  32,\n  33,\n  34,\n  35,\n  36,\n  37,\n  38,\n  39,\n  40,\n  41,\n  42,\n  43,\n  44],\n [0,\n  1,\n  2,\n  4,\n  5,\n  7,\n  8,\n  9,\n  10,\n  11,\n  13,\n  14,\n  15,\n  16,\n  17,\n  18,\n  19,\n  20,\n  21,\n  22,\n  23,\n  24,\n  25,\n  26,\n  27,\n  28,\n  29,\n  30,\n  31,\n  32,\n  33,\n  34,\n  35,\n  36,\n  37,\n  38,\n  39,\n  40,\n  41,\n  42,\n  43,\n  44]]\nval_fold =  [[0, 9, 11], [5,  8, 13], [1,  2, 14], [4,  7, 10], [3, 6,12]]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Some modelling and augmentation parameters\n\nCFG = dict(\n    epochs = 20,\n    batch_size = 256,\n#     lr = 0.00016,  # learning rate \n    lr_start=0.000005,\n    lr_max=0.00000125,\n    lr_min=0.000001,\n    lr_rampup=5,\n    lr_sustain=0,\n    lr_decay=0.8,\n    \n    eff_B = 7, #effnet to choose eg. B1-B2-...-B7\n    \n    sprinkles_mode    = 'normal',\n    sprinkles_prob    =   1, # probability to spawn a box (between 0-1)\n)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"inp_size = [224, 240, 260, 300, 380, 456, 528, 600]\ninput_size = [256, 256, 256, 384, 384, 512, 512, 768]\nlr = [0.00016, 0.00016, 0.00016, 0.00016, 0.0001, 0.0001, 0.0001, 0.0001]\nCFG['inp_size'] = inp_size[CFG['eff_B']]\nCFG['input_size'] = input_size[CFG['eff_B']]\nCFG['lr'] = lr[CFG['eff_B']]\nprint('Input size: '+str(CFG['input_size'])+', '+str(CFG['inp_size'])+', '+str(CFG['lr']))","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\nGCS_PATH = KaggleDatasets().get_gcs_path('melanoma-%ix%i'%(CFG['input_size'],CFG['input_size'])) # main train data\nGCS_PATH2 = KaggleDatasets().get_gcs_path('isic2019-%ix%i'%(CFG['input_size'],CFG['input_size'])) # external data\n\n\n# Training files directory\ntraining_files_1 = tf.io.gfile.glob(GCS_PATH + '/train%.2d*.tfrec'%i for i in range(0, 15))\ntraining_files_2019 = tf.io.gfile.glob(GCS_PATH2 + '/train%.2d*.tfrec'%i for i in range(0, 30))\ntraining_files = training_files_1 + training_files_2019\n\n\n# test files \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\n\ndef 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))\n\ndef 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\n\ndef 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    \n#     image = tf.cast(image, tf.float32) / 255.0 \n#     image = tf.decode_raw(image, tf.uint8) / 255.0 \n\n    \n    # explicit input size for TPU\n    image = tf.image.resize(image, [CFG['inp_size'], CFG['inp_size']])\n    image = tf.reshape(image, [CFG['inp_size'], CFG['inp_size'], 3])\n#     image = tf.image.rgb_to_hsv(image)\n    image = tf.cast(image, tf.float32) / 255.0\n#     image = tf.image.resize(image, [CFG['inp_size'], CFG['inp_size']])\n    return image\n\ndef 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#     data['img_inp'] = tf.image.resize(data['img_inp'], [CFG['inp_size'], CFG['inp_size']])\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#     image = tf.image.resize(decode_image(example['image']), [224, 224])\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\n\ndef 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 = tf.image.resize(decode_image(example['image']), [224, 224])\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\n\ndef 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 = tf.image.resize(decode_image(example['image']), [224, 224])\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\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        # 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\n\ndef 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\n\ndef 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\ndef 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\n\ndef 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\n\ndef 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_1) * 0.8 + count_data_items(training_files_2019))\n# use validation data for training\nNUM_VALIDATION_IMAGES = int(count_data_items(training_files_1) * 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.GaussianDropout(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.GaussianDropout(0.5)(gap)\n        dr_steps = tf.keras.layers.GaussianDropout(0.25)(tf.keras.layers.Dense(128, activation = 'swish')(gap_dr))\n        \n        \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.GaussianDropout(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        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        model.summary()\n                \n            \n        opt = tf.keras.optimizers.Adam(learning_rate = CFG['lr'])\n        \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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"CFG['num_holes'] = 5 \nCFG['side_length'] = CFG['inp_size']//10\n\ntrn_ind = train_fold[2]\nval_ind = val_fold[2]\n\ntrain_dataset = get_training_dataset([training_files[x] for x in trn_ind], labeled = True, ordered = False)\nval_dataset = get_validation_dataset([training_files[x] for x in val_ind], labeled = True, ordered = True)\n\nK.clear_session()\n\nmodel = get_model()\n# early stopping with 5 patience\nearly_stopping = tf.keras.callbacks.EarlyStopping(monitor = 'val_auc', mode = 'max', patience = 5, \n                                              verbose = 2, min_delta = 0.00025, restore_best_weights = True)\n\n# lr scheduler with 2 patience\ncb_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\n# saving best model weights\ncpoint_callback = tf.keras.callbacks.ModelCheckpoint(\n                    'best_res.h5', monitor='val_auc', verbose=1, save_best_only=True,\n                     mode='max', save_freq='epoch')\nhistory = 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)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# since we are splitting the dataset and iterating separately on images and ids, order matters.\ntest_ds = get_test_dataset(test_files, labeled = False, ordered = True)\ntest_images_ds = test_ds.map(lambda image, image_name: image)\n\nprint('Computing predictions...')\nprobabilities = np.average([np.concatenate(model.predict(test_images_ds))], axis = 0)\nprint('Generating submission.csv file...')\ntest_ids_ds = test_ds.map(lambda image, image_name: image_name).unbatch()\n\ntest_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U') \npred_df = pd.DataFrame({'image_name': test_ids, 'target': probabilities})\ndf_sub.drop('target', inplace = True, axis = 1)\ndf_sub = df_sub.merge(pred_df, on = 'image_name')\ndf_sub.to_csv('sub_EfficientNetB%i_%i.csv'%(CFG['eff_B'],CFG['inp_size']), index = False)","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}