{"cells":[{"metadata":{},"cell_type":"markdown","source":"You can get the results using Tensorflow or PyTorch, don't take my word for it, see it for yourself.\n\nTo make sure each model has a same input pipeline, I used tf.data.dataset to fetch data for the Pytorch model as well, bit sacrilegious I admit.\nThe only different between to two implementations, is the external Efficientnet libary.\n\nForked from: @cdeotte's https://www.kaggle.com/cdeotte/triple-stratified-kfold-with-tfrecords","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install -q efficientnet >> /dev/null","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import os, random, re, math, time\nrandom.seed(a=42)\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import KFold\nfrom sklearn.metrics import roc_auc_score\n\nfrom glob import glob\nfrom tqdm import tqdm\n\nimport tensorflow as tf\nimport tensorflow.keras.backend as K\n\nfrom tensorflow.keras.mixed_precision import experimental as mixed_precision\n\ngpus = tf.config.experimental.list_physical_devices('GPU')\ntry:\n    for gpu in gpus:\n        tf.config.experimental.set_memory_growth(gpu, True)\nexcept RuntimeError as e:\n    print(e)\n\nCFG = dict(\n    batch_size        =  32,\n    read_size         = 256, \n    crop_size         = 235, \n    net_size          = 224, \n    \n    LR                =   1e-4,\n    epochs            =  30,\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    tta_steps = 15,\n    \n    es_patience = 4,\n    \n)\n\n\nGCS_PATH = f'../input//melanoma-{CFG[\"read_size\"]}x{CFG[\"read_size\"]}'\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')))\n\nmalig_files = sorted(glob(f'../input/malignant-v2-{CFG[\"read_size\"]}x{CFG[\"read_size\"]}/*.tfrec'))\nmalig_files = malig_files[15:]\n\nfiles_train = np.concatenate([files_train, malig_files])\n    ","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    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    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])\n\ndef 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'], example['image_name']\n\n\ndef read_unlabeled_tfrecord(example):\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'], 0, example['image_name']\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 get_dataset(files, cfg, augment = False, shuffle = False, \n                labeled=True):\n    AUTO     = tf.data.experimental.AUTOTUNE\n    ds = tf.data.TFRecordDataset(files, num_parallel_reads=AUTO)\n    ds = ds.cache()\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), \n                    num_parallel_calls=AUTO)      \n    \n    ds = ds.map(lambda img, label, fn: (prepare_image(img, augment=augment, cfg=cfg), \n                                               label, fn), \n                num_parallel_calls=AUTO)\n    \n    ds = ds.batch(cfg['batch_size'])\n    ds = ds.prefetch(AUTO)\n    return ds","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#tf\nimport efficientnet.tfkeras as efn\ndef 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\n    constructor = getattr(efn, f'EfficientNetB0')\n    x = constructor(include_top=False, weights='imagenet', \n                    input_shape=(cfg['net_size'], cfg['net_size'], 3), \n                    pooling='avg')(dummy)\n    x = tf.keras.layers.Dense(1, activation='sigmoid', dtype=tf.float32)(x)\n        \n    model = tf.keras.Model(model_input, x)\n    return model\n\ndef get_opt_loss_fn():\n    optimizer = tf.keras.optimizers.Adam(learning_rate=CFG[\"LR\"])\n    loss_object = tf.keras.losses.BinaryCrossentropy(from_logits=False)\n    return optimizer, loss_object\n\ndef get_train_fn():\n    @tf.function\n    def train_step(images, labels, model, optimizer, loss_object):\n        with tf.GradientTape() as tape:\n            predictions = model(images, training=True)\n            loss = loss_object(labels, predictions[:,0])\n        gradients = tape.gradient(loss, model.trainable_variables)\n        optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n        return loss\n    \n    return train_step\n\ndef get_test_fn():\n    @tf.function\n    def test_step(images, labels, model, loss_object):\n        predictions = model(images, training=False)\n        return loss_object(labels, predictions[:,0])\n    return test_step\n\ndef get_pred_fn():\n    @tf.function\n    def pred_step(images, model):\n        predictions = model(images, training=False)\n        return predictions\n    return pred_step","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fold_cv_scores = []\nsubmission_scores = []\n\nfolds = KFold(n_splits=5, shuffle = True, random_state = 42)\nfold_num = 0\nfor tr_idx, va_idx in folds.split(files_train):\n    print(f\"Starting fold: {fold_num}\")\n    no_imp = 0\n    CFG['batch_size'] = 32\n    checkpoint_filepath = f\"checkpoint_{fold_num}.h5\"\n    \n    files_train_tr = files_train[tr_idx]\n    files_train_va = files_train[va_idx]  \n    \n    ds_train     = get_dataset(files_train_tr, CFG, augment=True, shuffle=True)\n    ds_val     = get_dataset(files_train_va, CFG, augment=False, shuffle=False)\n    \n    \n    optimizer, loss_object = get_opt_loss_fn()\n    model = get_model(CFG)\n    train_fn = get_train_fn()\n    test_fn = get_test_fn()\n    pred_fn = get_pred_fn()\n    \n    bestLoss = float(\"inf\")\n    for e in range(CFG[\"epochs\"]):\n        trainLoss = 0\n        tk0 = tqdm(ds_train)\n        for idx, (x,y,_) in enumerate(tk0):\n            loss = train_fn(x, y, model, optimizer, loss_object)\n            trainLoss += loss.numpy()\n            tk0.set_postfix(loss=trainLoss/(idx+1))\n            \n        testLoss = 0\n        tk0 = tqdm(ds_val)\n        for idx, (x,y,_) in enumerate(tk0):\n            loss = test_fn(x, y, model, loss_object)\n            testLoss += loss.numpy()\n            tk0.set_postfix(loss=testLoss/(idx+1))\n            \n        testLoss /= idx\n        if testLoss < bestLoss:\n            no_imp = 0\n            bestLoss = testLoss\n            model.save_weights(checkpoint_filepath)\n        else:\n            no_imp += 1\n            if no_imp > CFG[\"es_patience\"]:\n                print(\"Early stopping..\")\n                break\n\n\n    model.load_weights(checkpoint_filepath)\n    \n    ##############################################################\n    CFG['batch_size'] = 256    \n    ds_valAug = get_dataset(files_train_va, CFG, augment=True)\n    ds_testAug = get_dataset(files_test, CFG, augment=True, labeled=False)\n    for t in range(CFG['tta_steps']):\n        ####EVAL FOLD\n        for idx, (x,y,fn) in enumerate(ds_valAug):\n            predictions = pred_fn(x, model)\n            for j in range(predictions.shape[0]):\n                fold_cv_scores.append([fold_num, \n                                       fn[j].numpy().decode(\"utf-8\"),\n                                        predictions[j,0].numpy(),\n                                        y[j].numpy()])\n        \n        ####INFER ON TEST\n        for idx, (x,y,fn) in enumerate(ds_testAug):\n            predictions = pred_fn(x, model)\n            for j in range(predictions.shape[0]):\n                submission_scores.append([fold_num, \n                                       fn[j].numpy().decode(\"utf-8\"),\n                                        predictions[j,0].numpy()])\n                \n    tf.compat.v1.reset_default_graph() \n    tf.keras.backend.clear_session()\n    \n    fold_num += 1\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_fold = pd.DataFrame(fold_cv_scores, columns=[\"Fold\", \"Filename\", \"Pred\", \"Label\"])\ndf_sub = pd.DataFrame(submission_scores, columns=[\"Fold\", \"Filename\", \"Pred\"])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_fold = df_fold.groupby([\"Filename\"]).mean().reset_index()\nprint(\"CV ROCAUC: \")\nprint(roc_auc_score(df_fold[\"Label\"], df_fold[\"Pred\"]))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_sub = df_sub.groupby([\"Filename\"]).mean().reset_index()\ndf_sub = df_sub[[\"Filename\", \"Pred\"]]\ndf_sub.columns=[\"image_name\", \"target\"]\ndf_sub.to_csv(\"submission.csv\", index=False)","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}