{"cells":[{"metadata":{},"cell_type":"markdown","source":"Fork from Incredible TPUs - finetune EffNetB0-B6 at once. \nThanks @AgentAuers very much!","execution_count":null},{"metadata":{"trusted":true,"id":"kY0v6-e9eW3J"},"cell_type":"code","source":"DEVICE = \"TPU\"\n\nCFG = dict(\n    net_count         =   7,\n    batch_size        =  16,\n    \n    read_size         = 384, \n    crop_size         = 380, \n    net_size          = 384, \n    \n    LR_START          =   0.000005,\n    LR_MAX            =   0.000020,\n    LR_MIN            =   0.000001,\n    LR_RAMPUP_EPOCHS  =   5,\n    LR_SUSTAIN_EPOCHS =   0,\n    LR_EXP_DECAY      =   0.8,\n    epochs            =  15,\n    \n    rot               = 180.0,\n    shr               =   2.0,\n    hzoom             =   8.0,\n    wzoom             =   8.0,\n    hshift            =   8.0,\n    wshift            =   8.0,\n\n    optimizer         = 'adam',\n    label_smooth_fac  =   0.05,\n    \n    tta_steps         =  25    \n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"id":"euZDUcqbeW3N"},"cell_type":"code","source":"!pip install -q efficientnet","execution_count":null,"outputs":[]},{"metadata":{"id":"NVAYDs83WJIV"},"cell_type":"markdown","source":"# IMPORT LIB","execution_count":null},{"metadata":{"trusted":true,"id":"cOlR9scseW3U"},"cell_type":"code","source":"import os, random, re, math, time\nimport torch\nimport numpy as np\nimport pandas as pd\n\nimport tensorflow as tf\nimport tensorflow.keras.backend as K\nimport efficientnet.tfkeras as efn\n\nimport PIL\n\nfrom tqdm import tqdm\nfrom sklearn.metrics import roc_auc_score\n\nimport os\nimport keras\nimport efficientnet.tfkeras as efn\nfrom tensorflow.keras.models import Sequential\nimport tensorflow.keras.layers as L\nfrom tensorflow.keras.layers import Dense, GlobalAveragePooling2D\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.callbacks import ReduceLROnPlateau , EarlyStopping , ModelCheckpoint , LearningRateScheduler\nfrom tensorflow.keras.applications import ResNet152V2, InceptionResNetV2, InceptionV3, Xception, VGG19,DenseNet201\nfrom kaggle_datasets import KaggleDatasets","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"id":"NXAhK9Z0eW3X"},"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-384x384')\nfiles_train = np.sort(np.array(tf.io.gfile.glob(GCS_PATH + '/train*.tfrec')))\nfiles_test  = np.sort(np.array(tf.io.gfile.glob(GCS_PATH + '/test*.tfrec')))","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true,"id":"ig8qevgseW3a","outputId":"039b763a-f3a7-4464-b68d-d90a654d7080"},"cell_type":"code","source":"if 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        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    \n\nAUTO     = tf.data.experimental.AUTOTUNE\nREPLICAS = strategy.num_replicas_in_sync\nprint(f'REPLICAS: {REPLICAS}')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"id":"XSvVmk23eW3e"},"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    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\n\ndef transform(image, cfg):    \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[\"read_size\"]\n    XDIM = DIM%2 #fix for size 331\n    \n    rot = cfg['rot'] * tf.random.normal([1], dtype='float32')\n    shr = cfg['shr'] * tf.random.normal([1], dtype='float32') \n    h_zoom = 1.0 + tf.random.normal([1], dtype='float32') / cfg['hzoom']\n    w_zoom = 1.0 + tf.random.normal([1], dtype='float32') / cfg['wzoom']\n    h_shift = cfg['hshift'] * tf.random.normal([1], dtype='float32') \n    w_shift = cfg['wshift'] * 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, tf.transpose(idx3))\n        \n    return tf.reshape(d,[DIM, DIM,3])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"id":"HImYY3qoeW3i"},"cell_type":"code","source":"def read_labeled_tfrecord(example):\n    tfrec_format = {\n        'image'                        : tf.io.FixedLenFeature([], tf.string),\n        'image_name'                   : tf.io.FixedLenFeature([], tf.string),\n        'patient_id'                   : tf.io.FixedLenFeature([], tf.int64),\n        'sex'                          : tf.io.FixedLenFeature([], tf.int64),\n        'age_approx'                   : tf.io.FixedLenFeature([], tf.int64),\n        'anatom_site_general_challenge': tf.io.FixedLenFeature([], tf.int64),\n        'diagnosis'                    : tf.io.FixedLenFeature([], tf.int64),\n        'target'                       : tf.io.FixedLenFeature([], tf.int64)\n    }           \n    example = tf.io.parse_single_example(example, tfrec_format)\n    return example['image'], example['target']\n\n\ndef read_unlabeled_tfrecord(example, return_image_name):\n    tfrec_format = {\n        'image'                        : tf.io.FixedLenFeature([], tf.string),\n        'image_name'                   : tf.io.FixedLenFeature([], tf.string),\n    }\n    example = tf.io.parse_single_example(example, tfrec_format)\n    return example['image'], example['image_name'] if return_image_name else 0\n\n \ndef prepare_image(img, cfg=None, augment=True):    \n    img = tf.image.decode_jpeg(img, channels=3)\n    img = tf.image.resize(img, [cfg['read_size'], cfg['read_size']])\n    img = tf.cast(img, tf.float32) / 255.0\n    \n    if augment:\n        img = transform(img, cfg)\n        img = tf.image.random_crop(img, [cfg['crop_size'], cfg['crop_size'], 3])\n        img = tf.image.random_flip_left_right(img)\n        #img = tf.image.random_hue(img, 0.01)\n        img = tf.image.random_saturation(img, 0.7, 1.3)\n        img = tf.image.random_contrast(img, 0.8, 1.2)\n        img = tf.image.random_brightness(img, 0.1)\n\n    else:\n        img = tf.image.central_crop(img, cfg['crop_size'] / cfg['read_size'])\n                                   \n    img = tf.image.resize(img, [cfg['net_size'], cfg['net_size']])\n    img = tf.reshape(img, [cfg['net_size'], cfg['net_size'], 3])\n    return img\n\ndef count_data_items(filenames):\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) \n         for filename in filenames]\n    return np.sum(n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"id":"UJFoX0eseW3l"},"cell_type":"code","source":"def get_dataset(files, cfg, augment = False, shuffle = False, repeat = False, \n                labeled=True, return_image_names=True):\n    \n    ds = tf.data.TFRecordDataset(files, num_parallel_reads=AUTO)\n    ds = ds.cache()\n    \n    if repeat:\n        ds = ds.repeat()\n    \n    if shuffle: \n        ds = ds.shuffle(1024*8)\n        opt = tf.data.Options()\n        opt.experimental_deterministic = False\n        ds = ds.with_options(opt)\n        \n    if labeled: \n        ds = ds.map(read_labeled_tfrecord, num_parallel_calls=AUTO)\n    else:\n        ds = ds.map(lambda example: read_unlabeled_tfrecord(example, return_image_names), \n                    num_parallel_calls=AUTO)      \n    \n    ds = ds.map(lambda img, imgname_or_label: (prepare_image(img, augment=augment, cfg=cfg), \n                                               imgname_or_label), \n                num_parallel_calls=AUTO)\n    \n    ds = ds.batch(cfg['batch_size'] * REPLICAS)\n    ds = ds.prefetch(AUTO)\n    return ds","execution_count":null,"outputs":[]},{"metadata":{"id":"KvvtZh9seW3n"},"cell_type":"markdown","source":"## Test the input pipeline\nBefore calling any neural net I always test the input pipeline.\nHere are images from the train data.","execution_count":null},{"metadata":{"trusted":true,"id":"KinUJxW-eW3o","outputId":"d73e8b4f-778f-4b21-e7ea-9a78544dd93d"},"cell_type":"code","source":"def show_dataset(thumb_size, cols, rows, ds):\n    mosaic = PIL.Image.new(mode='RGB', size=(thumb_size*cols + (cols-1), \n                                             thumb_size*rows + (rows-1)))\n   \n    for idx, data in enumerate(iter(ds)):\n        img, target_or_imgid = data\n        ix  = idx % cols\n        iy  = idx // cols\n        img = np.clip(img.numpy() * 255, 0, 255).astype(np.uint8)\n        img = PIL.Image.fromarray(img)\n        img = img.resize((thumb_size, thumb_size), resample=PIL.Image.BILINEAR)\n        mosaic.paste(img, (ix*thumb_size + ix, \n                           iy*thumb_size + iy))\n\n    display(mosaic)\n    \nds = get_dataset(files_train, CFG).unbatch().take(12*5)   \nshow_dataset(64, 12, 5, ds)","execution_count":null,"outputs":[]},{"metadata":{"id":"mNLu34TLeW3r"},"cell_type":"markdown","source":"## Test of image augmentation","execution_count":null},{"metadata":{"trusted":true,"id":"tkdw7JdEeW3s","outputId":"4fd1f330-5ea1-4372-dfad-a7c132e40462"},"cell_type":"code","source":"ds = tf.data.TFRecordDataset(files_train, num_parallel_reads=AUTO)\nds = ds.take(1).cache().repeat()\nds = ds.map(read_labeled_tfrecord, num_parallel_calls=AUTO)\nds = ds.map(lambda img, target: (prepare_image(img, cfg=CFG, augment=True), target), \n            num_parallel_calls=AUTO)\nds = ds.take(12*5)\nds = ds.prefetch(AUTO)\n\nshow_dataset(64, 12, 5, ds)","execution_count":null,"outputs":[]},{"metadata":{"id":"jgrVLvoieW3w"},"cell_type":"markdown","source":"## Images from the test data","execution_count":null},{"metadata":{"trusted":true,"id":"haariu1DeW3w","outputId":"eaae8f1a-5985-41b0-9bf9-d7bd05e05c6f"},"cell_type":"code","source":"ds = get_dataset(files_test, CFG, labeled=False).unbatch().take(12*5)   \nshow_dataset(64, 12, 5, ds)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"id":"H2t_T6s6eW3z"},"cell_type":"code","source":"def get_lr_callback(cfg):\n    lr_start   = cfg['LR_START']\n    lr_max     = cfg['LR_MAX'] * strategy.num_replicas_in_sync\n    lr_min     = cfg['LR_MIN']\n    lr_ramp_ep = cfg['LR_RAMPUP_EPOCHS']\n    lr_sus_ep  = cfg['LR_SUSTAIN_EPOCHS']\n    lr_decay   = cfg['LR_EXP_DECAY']\n   \n    def lrfn(epoch):\n        if epoch < lr_ramp_ep:\n            lr = (lr_max - lr_start) / lr_ramp_ep * epoch + lr_start\n            \n        elif epoch < lr_ramp_ep + lr_sus_ep:\n            lr = lr_max\n            \n        else:\n            lr = (lr_max - lr_min) * lr_decay**(epoch - lr_ramp_ep - lr_sus_ep) + lr_min\n            \n        return lr\n\n    lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=False)\n    return lr_callback","execution_count":null,"outputs":[]},{"metadata":{"id":"56pGO_FBrINa"},"cell_type":"markdown","source":"# MODEL ARCHITECTURE","execution_count":null},{"metadata":{"id":"j8n-mjgp60eZ"},"cell_type":"markdown","source":"## EFFICIENTNET 4-7","execution_count":null},{"metadata":{"id":"kjNyB7bC88WJ","trusted":false},"cell_type":"code","source":"def get_model(cfg):\n    model_input = tf.keras.Input(shape=(cfg['net_size'], cfg['net_size'], 3), name='imgIn')\n\n    dummy = tf.keras.layers.Lambda(lambda x:x)(model_input)\n    \n    outputs = []    \n    for i in range(4,8):\n        constructor = getattr(efn, f'EfficientNetB{i}')\n        \n        x = constructor(include_top=False, weights='noisy-student', \n                        input_shape=(cfg['net_size'], cfg['net_size'], 3), \n                        pooling='avg')(dummy)\n        \n        x = tf.keras.layers.Dense(1, activation='sigmoid')(x)\n        outputs.append(x)\n        \n    model = tf.keras.Model(model_input, outputs, name='aNetwork')\n    model.summary()\n    return model","execution_count":null,"outputs":[]},{"metadata":{"id":"Mv_y1HRr63j9","trusted":false},"cell_type":"code","source":"def compile_new_model(cfg):    \n    with strategy.scope():\n        model = get_model(cfg)\n     \n        losses = [tf.keras.losses.BinaryCrossentropy(label_smoothing = cfg['label_smooth_fac'])\n                  for i in range(4,8)]\n        \n        model.compile(\n            optimizer = cfg['optimizer'],\n            loss      = losses,\n            metrics   = [tf.keras.metrics.AUC(name='auc')])\n        \n    return model","execution_count":null,"outputs":[]},{"metadata":{"id":"LlS4Pi1R9nI7","outputId":"471c82d1-97d8-4d1c-c519-1ad72ec1e2f7","trusted":false},"cell_type":"code","source":"len(files_train)","execution_count":null,"outputs":[]},{"metadata":{"id":"rrEbhFe291B3","trusted":false},"cell_type":"code","source":"mc = ModelCheckpoint('best_model7.h5', monitor = 'train_auc' , mode = 'max', verbose = 1 , save_best_only = True)","execution_count":null,"outputs":[]},{"metadata":{"id":"iFQK9rng8y1b","outputId":"ac3fd9ac-a9e3-4086-c4c1-4094b99942e2","trusted":false},"cell_type":"code","source":"\nds_train     = get_dataset(files_train, CFG, augment=True, shuffle=True, repeat=True)\nds_train     = ds_train.map(lambda img, label: (img, tuple([label] * CFG['net_count'])))\n\nsteps_train  = count_data_items(files_train) / (CFG['batch_size'] * REPLICAS)\n\nmodel        = compile_new_model(CFG)\nhistory      = model.fit(ds_train, \n                         verbose          = 1,\n                         steps_per_epoch  = steps_train, \n                         epochs           = CFG['epochs'],\n                         callbacks        = [get_lr_callback(CFG), mc])","execution_count":null,"outputs":[]},{"metadata":{"id":"NS5Uqf7ILSYA"},"cell_type":"markdown","source":"## INCEPTIONRESNETV2","execution_count":null},{"metadata":{"id":"Ph0HnjH6rMiF","outputId":"1b592ebf-c53b-46b0-8ace-2b4f6652f2b6","trusted":true},"cell_type":"code","source":"with strategy.scope():\n    model = tf.keras.Sequential([\n        InceptionResNetV2(\n            input_shape=(CFG['net_size'], CFG['net_size'], 3),\n            weights='imagenet',\n            include_top=False\n        ),\n        L.GlobalMaxPooling2D(),\n        L.Dense(1, activation='sigmoid')\n        # SoftProbField()\n    ])\n    losses = tf.keras.losses.BinaryCrossentropy(label_smoothing = CFG['label_smooth_fac'])\n    model.compile(\n            optimizer = CFG['optimizer'],\n            loss      = losses,\n            metrics   = [tf.keras.metrics.AUC(name='auc')])\n        \n    model.summary()","execution_count":null,"outputs":[]},{"metadata":{"id":"MKbHYuAusDbn","trusted":true},"cell_type":"code","source":"mc = ModelCheckpoint('best_model.h5', monitor = 'train_auc' , mode = 'max', verbose = 1 , save_best_only = True)","execution_count":null,"outputs":[]},{"metadata":{"id":"2n4pzCcU1BJZ","outputId":"a14ecbe9-fe57-4d76-9f9e-fa37b81ac22e","trusted":true},"cell_type":"code","source":"ds_train     = get_dataset(files_train, CFG, augment=True, shuffle=True, repeat=True)\nsteps_train  = count_data_items(files_train) / (CFG['batch_size'] * REPLICAS)\n\nhistory      = model.fit(ds_train, \n                         verbose          = 1,\n                         steps_per_epoch  = steps_train, \n                         epochs           = CFG['epochs'],\n        \n                         callbacks        = [get_lr_callback(CFG),mc])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save_weights('inception.h5')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import os\nos.chdir(r'/kaggle/working')\nfrom IPython.display import FileLink\nFileLink(r'inception.h5')","execution_count":null,"outputs":[]},{"metadata":{"id":"FGs-cXCgIFsG"},"cell_type":"markdown","source":"## EFFICIENT B7 MODEL","execution_count":null},{"metadata":{"id":"u451rDC1upPo","outputId":"0afc9ddf-4680-4842-8d28-7485616c09dc","trusted":true},"cell_type":"code","source":"with strategy.scope():\n    model2 = tf.keras.Sequential([\n        efn.EfficientNetB7(\n            input_shape=(CFG['net_size'], CFG['net_size'], 3),\n            weights='noisy-student',\n            include_top=False\n        ),\n         L.GlobalMaxPooling2D(),\n        L.Dense(1, activation='sigmoid')\n    ])\n    losses = tf.keras.losses.BinaryCrossentropy(label_smoothing = CFG['label_smooth_fac'])\n    model2.compile(\n            optimizer = CFG['optimizer'],\n            loss      = losses,\n            metrics   = [tf.keras.metrics.AUC(name='auc')])\n        \n    model2.summary()","execution_count":null,"outputs":[]},{"metadata":{"id":"VBW0o-LC9i69","trusted":true},"cell_type":"code","source":"mc = ModelCheckpoint('best_model2.h5', monitor = 'train_auc' , mode = 'max', verbose = 1 , save_best_only = True)","execution_count":null,"outputs":[]},{"metadata":{"id":"zk9NXZB6vbLT","outputId":"2eafc73c-8f3d-4cd9-eacd-522a35750001","trusted":true},"cell_type":"code","source":"ds_train     = get_dataset(files_train, CFG, augment=True, shuffle=True, repeat=True)\n\nsteps_train  = count_data_items(files_train) / (CFG['batch_size'] * REPLICAS)\nhistory      = model2.fit(ds_train, \n                         verbose          = 1,\n                         steps_per_epoch  = steps_train, \n                         epochs           = CFG['epochs'],\n                         \n                         callbacks        = [get_lr_callback(CFG),mc])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"CFG['batch_size'] = 256\n\ncnt_test   = count_data_items(files_test)\nsteps      = cnt_test / (CFG['batch_size'] * REPLICAS) * CFG['tta_steps']\nds_testAug = get_dataset(files_test, CFG, augment=True, repeat=True, \n                         labeled=False, return_image_names=False)\n\nprobs = model2.predict(ds_testAug, verbose=1, steps=steps)\n\nprobs = np.stack(probs)\nprobs = probs[:,:cnt_test * CFG['tta_steps']]\nprobs = np.stack(np.split(probs, CFG['tta_steps'], axis=1), axis=1)\nprobs = np.mean(probs, axis=1)","execution_count":null,"outputs":[]},{"metadata":{"id":"87EYEMNkNjoL"},"cell_type":"markdown","source":"## XCEPTION","execution_count":null},{"metadata":{"id":"B_xiqLNiONtQ","outputId":"86a28e9b-8c30-4066-9483-570657697a38","trusted":false},"cell_type":"code","source":"with strategy.scope():\n    model3 = tf.keras.Sequential([\n        Xception(input_shape=(CFG['net_size'], CFG['net_size'], 3),\n                 weights='imagenet', include_top=False),\n         L.GlobalMaxPooling2D(),\n        L.Dense(1, activation='sigmoid')\n    ])\n    losses = tf.keras.losses.BinaryCrossentropy(label_smoothing = CFG['label_smooth_fac'])\n    model3.compile(\n            optimizer = CFG['optimizer'],\n            loss      = losses,\n            metrics   = [tf.keras.metrics.AUC(name='auc')])\n        \n    model3.summary()","execution_count":null,"outputs":[]},{"metadata":{"id":"jqnh3z3XOyxH","trusted":false},"cell_type":"code","source":"mc = ModelCheckpoint('best_model3.h5', monitor = 'val_auc' , mode = 'max', verbose = 1 , save_best_only = True)","execution_count":null,"outputs":[]},{"metadata":{"id":"LTBxluQrO0HG","outputId":"bfdd63c4-dd5b-4ce0-e0f7-31c29299195f","trusted":false},"cell_type":"code","source":"history      = model3.fit(ds_train, \n                         verbose          = 1,\n                         steps_per_epoch  = steps_train, \n                         epochs           = CFG['epochs'],\n                         validation_data = ds_valid,\n                          validation_steps= validation_step,\n                         callbacks        = [get_lr_callback(CFG),mc])","execution_count":null,"outputs":[]},{"metadata":{"id":"l-UEsd4aS5pd"},"cell_type":"markdown","source":"## EFICIENTNET B6","execution_count":null},{"metadata":{"id":"UaTs2_hvS31n","outputId":"e95731f4-32b0-4da9-e357-3941a3b16620","trusted":true},"cell_type":"code","source":"with strategy.scope():\n    model4 = tf.keras.Sequential([\n        efn.EfficientNetB6(\n            input_shape=(CFG['net_size'], CFG['net_size'], 3),\n            weights='noisy-student',\n            include_top=False\n        ),\n         L.GlobalMaxPooling2D(),\n        L.Dense(1, activation='sigmoid')\n    ])\n    losses = tf.keras.losses.BinaryCrossentropy(label_smoothing = CFG['label_smooth_fac'])\n    model4.compile(\n            optimizer = CFG['optimizer'],\n            loss      = losses,\n            metrics   = [tf.keras.metrics.AUC(name='auc')])\n        \n    model4.summary()","execution_count":null,"outputs":[]},{"metadata":{"id":"43H-rVoQTUtD","trusted":true},"cell_type":"code","source":"mc = ModelCheckpoint('best_model4.h5', monitor = 'val_auc' , mode = 'max', verbose = 1 , save_best_only = True)","execution_count":null,"outputs":[]},{"metadata":{"id":"_xkfVkI7TYV-","outputId":"2c75a6b9-394b-4b99-d4ae-be1533d8236a","trusted":false},"cell_type":"code","source":"history      = model4.fit(ds_train, \n                         verbose          = 1,\n                         steps_per_epoch  = steps_train, \n                         epochs           = CFG['epochs'],\n                         callbacks        = [get_lr_callback(CFG),mc])","execution_count":null,"outputs":[]},{"metadata":{"id":"49ZGunAZTgUY"},"cell_type":"markdown","source":"## RESNET152V2","execution_count":null},{"metadata":{"id":"U992rFuQT1fI","outputId":"f9dbf5d6-f47d-491a-e9e8-21388f4ce628","trusted":false},"cell_type":"code","source":"with strategy.scope():\n    model5 = tf.keras.Sequential([\n        ResNet152V2(\n            input_shape=(CFG['net_size'], CFG['net_size'], 3),\n            weights='imagenet',\n            include_top=False\n        ),\n         L.GlobalMaxPooling2D(),\n        L.Dense(1, activation='sigmoid')\n    ])\n    losses = tf.keras.losses.BinaryCrossentropy(label_smoothing = CFG['label_smooth_fac'])\n    model5.compile(\n            optimizer = CFG['optimizer'],\n            loss      = losses,\n            metrics   = [tf.keras.metrics.AUC(name='auc')])\n        \n    model5.summary()\n","execution_count":null,"outputs":[]},{"metadata":{"id":"Dsh2uMNPT-5i","trusted":false},"cell_type":"code","source":"rdc = ReduceLROnPlateau(monitor='val_auc', factor=0.3, patience=2, verbose=1, mode='max')\nmc = ModelCheckpoint('best_model6.h5', monitor = 'val_auc' , mode = 'max', verbose = 1 , save_best_only = True)","execution_count":null,"outputs":[]},{"metadata":{"id":"2yyV9UDKUBPo","outputId":"a0c429f6-4fe9-4014-e282-2e8ca6185bce","trusted":false},"cell_type":"code","source":"history      = model5.fit(ds_train, \n                         verbose          = 1,\n                         steps_per_epoch  = steps_train, \n                         epochs           = 5,#CFG['epochs'],\n                         validation_data = ds_valid,\n                          validation_steps= validation_step,\n                         callbacks        = [get_lr_callback(CFG),mc])","execution_count":null,"outputs":[]},{"metadata":{"id":"SIJzKLPtgHSd"},"cell_type":"markdown","source":"## DENSENET201\n\n","execution_count":null},{"metadata":{"id":"ae7YgnaLg2TT","outputId":"4a8f31fb-c65b-4151-8b50-7dc7ba7359d6","trusted":false},"cell_type":"code","source":"with strategy.scope():\n    model6 = tf.keras.Sequential([\n        DenseNet201(\n            input_shape=(CFG['net_size'], CFG['net_size'], 3),\n            weights='imagenet',\n            include_top=False\n        ),\n         L.GlobalMaxPooling2D(),\n        L.Dense(1, activation='sigmoid')\n    ])\n    losses = tf.keras.losses.BinaryCrossentropy(label_smoothing = CFG['label_smooth_fac'])\n    model6.compile(\n            optimizer = CFG['optimizer'],\n            loss      = losses,\n            metrics   = [tf.keras.metrics.AUC(name='auc')])\n        \n    model6.summary()\n","execution_count":null,"outputs":[]},{"metadata":{"id":"g1uVLmOnhfBm","trusted":false},"cell_type":"code","source":"rdc = ReduceLROnPlateau(monitor='val_auc', factor=0.3, patience=2, verbose=1, mode='max')\nmc = ModelCheckpoint('best_model5.h5', monitor = 'val_auc' , mode = 'max', verbose = 1 , save_best_only = True)","execution_count":null,"outputs":[]},{"metadata":{"id":"jmsw2YJ4hhsR","outputId":"b38a4517-f405-4e0a-db83-2223edb6bac6","trusted":false},"cell_type":"code","source":"history      = model6.fit(ds_train, \n                         verbose          = 1,\n                         steps_per_epoch  = steps_train, \n                         epochs           = CFG['epochs'],\n                         validation_data = ds_valid,\n                          validation_steps= validation_step,\n                         callbacks        = [get_lr_callback(CFG),mc,rdc])","execution_count":null,"outputs":[]},{"metadata":{"id":"6o7TYTWDUGvv","trusted":false},"cell_type":"code","source":"!mv *.h5 '/content/drive/My Drive/dataset/'","execution_count":null,"outputs":[]},{"metadata":{"id":"E_q8wrnSWc5c"},"cell_type":"markdown","source":"# VALIDATION","execution_count":null},{"metadata":{"id":"FDn3bUAq9mXb","trusted":false},"cell_type":"code","source":"ds = get_dataset(files_valid, CFG, augment=False, repeat=False, \n                 labeled=True, return_image_names=True)\n\nlabel_valid = np.array([img_name.numpy()\n                        for img, img_name in iter(ds.unbatch())])","execution_count":null,"outputs":[]},{"metadata":{"id":"NOv4TOMSWgLw","trusted":false},"cell_type":"code","source":"model2.load_weights('/content/drive/My Drive/dataset/best_model2.h5')\nmodel6.load_weights('/content/drive/My Drive/dataset/best_model5.h5')","execution_count":null,"outputs":[]},{"metadata":{"id":"5qEwsoq9fcfQ","trusted":false},"cell_type":"code","source":"model.load_weights('/content/drive/My Drive/dataset/best_model.h5')\nmodel3.load_weights('/content/drive/My Drive/dataset/best_model3.h5')\nmodel4.load_weights('/content/drive/My Drive/dataset/best_model4.h5')\nmodel5.load_weights('/content/drive/My Drive/dataset/best_model6.h5')\n","execution_count":null,"outputs":[]},{"metadata":{"id":"fdd5jUTBe_cA","outputId":"40797acf-b8f0-4a06-eefd-bfd2943712ae","trusted":false},"cell_type":"code","source":"label =  model.predict(ds, verbose=1,  steps  = validation_step)\nlabel2 = model2.predict(ds, verbose=1, steps  = validation_step)\nlabel3 = model3.predict(ds, verbose=1, steps  = validation_step)\nlabel4 = model4.predict(ds, verbose=1, steps  = validation_step)\nlabel5 = model5.predict(ds, verbose=1, steps  = validation_step)\nlabel6 = model6.predict(ds, verbose=1, steps  = validation_step)","execution_count":null,"outputs":[]},{"metadata":{"id":"AEfu-lkv9TMG","trusted":false},"cell_type":"code","source":"cnt_test   = count_data_items(files_valid)\nprobs = np.concatenate(( label2, label6), axis=1)\nprobs = np.stack(probs)\nprobs = probs[:,:cnt_test * CFG['tta_steps']]\nprobs = np.mean(probs, axis=1)","execution_count":null,"outputs":[]},{"metadata":{"id":"4h8bClaIVDBs","outputId":"b89952af-10d0-408d-9899-3d4a2b652200","trusted":false},"cell_type":"code","source":"probs.shape","execution_count":null,"outputs":[]},{"metadata":{"id":"szj224XhUkCv","outputId":"c73026a7-0aa1-4129-9af9-af75ef7fb91a","trusted":false},"cell_type":"code","source":"roc_auc_score( np.array(probs)>0.5, label_valid)","execution_count":null,"outputs":[]},{"metadata":{"id":"0qKPGVWf8Hbn","outputId":"81ed5e23-b736-4f8f-c97b-304c295108c9","trusted":false},"cell_type":"code","source":"plt.hist(label_valid)","execution_count":null,"outputs":[]},{"metadata":{"id":"rA5DRcwnsQre"},"cell_type":"markdown","source":"# PREDICT TO DATASET","execution_count":null},{"metadata":{"id":"pyf-wAz6eW3_"},"cell_type":"markdown","source":"### predict the test set using augmented images","execution_count":null},{"metadata":{"trusted":true,"id":"wyDMaqZAeW4A","outputId":"f0169756-7911-49e8-d87d-19e21e26a847"},"cell_type":"code","source":"CFG['batch_size'] = 256\n\ncnt_test   = count_data_items(files_test)\nsteps      = cnt_test / (CFG['batch_size'] * REPLICAS) * CFG['tta_steps']\nds_testAug = get_dataset(files_test, CFG, augment=False, repeat=False, \n                         labeled=False, return_image_names=False)\n\n#prob1 = model2.predict(ds_testAug, verbose=1, steps=steps)\nprob2 = model6.predict(ds_testAug, verbose=1, steps=steps)","execution_count":null,"outputs":[]},{"metadata":{"id":"5t1brr7oYVaX","outputId":"f8a35b74-8743-4980-aec4-79e164c4d831","trusted":false},"cell_type":"code","source":"probs = np.stack(prob2)\n\nprobs = prob2[:,:cnt_test * CFG['tta_steps']]\nprobs = probs.squeeze()\nprobs = np.stack(np.split(probs, CFG['tta_steps']))\nprobs = np.mean(probs, axis=1)","execution_count":null,"outputs":[]},{"metadata":{"id":"TIvBvzAxZDOc","outputId":"3d711b40-f9e8-4107-c9f1-4540e23695f9","trusted":false},"cell_type":"code","source":"prob2.shape, len(image_names), probs.squeeze().shape","execution_count":null,"outputs":[]},{"metadata":{"id":"hh6L-ySu4f93","outputId":"0819316a-7214-463a-95c2-9dfcb9838c81","trusted":false},"cell_type":"code","source":"(276480/(cnt_test*CFG['tta_steps']))","execution_count":null,"outputs":[]},{"metadata":{"id":"Iuafd6gcgJY_","outputId":"2b3e616c-3c5f-4373-f1c4-375cac19379d","trusted":false},"cell_type":"code","source":"x = np.arange(9.0)\nx.shape\nnp.split(x, 3)","execution_count":null,"outputs":[]},{"metadata":{"id":"9510DikeeW4E"},"cell_type":"markdown","source":"### sort predictions to have the same order as the submission\nThe submission ist sorted by image_name, but the dataset yielded a different order.\nTraverse the test dataset once again and capture the image_names. Then join this list of image_names with the predictions and sort by image_name.","execution_count":null},{"metadata":{"trusted":true,"id":"4dniYt-veW4E"},"cell_type":"code","source":"ds = get_dataset(files_test, CFG, augment=False, repeat=False, \n                 labeled=False, return_image_names=True)\n\nimage_names = np.array([img_name.numpy().decode(\"utf-8\") \n                        for img, img_name in iter(ds.unbatch())])","execution_count":null,"outputs":[]},{"metadata":{"id":"nXORjIuweW4K"},"cell_type":"markdown","source":"### write a submission file using the mean of all submodels","execution_count":null},{"metadata":{"trusted":true,"id":"dlK0jIkAeW4L","outputId":"c3cc0f12-5b6b-4c82-d893-cd724d3aefa8"},"cell_type":"code","source":"submission = pd.DataFrame(dict(\n    image_name = image_names,\n    target     = prob2))\n\nsubmission = submission.sort_values('image_name') \nsubmission.to_csv('submission_models_blended.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"id":"6tbR-7RUeW4N"},"cell_type":"code","source":"np.mean(probs[:,:,0], axis=0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"id":"G_DBPnkLeW4P"},"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}