{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"!pip install -q efficientnet\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\nimport dill\nfrom tensorflow.keras import backend as K\nimport tensorflow_addons as tfa","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"# Detect hardware, return appropriate distribution strategy\ntry:\n    # TPU detection. No parameters necessary if TPU_NAME environment variable is\n    # set: this is always the case on Kaggle.\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    print('Running on TPU ', tpu.master())\nexcept ValueError:\n    tpu = None\n\nif tpu:\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nelse:\n    # Default distribution strategy in Tensorflow. Works on CPU and single GPU.\n    strategy = tf.distribute.get_strategy()\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# For tf.dataset\nAUTO = tf.data.experimental.AUTOTUNE\n\n# Data access\nGCS_PATH = KaggleDatasets().get_gcs_path('melanoma-512x512')\n\n# Configuration\nEPOCHS = 40\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\nAUG_BATCH = BATCH_SIZE\nIMAGE_SIZE = [512, 512]\n# Seed\nSEED = 123\n# Learning rate\nLR = 0.0003\n# cutmix prob\ncutmix_rate = 0.3\n# gridmask prob\ngridmask_rate = 0\n\n# training filenames directory\nTRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train*.tfrec')\n# test filenames directory\nTEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test*.tfrec')\n# submission file\nSUB = pd.read_csv('/kaggle/input/siim-isic-melanoma-classification/sample_submission.csv')","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    # returns 3x3 transformmatrix which transforms indicies\n        \n    # CONVERT DEGREES TO RADIANS\n    rotation = math.pi * rotation / 180.\n    shear = math.pi * shear / 180.\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    rotation_matrix = tf.reshape( tf.concat([c1,s1,zero, -s1,c1,zero, zero,zero,one],axis=0),[3,3] )\n        \n    # SHEAR MATRIX\n    c2 = tf.math.cos(shear)\n    s2 = tf.math.sin(shear)\n    shear_matrix = tf.reshape( tf.concat([one,s2,zero, zero,c2,zero, zero,zero,one],axis=0),[3,3] )    \n    \n    # ZOOM MATRIX\n    zoom_matrix = tf.reshape( tf.concat([one/height_zoom,zero,zero, zero,one/width_zoom,zero, zero,zero,one],axis=0),[3,3] )\n    \n    # SHIFT MATRIX\n    shift_matrix = tf.reshape( tf.concat([one,zero,height_shift, zero,one,width_shift, zero,zero,one],axis=0),[3,3] )\n    \n    return K.dot(K.dot(rotation_matrix, shear_matrix), K.dot(zoom_matrix, shift_matrix))\n\ndef my_ceil(a, precision=0):\n    return np.round(a + 0.5 * 10**(-precision), precision)\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 = IMAGE_SIZE[0]\n    XDIM = DIM%2 #fix for size 331\n    \n    rot = (my_ceil(random.uniform(0, 1), 1) * 180.0) * 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['inp1'],tf.transpose(idx3))\n        \n    return {'inp1': tf.reshape(d,[DIM,DIM,3]), 'inp2': image['inp2']}, label\n\n# function to apply cutmix augmentation\ndef cutmix(image, label):\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 cutmix applied\n    \n    DIM = IMAGE_SIZE[0]    \n    imgs = []; labs = []\n    \n    for j in range(BATCH_SIZE):\n        \n        #random_uniform( shape, minval=0, maxval=None)        \n        # DO CUTMIX WITH PROBABILITY DEFINED ABOVE\n        P = tf.cast(tf.random.uniform([], 0, 1) <= cutmix_rate, tf.int32)\n        \n        # CHOOSE RANDOM IMAGE TO CUTMIX WITH\n        k = tf.cast(tf.random.uniform([], 0, BATCH_SIZE), tf.int32)\n        \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        \n        # Beta(1, 1)\n        b = tf.random.uniform([], 0, 1) # this is beta dist with alpha=1.0\n        \n\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        \n        # MAKE CUTMIX IMAGE\n        one = image['inp1'][j,ya:yb,0:xa,:]\n        two = image['inp1'][k,ya:yb,xa:xb,:]\n        three = image['inp1'][j,ya:yb,xb:DIM,:]        \n        #ya:yb\n        middle = tf.concat([one,two,three],axis=1)\n\n        img = tf.concat([image['inp1'][j,0:ya,:,:],middle,image['inp1'][j,yb:DIM,:,:]],axis=0)\n        imgs.append(img)\n        \n        # MAKE CUTMIX LABEL\n        a = tf.cast(WIDTH*WIDTH/DIM/DIM,tf.float32)\n        lab1 = label[j,]\n        lab2 = label[k,]\n        labs.append((1-a)*lab1 + a*lab2)\n\n    image2 = tf.reshape(tf.stack(imgs),(BATCH_SIZE,DIM,DIM,3))\n    label2 = tf.reshape(tf.stack(labs),(BATCH_SIZE, 1))\n    return {'inp1': image2, 'inp2': image['inp2']}, label2\n\ndef transform_gridmask(image, inv_mat, image_shape):\n    h, w, c = image_shape\n    cx, cy = w//2, h//2\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    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    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    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    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    return tf.transpose(tf.stack(rotated_image_channel), [1,2,0])\n\ndef random_rotate(image, angle, image_shape):\n    def get_rotation_mat_inv(angle):\n        # transform to radian\n        angle = math.pi * angle / 180\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        rot_mat_inv = tf.concat([cos_val, sin_val, zero, -sin_val, cos_val, zero, zero, zero, one], axis=0)\n        rot_mat_inv = tf.reshape(rot_mat_inv, [3,3])\n        return rot_mat_inv\n    angle = float(angle) * tf.random.normal([1],dtype='float32')\n    rot_mat_inv = get_rotation_mat_inv(angle)\n    return transform_gridmask(image, rot_mat_inv, image_shape)\n\ndef GridMask(image_height, image_width, d1, d2, rotate_angle=1, ratio=0.5):\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    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, PROBABILITY = gridmask_rate):\n    AugParams = {\n        'd1' : 100,\n        'd2': 160,\n        'rotate' : 45,\n        'ratio' : 0.3\n    }\n    \n    mask = GridMask(image_shape[0], image_shape[1], AugParams['d1'], AugParams['d2'], AugParams['rotate'], AugParams['ratio'])\n    if image_shape[-1] == 3:\n        mask = tf.concat([mask, mask, mask], axis=-1)\n        mask = tf.cast(mask,tf.float32)\n        P = tf.cast(tf.random.uniform([], 0, 1) <= PROBABILITY, tf.int32)\n    if P==1:\n        return image*mask\n    else:\n        return image\n\ndef gridmask(img_batch, label_batch):\n    return {'inp1': apply_grid_mask(img_batch['inp1'], (*IMAGE_SIZE, 3)), 'inp2': img_batch['inp2']}, label_batch\n\ndef seed_everything(seed):\n    random.seed(seed)\n    np.random.seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    tf.random.set_seed(seed)\n\n# function to decode our images (normalize and reshape)\ndef decode_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3)\n    # convert image to floats in [0, 1] range\n    image = tf.cast(image, tf.float32) / 255.0 \n    # explicit size needed for TPU\n    image = tf.reshape(image, [*IMAGE_SIZE, 3])\n    return image\n\n# this function parse our images and also get the target variable\ndef read_labeled_tfrecord(example):\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.float32)\n    # meta features\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\n# this function parse our image and also get our image_name (id) to perform predictions\ndef read_unlabeled_tfrecord(example):\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    # meta features\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 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\n# function for training and validation dataset\ndef setup_input1(image, label, data):\n    \n    # get anatom site general challenge vectors\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 {'inp1': image, 'inp2':  tabular}, label\n\n# function for the test set\ndef setup_input2(image, image_name, data):\n    \n    # get anatom site general challenge vectors\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 {'inp1': image, 'inp2':  tabular}, image_name\n\n# function for the validation (image name)\ndef setup_input3(image, image_name, target, data):\n    \n    # get anatom site general challenge vectors\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 {'inp1': image, 'inp2':  tabular}, image_name, target\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    data['inp1'] = tf.image.random_flip_left_right(data['inp1'])\n    data['inp1'] = tf.image.random_flip_up_down(data['inp1'])\n    data['inp1'] = tf.image.random_hue(data['inp1'], 0.01)\n    data['inp1'] = tf.image.random_saturation(data['inp1'], 0.7, 1.3)\n    data['inp1'] = tf.image.random_contrast(data['inp1'], 0.8, 1.2)\n    data['inp1'] = tf.image.random_brightness(data['inp1'], 0.1)\n    \n    return data, label\n\ndef get_training_dataset(filenames, labeled = True, ordered = False):\n    dataset = load_dataset(filenames, labeled = labeled, ordered = ordered)\n    dataset = dataset.map(setup_input1, 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(BATCH_SIZE)\n    dataset = dataset.map(cutmix, num_parallel_calls = AUTO)\n    dataset = dataset.map(gridmask, num_parallel_calls = AUTO)\n    # prefetch next batch while training (autotune prefetch buffer size)\n    dataset = dataset.prefetch(AUTO)\n    return dataset\n\ndef get_validation_dataset(filenames, labeled = True, ordered = True):\n    dataset = load_dataset(filenames, labeled = labeled, ordered = ordered)\n    dataset = dataset.map(setup_input1, num_parallel_calls = AUTO)\n    dataset = dataset.batch(BATCH_SIZE)\n    # using gpu, not enought memory to use cache\n    # dataset = dataset.cache()\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    dataset = load_dataset(filenames, labeled = labeled, ordered = ordered)\n    dataset = dataset.map(setup_input2, num_parallel_calls = AUTO)\n    dataset = dataset.batch(BATCH_SIZE)\n    # prefetch next batch while training (autotune prefetch buffer size)\n    dataset = dataset.prefetch(AUTO) \n    return dataset\n\n# function to count how many photos we have in\ndef count_data_items(filenames):\n    # the number of data items is written in the name of the .tfrec files, i.e. flowers00-230.tfrec = 230 data items\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    return np.sum(n)\n\n# this function parse our images and also get the target variable\ndef read_tfrecord_full(example):\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.float32)\n    # meta features\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_full(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_tfrecord_full, num_parallel_calls = AUTO) \n    return dataset\n\ndef get_data_full(filenames):\n    dataset = load_dataset_full(filenames)\n    dataset = dataset.map(setup_input3, num_parallel_calls = AUTO)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO)\n    return dataset\n\n\n\nNUM_TRAINING_IMAGES = int(count_data_items(TRAINING_FILENAMES) * 0.8)\n# use validation data for training\nNUM_VALIDATION_IMAGES = int(count_data_items(TRAINING_FILENAMES) * 0.2)\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // 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":{"trusted":true},"cell_type":"code","source":"def binary_focal_loss(gamma=2., alpha=.25):\n    \"\"\"\n    Binary form of focal loss.\n      FL(p_t) = -alpha * (1 - p_t)**gamma * log(p_t)\n      where p = sigmoid(x), p_t = p or 1 - p depending on if the label is 1 or 0, respectively.\n    References:\n        https://arxiv.org/pdf/1708.02002.pdf\n    Usage:\n     model.compile(loss=[binary_focal_loss(alpha=.25, gamma=2)], metrics=[\"accuracy\"], optimizer=adam)\n    \"\"\"\n    def binary_focal_loss_fixed(y_true, y_pred):\n        \"\"\"\n        :param y_true: A tensor of the same shape as `y_pred`\n        :param y_pred:  A tensor resulting from a sigmoid\n        :return: Output tensor.\n        \"\"\"\n        pt_1 = tf.where(tf.equal(y_true, 1), y_pred, tf.ones_like(y_pred))\n        pt_0 = tf.where(tf.equal(y_true, 0), y_pred, tf.zeros_like(y_pred))\n\n        epsilon = K.epsilon()\n        # clip to prevent NaN's and Inf's\n        pt_1 = K.clip(pt_1, epsilon, 1. - epsilon)\n        pt_0 = K.clip(pt_0, epsilon, 1. - epsilon)\n\n        return -K.sum(alpha * K.pow(1. - pt_1, gamma) * K.log(pt_1)) \\\n               -K.sum((1 - alpha) * K.pow(pt_0, gamma) * K.log(1. - pt_0))\n\n    return binary_focal_loss_fixed\n\ndef get_model():\n    with strategy.scope():\n        inp1 = tf.keras.layers.Input(shape = (*IMAGE_SIZE, 3), name='inp1')\n        inp2 = tf.keras.layers.Input(shape = (9), name='inp2')\n        efn1 = efn.EfficientNetB3(input_shape=(*IMAGE_SIZE,3), weights = 'imagenet', include_top = False)\n        x1 = efn1(inp1)\n        x1 = tf.keras.layers.GlobalAveragePooling2D()(x1)\n        \n        small = tf.keras.layers.AveragePooling2D(pool_size=2, strides=2)(inp1)\n        efn2 = efn.EfficientNetB4(input_shape=(256,256,3), weights='imagenet', include_top=False)\n        x2 = efn2(small)\n        x2 = tf.keras.layers.GlobalAveragePooling2D()(x2)\n        \n        #smaller = tf.keras.layers.AveragePooling2D(pool_size=4, strides=4)(inp1)\n        #efn3 = efn.EfficientNetB4(input_shape=(128,128,3), weights='imagenet', \n        #                          include_top=False)\n        #x3 = efn3(smaller)\n        #x3 = tf.keras.layers.GlobalAveragePooling2D()(x3)\n        \n        x = tf.keras.layers.Concatenate()([x1,x2])\n        \n        xtab = tf.keras.layers.Dense(50)(inp2)\n        xtab = tf.keras.layers.BatchNormalization()(xtab)\n        xtab = tf.keras.layers.Activation('relu')(xtab)\n        concat = tf.keras.layers.concatenate([x, xtab])\n        output = tf.keras.layers.Dense(1, activation = 'sigmoid')(concat)\n\n        model = tf.keras.models.Model(inputs = [inp1, inp2], outputs = [output])\n\n        opt = tf.keras.optimizers.Adam(learning_rate = LR)\n        # opt = tfa.optimizers.SWA(opt)\n\n        model.compile(optimizer=opt, loss=[binary_focal_loss(gamma = 2.0, alpha = 0.80)], metrics=[tf.keras.metrics.BinaryAccuracy(), tf.keras.metrics.AUC()])\n\n        return model\n    \ndef train_and_predict(SUB, folds = 3):\n    \n    models = []\n    oof_image_name = []\n    oof_target = []\n    oof_prediction = []\n    \n    # seed everything\n    seed_everything(SEED)\n\n    kfold = KFold(folds, shuffle = True, random_state = SEED)\n    for fold, (trn_ind, val_ind) in enumerate(kfold.split(TRAINING_FILENAMES)):\n        print('\\n')\n        print('-'*50)\n        print(f'Training fold {fold + 1}')\n        train_dataset = get_training_dataset([TRAINING_FILENAMES[x] for x in trn_ind], labeled = True, ordered = False)\n        val_dataset = get_validation_dataset([TRAINING_FILENAMES[x] for x in val_ind], labeled = True, ordered = True)\n        K.clear_session()\n        model = get_model()\n        # using early stopping using val loss\n        early_stopping = tf.keras.callbacks.EarlyStopping(monitor = 'val_auc', mode = 'max', patience = 5, \n                                                      verbose = 1, min_delta = 0.0001, restore_best_weights = True)\n        # lr scheduler\n        cb_lr_schedule = tf.keras.callbacks.ReduceLROnPlateau(monitor = 'val_auc', factor = 0.4, patience = 2, verbose = 1, min_delta = 0.0001, mode = 'max')\n        history = model.fit(train_dataset, steps_per_epoch = STEPS_PER_EPOCH, epochs = EPOCHS, callbacks = [early_stopping, cb_lr_schedule], validation_data = val_dataset, verbose = 2)\n        models.append(model)\n        \n        # want to predict the validation set and save them for stacking\n        number_of_files = count_data_items([TRAINING_FILENAMES[x] for x in val_ind])\n        dataset = get_data_full([TRAINING_FILENAMES[x] for x in val_ind])\n        # get the image name\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        # get the real target\n        target = dataset.map(lambda image, image_name, target: target).unbatch()\n        target = next(iter(target.batch(number_of_files))).numpy()\n        # predict the 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    print('\\n')\n    print('-'*50)\n    # save oof predictions\n    oof_df = pd.DataFrame({'image_name': oof_image_name, 'target': oof_target, 'predictions': oof_prediction})\n    oof_df.to_csv('EfficientNetB4_5_ensemble.csv', 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_FILENAMES, 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    # all in one batch\n    test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U') # all in one batch\n    pred_df = pd.DataFrame({'image_name': test_ids, 'target': probabilities})\n    SUB.drop('target', inplace = True, axis = 1)\n    SUB = SUB.merge(pred_df, on = 'image_name')\n    SUB.to_csv('sub_EfficientNetB4_5_ensemble.csv', index = False)\n    \n    return oof_target, oof_prediction\n    \noof_target, oof_prediction = train_and_predict(SUB)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"TRAINING_FILENAMES","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# calculate our out of folds roc auc score\nroc_auc = metrics.roc_auc_score(oof_target, oof_prediction)\nprint('Our out of folds roc auc score is: ', roc_auc)","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}