{"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_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# [RSNA Screening Mammography Breast Cancer Detection](https://www.kaggle.com/c/petfinder-pawpularity-score)\n> Find breast cancers in screening mammograms\n\n![](https://storage.googleapis.com/kaggle-competitions/kaggle/39272/logos/header.png?t=2022-11-28-17-29-35)","metadata":{}},{"cell_type":"markdown","source":"# Idea:\n* In this notebook will classify `breast cancer` from Mammography images. Intially, we'll use CNN models then we'll move towards Transformer models.\n* There is a huge **class-imbalance** between cancer and non-cancer class which makes it difficult for the model to learn properly. Moreover, cancer size could be from very small to very large, so there is also **pixel-imbalance** which makes the task even more difficult. There are couple of ways to handle imbalance ex: `WeightedLoss`, `FocalLoss`, `Upsample`. In our notebook we'll use both `FocalLoss` and `Upsample`.\n* We'll use **ROI: Regoin Of Interest** instead of whole image as most of the image contains no information (black). To avoid distortion we'll also use **Rectangule** image for training instead of Squares\n* As dataset is quite large we'll utilize `TPU-VM` aka `Local TPU` to speed up the training.\n* We'll use `cancer` column as target.\n* We'll use **CNN** model: EfficientNet for our training.\n* We won't use **Tabular** feature in this notebook.\n* **Wandb** is integrated hence we can use this notebook to track which experiemnt is peforming better.\n* We'll maximize the `pF1` score using **Threshold**\n","metadata":{}},{"cell_type":"markdown","source":"# Notebooks\n* Only Image:\n    * ROI:\n        * train: [RSNA-BCD: EfficientNet [TF][TPU-1VM][Train]](https://www.kaggle.com/code/awsaf49/rsna-bcd-efficientnet-tf-tpu-1vm-train)\n        * infer: [RSNA-BCD: EfficientNet [TF][TPU-1VM][Infer]](https://www.kaggle.com/code/awsaf49/rsna-bcd-efficientnet-tf-tpu-1vm-infer)\n    * NoROI + KerasCV: \n        * train: [RSNA-BCD: NoROI KerasCV [TF][Train]](https://www.kaggle.com/awsaf49/rsna-bcd-noroi-kerascv-tf-train/)\n        * infer: [RSNA-BCD: NoROI KerasCV [TF][Infer]](https://www.kaggle.com/awsaf49/rsna-bcd-noroi-kerascv-tf-infer/)\n* Dataset:\n    * ROI:\n        * [RSNA-BCD: ROI 1024x PNG Dataset](https://www.kaggle.com/datasets/awsaf49/rsna-bcd-roi-1024x-png-dataset)\n    * NoROI:\n        * [RSNA-BCD: 512 PNG v2 PNG Dataset](https://www.kaggle.com/datasets/awsaf49/rsnabcd-512-png-v2-dataset)","metadata":{}},{"cell_type":"markdown","source":"# Overview\n\n## ROI + Rectangle Image\n* This notebook will **ROI (Region Of Interest)** image instead of full image. ROI is extracted using `OpenCV` (binary + max contour).\n* This notebook will use **rectangle** image (width!=height) training to avoid distortion.\n\n## Upsample `Cancer`\n* Upsample the cancer data `10x` to reduce class_imbalance effect on loss\n\n## `TPU-VM` aka `Local TPU`\n* It doesn't require `GCS_PATH` like normaly `TPU`. So, for this, we don't have to make our dataset **public** anymore. \n* As datasets will be read from local path, it should speed up the first epoch (for normal `tpu` first epoch is quite slow).\n\n## Augmentations:\n* Random - Horizontal Flip\n* Random - Brightness, Contrast, Hue, Saturation\n* Coarse Dropout\n* MixUp - soon\n\n## WandB Integration:\n* You can track your training using **wandb**\n* It's very easy to compare model's performance using **wandb**.\n\n## `pF1` Maximization:\n* Use simple empirical method to attain best `threshold` for max `pF1`","metadata":{}},{"cell_type":"markdown","source":"# Update\n* `v8 - 08/12/202`:\n    * MixUp and CutMix added\n    * Save gradcam in local directory\n* `v9 - 09/12/2022`:\n    * Swap MixUp->CutMix to CutMix->MixUp\n    * Number of folds 4, (saves time also can't submit 5 folds in test due to timeout)\n* `v10 - 10/12/2022`:\n    * Moved from pydicom to dicomsdl\n* `v18` - `19/12/2022`:\n    * Integration of `EfficinetNetV2` through `keras_cv_attention_models` library\n* `v22` - `18/01/2023`:\n    * `WandbModelCheckpoint` and `WandbModelCheckpoint` are used now","metadata":{}},{"cell_type":"markdown","source":"# Install Libraries","metadata":{}},{"cell_type":"markdown","source":"## Install for `TPU VM v3-8`\nUsually these libraries come pre-installed for other accelerators but fo `tpu-vm` we need to install them manually. If you want to use rather `remote-TPU` or `GPU` or `CPU`, then comment out the following cell.","metadata":{}},{"cell_type":"code","source":"!pip install -q /lib/wheels/tensorflow-2.9.1-cp38-cp38-linux_x86_64.whl\n!pip install -q tensorflow-addons==0.18.0\n!pip install -q tensorflow-probability==0.17.0\n!pip install -q opencv-python-headless\n!pip install -q seaborn","metadata":{"_kg_hide-input":false,"_kg_hide-output":true,"execution":{"iopub.status.busy":"2022-12-19T15:19:50.799397Z","iopub.execute_input":"2022-12-19T15:19:50.800472Z","iopub.status.idle":"2022-12-19T15:21:08.672526Z","shell.execute_reply.started":"2022-12-19T15:19:50.800379Z","shell.execute_reply":"2022-12-19T15:21:08.671547Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Install Custom Libraries","metadata":{}},{"cell_type":"code","source":"!pip install -q keras-cv-attention-models\n!pip install -qU wandb\n!pip install -qU scikit-learn","metadata":{"_kg_hide-output":true,"_kg_hide-input":false,"execution":{"iopub.status.busy":"2022-12-19T15:21:35.975617Z","iopub.execute_input":"2022-12-19T15:21:35.976343Z","iopub.status.idle":"2022-12-19T15:21:54.145832Z","shell.execute_reply.started":"2022-12-19T15:21:35.976309Z","shell.execute_reply":"2022-12-19T15:21:54.144921Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Import Libraries","metadata":{}},{"cell_type":"code","source":"import os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'  # to avoid too many logging messages\nimport pandas as pd, numpy as np, random, shutil\nimport tensorflow as tf, re, math\nimport tensorflow.keras.backend as K\nimport sklearn\nimport matplotlib.pyplot as plt\nimport tensorflow_addons as tfa\nimport tensorflow_probability as tfp\nimport wandb\nimport yaml\n\nfrom IPython import display as ipd\nfrom glob import glob\nfrom tqdm import tqdm\nfrom sklearn.model_selection import KFold, StratifiedKFold, GroupKFold, StratifiedGroupKFold\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.utils.class_weight import compute_class_weight","metadata":{"execution":{"iopub.status.busy":"2022-12-19T15:24:29.517225Z","iopub.execute_input":"2022-12-19T15:24:29.518054Z","iopub.status.idle":"2022-12-19T15:24:29.524912Z","shell.execute_reply.started":"2022-12-19T15:24:29.518016Z","shell.execute_reply":"2022-12-19T15:24:29.524104Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Version Check","metadata":{}},{"cell_type":"code","source":"print('np:', np.__version__)\nprint('pd:', pd.__version__)\nprint('sklearn:', sklearn.__version__)\nprint('tf:',tf.__version__)\nprint('tfp:', tfp.__version__)\nprint('tfa:', tfa.__version__)\nprint('w&b:', wandb.__version__)","metadata":{"execution":{"iopub.status.busy":"2022-12-19T15:24:31.670962Z","iopub.execute_input":"2022-12-19T15:24:31.671811Z","iopub.status.idle":"2022-12-19T15:24:31.677802Z","shell.execute_reply.started":"2022-12-19T15:24:31.671772Z","shell.execute_reply":"2022-12-19T15:24:31.676906Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Wandb","metadata":{}},{"cell_type":"markdown","source":"<img src=\"https://camo.githubusercontent.com/dd842f7b0be57140e68b2ab9cb007992acd131c48284eaf6b1aca758bfea358b/68747470733a2f2f692e696d6775722e636f6d2f52557469567a482e706e67\" width=\"400\" alt=\"Weights & Biases\" />\n\nWeights & Biases (W&B) is MLOps platform for tracking our experiemnts. We can use it to Build better models faster with experiment tracking, dataset versioning, and model management\n\nSome of the cool features of **W&B**:\n\n* Track, compare, and visualize ML experiments\n* Get live metrics, terminal logs, and system stats streamed to the centralized dashboard.\n* Explain how your model works, show graphs of how model versions improved, discuss bugs, and demonstrate progress towards milestones.\n\n> **Note:** `kaggle_secrets` has not been added to `TPU-VM` yet, so run anonymously then go to the dashbaord and simply `claim` the run.","metadata":{}},{"cell_type":"code","source":"import wandb\n\ntry:\n    from kaggle_secrets import UserSecretsClient\n    user_secrets = UserSecretsClient()\n    api_key = user_secrets.get_secret(\"WANDB\")\n\n    wandb.login(key=api_key)\n    anonymous = None\nexcept:\n    anonymous = \"must\"\n    print('To use your W&B account,\\nGo to Add-ons -> Secrets and provide your W&B access token. Use the Label name as WANDB. \\nGet your W&B access token from here: https://wandb.ai/authorize')","metadata":{"execution":{"iopub.status.busy":"2022-12-19T15:24:34.753439Z","iopub.execute_input":"2022-12-19T15:24:34.75416Z","iopub.status.idle":"2022-12-19T15:24:34.760327Z","shell.execute_reply.started":"2022-12-19T15:24:34.754127Z","shell.execute_reply":"2022-12-19T15:24:34.759599Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Configuration","metadata":{}},{"cell_type":"code","source":"class CFG:\n    wandb         = True\n    competition   = 'rsna-bcd' \n    _wandb_kernel = 'awsaf49'\n    debug         = False\n    comment       = 'EfficientNetV1B4-1024x512-roi-up=10-lr4-focal-vflip-wb'\n    exp_name      = 'roi-v2-fix' # name of the experiment, folds will be grouped using 'exp_name'\n    \n    # use verbose=0 for silent, vebose=1 for interactive,\n    verbose      = 1\n    display_plot = True\n\n    # device\n    device = \"TPU-VM\" #or \"GPU\"\n\n    model_name = 'EfficientNetV1B4'\n\n    # seed for data-split, layer init, augs\n    seed = 42\n\n    # number of folds for data-split\n    folds = 5\n    \n    # which folds to train\n    selected_folds = [0, 1, 2]\n\n    # size of the image\n    img_size = [1024, 512]\n#     eq_dim = np.prod(img_size)**0.5\n\n    # batch_size and epochs\n    batch_size = 28\n    epochs = 8\n    \n    # upsample\n    upsample = 10\n\n    # loss\n    loss      = 'Focal'  # BCE, Focal\n    use_cw    = False  # use class weight or not\n    \n    # optimizer\n    optimizer = 'Adam'\n\n    # augmentation\n    augment   = True\n\n    # scale-shift-rotate-shear\n    transform = 0.90  # transform prob\n    fill_mode = 'constant'\n    rot    = 2.0\n    shr    = 2.0\n    hzoom  = 50.0\n    wzoom  = 50.0\n    hshift = 10.0\n    wshift = 10.0\n\n    # flip\n    hflip = True\n    vflip = True\n\n    # clip\n    clip = False\n\n    # lr-scheduler\n    scheduler   = 'exp' # cosine\n\n    # dropout\n    drop_prob   = 0.6\n    drop_cnt    = 10\n    drop_size   = 0.08\n    \n    # cut-mix-up\n    mixup_prob = 0.0\n    mixup_alpha = 0.5\n    \n    cutmix_prob = 0.0\n    cutmix_alpha = 2.5\n\n    # pixel-augment\n    pixel_aug = 0.90  # prob of pixel_aug\n    sat  = [0.7, 1.3]\n    cont = [0.8, 1.2]\n    bri  = 0.15\n    hue  = 0.05\n\n    # test-time augs\n    tta = 1\n    \n    # target column\n    target_col  = ['cancer']","metadata":{"execution":{"iopub.status.busy":"2022-12-19T15:29:53.100166Z","iopub.execute_input":"2022-12-19T15:29:53.101307Z","iopub.status.idle":"2022-12-19T15:29:53.112265Z","shell.execute_reply.started":"2022-12-19T15:29:53.101266Z","shell.execute_reply":"2022-12-19T15:29:53.111049Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Reproducibility","metadata":{}},{"cell_type":"code","source":"def seeding(SEED):\n    np.random.seed(SEED)\n    random.seed(SEED)\n    os.environ['PYTHONHASHSEED'] = str(SEED)\n#     os.environ['TF_CUDNN_DETERMINISTIC'] = str(SEED)\n    tf.random.set_seed(SEED)\n    print('seeding done!!!')\nseeding(CFG.seed)","metadata":{"execution":{"iopub.status.busy":"2022-12-19T15:24:39.889399Z","iopub.execute_input":"2022-12-19T15:24:39.890273Z","iopub.status.idle":"2022-12-19T15:24:39.896034Z","shell.execute_reply.started":"2022-12-19T15:24:39.89024Z","shell.execute_reply":"2022-12-19T15:24:39.895242Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Device Configs\nThis notebook is compatible for **remote-tpu**, **local-tpu**, **multi-gpu** and **single-gpu**. Simple change to `device=\"TPU\"` for **remote-tpu** and `device=\"TPU-VM\"` for **local-tpu** and finally, `device=\"GPU\"` for single or multi-gpu.","metadata":{}},{"cell_type":"code","source":"if \"TPU\" in CFG.device:\n    tpu = 'local' if CFG.device=='TPU-VM' else None\n    print(\"connecting to TPU...\")\n    try:\n        tpu = tf.distribute.cluster_resolver.TPUClusterResolver.connect(tpu=tpu)\n        strategy = tf.distribute.TPUStrategy(tpu)\n    except:\n        CFG.device = \"GPU\"\n        \nif CFG.device == \"GPU\"  or CFG.device==\"CPU\":\n    ngpu = len(tf.config.experimental.list_physical_devices('GPU'))\n    if ngpu>1:\n        print(\"Using multi GPU\")\n        strategy = tf.distribute.MirroredStrategy()\n    elif ngpu==1:\n        print(\"Using single GPU\")\n        strategy = tf.distribute.get_strategy()\n    else:\n        print(\"Using CPU\")\n        strategy = tf.distribute.get_strategy()\n        CFG.device = \"CPU\"\n\nif CFG.device == \"GPU\":\n    print(\"Num GPUs Available: \", ngpu)\n    \n\nAUTO     = tf.data.experimental.AUTOTUNE\nREPLICAS = strategy.num_replicas_in_sync\nprint(f'REPLICAS: {REPLICAS}')","metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"execution":{"iopub.status.busy":"2022-12-19T15:24:42.416303Z","iopub.execute_input":"2022-12-19T15:24:42.41725Z","iopub.status.idle":"2022-12-19T15:24:54.565803Z","shell.execute_reply.started":"2022-12-19T15:24:42.417211Z","shell.execute_reply":"2022-12-19T15:24:54.564863Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# GCS Path for TPU\n* Remote-TPU requires **GCS** path. Luckily Kaggle Provides that for us :)\n* Local-TPU aka TPU-VM doesn't need GCS path =)","metadata":{}},{"cell_type":"code","source":"BASE_PATH = f'/kaggle/input/rsna-bcd-roi-{CFG.img_size[0]}x{CFG.img_size[1]}-png-v2-dataset'\n\nif CFG.device==\"TPU\":\n    from kaggle_datasets import KaggleDatasets\n    GCS_PATH = KaggleDatasets().get_gcs_path(BASE_PATH.split('/')[-1])","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-12-19T15:25:13.340017Z","iopub.execute_input":"2022-12-19T15:25:13.341015Z","iopub.status.idle":"2022-12-19T15:25:13.345648Z","shell.execute_reply.started":"2022-12-19T15:25:13.340977Z","shell.execute_reply":"2022-12-19T15:25:13.344722Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Meta Data","metadata":{}},{"cell_type":"code","source":"# use gcs_path for remote-tpu\nif CFG.device==\"TPU\":\n    BASE_PATH = GCS_PATH\n\n# train\ndf = pd.read_csv(f'{BASE_PATH}/train.csv')\ndf['image_path'] = f'{BASE_PATH}/train_images'\\\n                    + '/' + df.patient_id.astype(str)\\\n                    + '/' + df.image_id.astype(str)\\\n                    + '.png'\nprint('Train:')\ndisplay(df.head(2))\n\n# test\ntest_df = pd.read_csv(f'{BASE_PATH}/test.csv')\ntest_df['image_path'] = f'{BASE_PATH}/test_images'\\\n                    + '/' + test_df.patient_id.astype(str)\\\n                    + '/' + test_df.image_id.astype(str)\\\n                    + '.png'\nprint('\\nTest:')\ndisplay(test_df.head(2))","metadata":{"execution":{"iopub.status.busy":"2022-12-19T15:25:17.070547Z","iopub.execute_input":"2022-12-19T15:25:17.071313Z","iopub.status.idle":"2022-12-19T15:25:17.385272Z","shell.execute_reply.started":"2022-12-19T15:25:17.071276Z","shell.execute_reply":"2022-12-19T15:25:17.38429Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Check If Data Exist?","metadata":{}},{"cell_type":"code","source":"tf.io.gfile.exists(df.image_path.iloc[0]), tf.io.gfile.exists(test_df.image_path.iloc[0])","metadata":{"execution":{"iopub.status.busy":"2022-12-19T15:25:22.289081Z","iopub.execute_input":"2022-12-19T15:25:22.289825Z","iopub.status.idle":"2022-12-19T15:25:22.31254Z","shell.execute_reply.started":"2022-12-19T15:25:22.289787Z","shell.execute_reply":"2022-12-19T15:25:22.311619Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Train-Test Ditribution","metadata":{}},{"cell_type":"code","source":"print('train_files:',df.shape[0])\nprint('test_files:',test_df.shape[0])","metadata":{"execution":{"iopub.status.busy":"2022-12-19T15:25:25.241991Z","iopub.execute_input":"2022-12-19T15:25:25.242899Z","iopub.status.idle":"2022-12-19T15:25:25.247335Z","shell.execute_reply.started":"2022-12-19T15:25:25.242863Z","shell.execute_reply":"2022-12-19T15:25:25.246503Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Data Split\n* Data is splited while stratifying, 'laterality', 'view', 'age','cancer', 'biopsy', 'invasive', 'BIRADS', 'implant', 'density','machine_id', 'difficult_negative_case','cancer'.\n* To avoid leakage, data is also split keeping images from same patient in either train or valid not in both.\n* `StratifiedGroupKFold` does the both job **stratifying** and **group** split.\n\n","metadata":{}},{"cell_type":"code","source":"num_bins = 5\ndf[\"age_bin\"] = pd.cut(df['age'].values.reshape(-1), bins=num_bins, labels=False)\n\nstrat_cols = [\n    'laterality', 'view', 'biopsy','invasive', 'BIRADS', 'age_bin',\n    'implant', 'density','machine_id', 'difficult_negative_case',\n    'cancer',\n]\n\ndf['stratify'] = ''\nfor col in strat_cols:\n    df['stratify'] += df[col].astype(str)\n\nskf = StratifiedGroupKFold(n_splits=CFG.folds, shuffle=True, random_state=CFG.seed)\nfor fold, (train_idx, val_idx) in enumerate(skf.split(df, df['stratify'], df[\"patient_id\"])):\n    df.loc[val_idx, 'fold'] = fold\ndisplay(df.groupby(['fold', \"cancer\"]).size())","metadata":{"execution":{"iopub.status.busy":"2022-12-19T15:25:28.004313Z","iopub.execute_input":"2022-12-19T15:25:28.004996Z","iopub.status.idle":"2022-12-19T15:25:36.545213Z","shell.execute_reply.started":"2022-12-19T15:25:28.004963Z","shell.execute_reply":"2022-12-19T15:25:36.544318Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Data Augmentation\nUsed simple augmentations, some of them may hurt the model.\n* RandomFlip (Left-Right)\n* No Rotation\n* RandomBrightness\n* RndomContrast\n* Shear\n* Zoom\n* Coarsee Dropout/Cutout","metadata":{}},{"cell_type":"code","source":"def get_mat(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\n    return  K.dot(shear_matrix,K.dot(zoom_matrix, shift_matrix)) #K.dot(K.dot(rotation_matrix, shear_matrix), K.dot(zoom_matrix, shift_matrix))                  \n\ndef transform(image, DIM=CFG.img_size):#[rot,shr,h_zoom,w_zoom,h_shift,w_shift]):\n    if DIM[0]>DIM[1]:\n        diff  = (DIM[0]-DIM[1])\n        pad   = [diff//2, diff//2 + diff%2]\n        image = tf.pad(image, [[0, 0], [pad[0], pad[1]],[0, 0]])\n        NEW_DIM = DIM[0]\n    elif DIM[0]<DIM[1]:\n        diff  = (DIM[1]-DIM[0])\n        pad   = [diff//2, diff//2 + diff%2]\n        image = tf.pad(image, [[pad[0], pad[1]], [0, 0],[0, 0]])\n        NEW_DIM = DIM[1]\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    transformation_matrix=tf.linalg.inv(get_mat(shr,h_zoom,w_zoom,h_shift,w_shift))\n    \n    flat_tensor=tfa.image.transform_ops.matrices_to_flat_transforms(transformation_matrix)\n    \n    image=tfa.image.transform(image,flat_tensor, fill_mode=CFG.fill_mode)\n    \n    rotation = math.pi * rot / 180.\n    \n    image=tfa.image.rotate(image,-rotation, fill_mode=CFG.fill_mode)\n    \n    if DIM[0]>DIM[1]:\n        image=tf.reshape(image, [NEW_DIM, NEW_DIM,3])\n        image = image[:, pad[0]:-pad[1],:]\n    elif DIM[1]>DIM[0]:\n        image=tf.reshape(image, [NEW_DIM, NEW_DIM,3])\n        image = image[pad[0]:-pad[1],:,:]\n    image = tf.reshape(image, [*DIM, 3])    \n    return image\n\ndef dropout(image,DIM=CFG.img_size, PROBABILITY = 0.6, CT = 5, SZ = 0.1):\n    # input image - is one image of size [dim,dim,3] not a batch of [b,dim,dim,3]\n    # output - image with CT squares of side size SZ*DIM removed\n    \n    # DO DROPOUT WITH PROBABILITY DEFINED ABOVE\n    P = tf.cast( tf.random.uniform([],0,1)<PROBABILITY, tf.int32)\n    if (P==0)|(CT==0)|(SZ==0): \n        return image\n    \n    for k in range(CT):\n        # CHOOSE RANDOM LOCATION\n        x = tf.cast( tf.random.uniform([],0,DIM[1]),tf.int32)\n        y = tf.cast( tf.random.uniform([],0,DIM[0]),tf.int32)\n        # COMPUTE SQUARE \n        WIDTH = tf.cast( SZ*min(DIM),tf.int32) * P\n        ya = tf.math.maximum(0,y-WIDTH//2)\n        yb = tf.math.minimum(DIM[0],y+WIDTH//2)\n        xa = tf.math.maximum(0,x-WIDTH//2)\n        xb = tf.math.minimum(DIM[1],x+WIDTH//2)\n        # DROPOUT IMAGE\n        one = image[ya:yb,0:xa,:]\n        two = tf.zeros([yb-ya,xb-xa,3], dtype = image.dtype) \n        three = image[ya:yb,xb:DIM[1],:]\n        middle = tf.concat([one,two,three],axis=1)\n        image = tf.concat([image[0:ya,:,:],middle,image[yb:DIM[0],:,:]],axis=0)\n        image = tf.reshape(image,[*DIM,3])\n\n#     image = tf.reshape(image,[*DIM,3])\n    return image","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-12-19T15:26:07.561608Z","iopub.execute_input":"2022-12-19T15:26:07.562341Z","iopub.status.idle":"2022-12-19T15:26:07.594394Z","shell.execute_reply.started":"2022-12-19T15:26:07.562307Z","shell.execute_reply":"2022-12-19T15:26:07.593275Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## CutMixUp","metadata":{}},{"cell_type":"code","source":"def random_int(shape=[], minval=0, maxval=1):\n    return tf.random.uniform(\n        shape=shape, minval=minval, maxval=maxval, dtype=tf.int32)\n\n\ndef random_float(shape=[], minval=0.0, maxval=1.0):\n    rnd = tf.random.uniform(\n        shape=shape, minval=minval, maxval=maxval, dtype=tf.float32)\n    return rnd\n\n# mixup\ndef get_mixup(alpha=0.2, prob=0.5):\n    @tf.function\n    def mixup(images, labels, alpha=alpha, prob=prob):\n        if random_float() > prob:\n            return images, labels\n\n        image_shape = tf.shape(images)\n        label_shape = tf.shape(labels)\n\n        beta = tfp.distributions.Beta(alpha, alpha)\n        lam = beta.sample(1)[0]\n\n        images = lam * images + (1.0 - lam) * tf.roll(images, shift=1, axis=0)\n        labels = lam * labels + (1.0 - lam) * tf.roll(labels, shift=1, axis=0)\n\n        images = tf.reshape(images, image_shape)\n        labels = tf.reshape(labels, label_shape)\n        return images, labels\n    return mixup\n\n# cutmix\ndef get_cutmix(alpha, prob=0.5):\n    @tf.function\n    def cutmix(images, labels, alpha=alpha, prob=prob):\n        if random_float() > prob:\n            return images, labels\n        image_shape = tf.shape(images)\n        label_shape = tf.shape(labels)\n        \n        W = tf.cast(image_shape[2], tf.int32)\n        H = tf.cast(image_shape[1], tf.int32)\n\n        beta = tfp.distributions.Beta(alpha, alpha)\n        lam = beta.sample(1)[0]\n\n        images_rolled = tf.roll(images, shift=1, axis=0)\n        labels_rolled = tf.roll(labels, shift=1, axis=0)\n\n        r_x = random_int([], minval=0, maxval=W)\n        r_y = random_int([], minval=0, maxval=H)\n        r = 0.5 * tf.math.sqrt(1.0 - lam)\n        r_w_half = tf.cast(r * tf.cast(W, tf.float32), tf.int32)\n        r_h_half = tf.cast(r * tf.cast(H, tf.float32), tf.int32)\n\n        x1 = tf.cast(tf.clip_by_value(r_x - r_w_half, 0, W), tf.int32)\n        x2 = tf.cast(tf.clip_by_value(r_x + r_w_half, 0, W), tf.int32)\n        y1 = tf.cast(tf.clip_by_value(r_y - r_h_half, 0, H), tf.int32)\n        y2 = tf.cast(tf.clip_by_value(r_y + r_h_half, 0, H), tf.int32)\n\n        # outer-pad patch -> [0, 0, 1, 1, 0, 0]\n        patch1 = images[:, y1:y2, x1:x2, :]  # [batch, height, width, channel]\n        patch1 = tf.pad(\n            patch1, [[0, 0], [y1, H - y2], [x1, W - x2], [0, 0]])  # outer-pad\n\n        # inner-pad patch -> [1, 1, 0, 0, 1, 1]\n        patch2 = images_rolled[:, y1:y2, x1:x2, :]\n        patch2 = tf.pad(\n            patch2, [[0, 0], [y1, H - y2], [x1, W - x2], [0, 0]])  # outer-pad\n        patch2 = images_rolled - patch2  # inner-pad = img - outer-pad\n\n        images = patch1 + patch2  # cutmix img\n\n        lam = tf.cast((1.0 - (x2 - x1) * (y2 - y1) / (W * H)), tf.float32)  # no H as (y1 - y2)/H = 1\n        labels = lam * labels + (1.0 - lam) * labels_rolled  # cutmix label\n\n        images = tf.reshape(images, image_shape)\n        labels = tf.reshape(labels, label_shape)\n\n        return images, labels\n\n    return cutmix","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-12-19T15:26:08.523813Z","iopub.execute_input":"2022-12-19T15:26:08.524609Z","iopub.status.idle":"2022-12-19T15:26:08.550783Z","shell.execute_reply.started":"2022-12-19T15:26:08.524572Z","shell.execute_reply":"2022-12-19T15:26:08.549698Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Data Pipeline\n* Reads the raw file and then decodes it to tf.Tensor\n* Resizes the image in desired size\n* Chages the datatype to **float32**\n* Caches the Data for boosting up the speed.\n* Uses Augmentations to reduce overfitting and make model more robust.\n* Finally, splits the data into batches.\n","metadata":{}},{"cell_type":"code","source":"def build_decoder(with_labels=True, target_size=CFG.img_size, ext='png'):\n    def decode(path):\n        file_bytes = tf.io.read_file(path)\n        if ext == 'png':\n            img = tf.image.decode_png(file_bytes, channels=3)\n        elif ext in ['jpg', 'jpeg']:\n            img = tf.image.decode_jpeg(file_bytes, channels=3)\n        else:\n            raise ValueError(\"Image extension not supported\")\n\n        img = tf.image.resize(img, target_size, method='bilinear')\n        img = tf.cast(img, tf.float32) / 255.0\n        img = tf.reshape(img, [*target_size, 3])\n\n        return img\n    \n    def decode_with_labels(path, label):\n        return decode(path), tf.cast(label, tf.float32)\n    \n    return decode_with_labels if with_labels else decode\n\n\ndef build_augmenter(with_labels=True, dim=CFG.img_size):\n    def augment(img, dim=dim):\n        if random_float() < CFG.transform:\n            img = transform(img,DIM=dim)\n        img = tf.image.random_flip_left_right(img) if CFG.hflip else img\n        img = tf.image.random_flip_up_down(img) if CFG.vflip else img\n        if random_float() < CFG.pixel_aug:\n            img = tf.image.random_hue(img, CFG.hue)\n            img = tf.image.random_saturation(img, CFG.sat[0], CFG.sat[1])\n            img = tf.image.random_contrast(img, CFG.cont[0], CFG.cont[1])\n            img = tf.image.random_brightness(img, CFG.bri)\n        img = tf.clip_by_value(img, 0, 1)  if CFG.clip else img         \n        img = tf.reshape(img, [*dim, 3])\n        return img\n    \n    def augment_with_labels(img, label):    \n        return augment(img), label\n    \n    return augment_with_labels if with_labels else augment\n\n\ndef build_dataset(paths, labels=None, batch_size=32, cache=True,\n                  decode_fn=None, augment_fn=None,\n                  augment=True, repeat=True, shuffle=1024, \n                  cache_dir=\"\", drop_remainder=False):\n    if cache_dir != \"\" and cache is True:\n        os.makedirs(cache_dir, exist_ok=True)\n    \n    if decode_fn is None:\n        decode_fn = build_decoder(labels is not None)\n    \n    if augment_fn is None:\n        augment_fn = build_augmenter(labels is not None)\n    \n    AUTO = tf.data.experimental.AUTOTUNE\n    slices = paths if labels is None else (paths, labels)\n    \n    ds = tf.data.Dataset.from_tensor_slices(slices)\n    ds = ds.map(decode_fn, num_parallel_calls=AUTO)\n    ds = ds.cache(cache_dir) if cache else ds\n    ds = ds.repeat() if repeat else ds\n    if shuffle: \n        ds = ds.shuffle(shuffle, seed=CFG.seed)\n        opt = tf.data.Options()\n        opt.experimental_deterministic = False\n        ds = ds.with_options(opt)\n    ds = ds.map(augment_fn, num_parallel_calls=AUTO) if augment else ds\n    if augment and labels is not None:\n        ds = ds.map(lambda img, label: (dropout(img, \n                                               DIM=CFG.img_size, \n                                               PROBABILITY=CFG.drop_prob, \n                                               CT=CFG.drop_cnt,\n                                               SZ=CFG.drop_size), label),num_parallel_calls=AUTO)\n    ds = ds.batch(batch_size, drop_remainder=drop_remainder)\n    if augment and labels is not None:\n        if CFG.cutmix_prob:\n            ds = ds.map(get_cutmix(alpha=CFG.cutmix_alpha,prob=CFG.cutmix_prob),num_parallel_calls=AUTO)\n        if CFG.mixup_prob:\n            ds = ds.map(get_mixup(alpha=CFG.mixup_alpha,prob=CFG.mixup_prob),num_parallel_calls=AUTO)\n    ds = ds.prefetch(AUTO)\n    return ds","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-12-19T15:26:10.504397Z","iopub.execute_input":"2022-12-19T15:26:10.505168Z","iopub.status.idle":"2022-12-19T15:26:10.528846Z","shell.execute_reply.started":"2022-12-19T15:26:10.505132Z","shell.execute_reply":"2022-12-19T15:26:10.52797Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Visualization\n* Check if augmentation is working properly or not.","metadata":{}},{"cell_type":"code","source":"def display_batch(batch, size=2):\n    if isinstance(batch, tuple):\n        imgs, tars = batch\n    else:\n        imgs = batch\n        tars = None\n    tars = tars.numpy().squeeze()\n    plt.figure(figsize=(size*2, 10))\n    for img_idx in range(size):\n        plt.subplot(1, size, img_idx+1)\n        if tars is not None:\n            plt.title(f'{CFG.target_col[0]}: {tars[img_idx]:0.3f}', fontsize=10)\n        plt.imshow(imgs[img_idx,:, :, :])\n        plt.xticks([]); plt.yticks([])\n    plt.tight_layout()\n    plt.show() ","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-12-19T15:26:11.377131Z","iopub.execute_input":"2022-12-19T15:26:11.377934Z","iopub.status.idle":"2022-12-19T15:26:11.385021Z","shell.execute_reply.started":"2022-12-19T15:26:11.3779Z","shell.execute_reply":"2022-12-19T15:26:11.384042Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Generate Image","metadata":{}},{"cell_type":"code","source":"fold = 0\nfold_df = df.groupby('cancer').head(16)\npaths  = fold_df.image_path.tolist()\nlabels = fold_df[CFG.target_col].values\nds = build_dataset(paths, labels, cache=False, batch_size=32,\n                   repeat=True, shuffle=True, augment=False)\nds = ds.unbatch().batch(20)\nbatch = next(iter(ds))","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-12-19T15:26:11.99323Z","iopub.execute_input":"2022-12-19T15:26:11.994071Z","iopub.status.idle":"2022-12-19T15:26:12.229017Z","shell.execute_reply.started":"2022-12-19T15:26:11.994038Z","shell.execute_reply":"2022-12-19T15:26:12.22794Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## No-Augmentation","metadata":{}},{"cell_type":"code","source":"display_batch(batch, 5);","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-12-19T15:26:12.649537Z","iopub.execute_input":"2022-12-19T15:26:12.650347Z","iopub.status.idle":"2022-12-19T15:26:13.356295Z","shell.execute_reply.started":"2022-12-19T15:26:12.650313Z","shell.execute_reply":"2022-12-19T15:26:13.355316Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## MixUp","metadata":{}},{"cell_type":"code","source":"mixup = get_mixup(alpha=2.5, prob=1)\nmimgs, mtars = mixup(batch[0], batch[1])\ndisplay_batch((mimgs, mtars), 5);","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-12-19T15:26:13.357673Z","iopub.execute_input":"2022-12-19T15:26:13.357954Z","iopub.status.idle":"2022-12-19T15:26:14.845929Z","shell.execute_reply.started":"2022-12-19T15:26:13.35793Z","shell.execute_reply":"2022-12-19T15:26:14.844809Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## CutMix","metadata":{}},{"cell_type":"code","source":"cutmix = get_cutmix(alpha=2.5, prob=1)\ncimgs, ctars = cutmix(batch[0], batch[1])\ndisplay_batch((cimgs, ctars), 5);","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-12-19T15:26:14.847411Z","iopub.execute_input":"2022-12-19T15:26:14.84771Z","iopub.status.idle":"2022-12-19T15:26:16.556888Z","shell.execute_reply.started":"2022-12-19T15:26:14.847685Z","shell.execute_reply":"2022-12-19T15:26:16.555697Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Dropout","metadata":{}},{"cell_type":"code","source":"dimgs = tf.map_fn(lambda img: dropout(img,\n                DIM=CFG.img_size, \n                PROBABILITY=1.0, \n                CT=10,\n                SZ=0.08), batch[0])\ndtars = batch[1]\ndisplay_batch((dimgs, dtars), 5);","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-12-19T15:26:16.558514Z","iopub.execute_input":"2022-12-19T15:26:16.558816Z","iopub.status.idle":"2022-12-19T15:26:18.712004Z","shell.execute_reply.started":"2022-12-19T15:26:16.55879Z","shell.execute_reply":"2022-12-19T15:26:18.710852Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Affine Transform","metadata":{}},{"cell_type":"code","source":"timgs = tf.map_fn(lambda img: transform(img,DIM=CFG.img_size), batch[0])\nttars = batch[1]\ndisplay_batch((timgs, ttars), 5);","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-12-19T15:26:24.225529Z","iopub.execute_input":"2022-12-19T15:26:24.226549Z","iopub.status.idle":"2022-12-19T15:26:27.321998Z","shell.execute_reply.started":"2022-12-19T15:26:24.226501Z","shell.execute_reply":"2022-12-19T15:26:27.320784Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Loss Function\n## BCE\nLoss Function for this notebook is **BCE: Binary Crossentropy** or **Focal** as the task is **binary classification**\n\n$$\\textrm{BCE}  = -\\frac{1}{N} \\sum_{i=1}^{N} y_i \\cdot log(\\hat{y}_i) + (1 - y_i) \\cdot log(1 - \\hat{y}_i)$$\n\nwhere $\\hat{y}_i$ is the **predicted** value and $y_i$ is the **original** value for each instance $i$.\n\n## Focal\n$$\\textrm{FL} = -\\alpha_{t}(1 - p_{t})^{\\gamma}\\log{p_{t}}$$\n\n$\\gamma$ controls the shape of the curve. The higher the value of $\\gamma$, the lower the loss for well-classified examples, so we could turn the attention of the model more towards ‘hard-to-classify examples. FL gives high weights to the rare class and small weights to the dominating or common class. These weights are referred to as $\\alpha$.\n\n\n## Code\n* `tf.keras.losses.BinaryCrossentropy`\n* `tfa.losses.SigmoidFocalCrossEntropy`","metadata":{}},{"cell_type":"markdown","source":"# Metric\nMetric for this competition is **probabilistic F1 score (pF1)**. This extension of the traditional F score accepts probabilities instead of binary classifications,\n\n$$\npF1=2\\frac{pPrecision⋅pRecall}{pPrecision+pRecall}\n$$\n\nWhere,\n$$\npPrecision=\\frac{pTP}{pTP+pFP}\n$$\n$$\npRecall=\\frac{pTP}{TP+FN}\n$$","metadata":{}},{"cell_type":"code","source":"# tensorflow\n\nclass pFBeta(tf.keras.metrics.Metric):\n    \"\"\"Compute overall probabilistic F-beta score.\"\"\"\n    def __init__(self, beta=1, epsilon=1e-5, name='pF1', **kwargs):\n        super().__init__(name=name, **kwargs)\n        self.beta = beta\n        self.epsilon = epsilon\n        self.pos = self.add_weight(name='pos', initializer='zeros')\n        self.ctp = self.add_weight(name='ctp', initializer='zeros')\n        self.cfp = self.add_weight(name='cfp', initializer='zeros')\n\n    def update_state(self, y_true, y_pred, sample_weight=None):\n        y_true = tf.cast(y_true, tf.float32)\n        y_pred = tf.clip_by_value(y_pred, 0, 1)\n        pos = tf.reduce_sum(y_true)\n        ctp = tf.reduce_sum(y_pred[y_true==1])\n        cfp = tf.reduce_sum(y_pred[y_true==0])\n        self.pos.assign_add(pos)\n        self.ctp.assign_add(ctp)\n        self.cfp.assign_add(cfp)\n\n    def result(self):\n        beta_squared = self.beta * self.beta\n        c_precision = self.ctp / (self.ctp + self.cfp + self.epsilon)\n        c_recall = self.ctp / (self.pos + self.epsilon)\n        result = (1 + beta_squared) * (c_precision * c_recall) / (beta_squared * c_precision + c_recall)\n        return tf.cond(c_precision > 0 and c_recall > 0, lambda: result, lambda: 0.0)\n\n\n# computes batch-wise pfbeta\ndef pfbeta_tf(labels, preds, beta=1):\n    eps = 1e-5\n    preds = tf.clip_by_value(preds, 0, 1)\n    y_true_count = tf.reduce_sum(labels)\n    ctp = tf.reduce_sum(preds[labels==1])\n    cfp = tf.reduce_sum(preds[labels==0])\n    beta_squared = beta * beta\n    c_precision = ctp / (ctp + cfp + eps)\n    c_recall = ctp / (y_true_count + eps)\n    if (c_precision > 0 and c_recall > 0):\n        result = (1 + beta_squared) * (c_precision * c_recall) / (beta_squared * c_precision + c_recall + eps)\n        return result\n    else:\n        return tf.constant(0.0, dtype=tf.float32)\n\n# finds best pf1 using thresholds\ndef pfbeta_thr(labels, preds):\n    thrs = tf.range(0, 1, 0.05)\n    best_score = tf.constant(0, dtype=tf.float32)\n    for thr in thrs:\n        score = pfbeta_tf(labels, tf.cast(preds>thr, tf.float32))\n        best_score = tf.cond(score > best_score, lambda: score, lambda: best_score)\n    return best_score\n\npfbeta_thr.__name__='pF1_thr'\n\n\n# numpy\ndef pfbeta(labels, preds, beta=1):\n    eps = 1e-5\n    preds = preds.clip(0, 1)\n    y_true_count = labels.sum()\n    ctp = preds[labels==1].sum()\n    cfp = preds[labels==0].sum()\n    beta_squared = beta * beta\n    c_precision = ctp / (ctp + cfp + eps)\n    c_recall = ctp / (y_true_count + eps)\n    if (c_precision > 0 and c_recall > 0):\n        result = (1 + beta_squared) * (c_precision * c_recall) / (beta_squared * c_precision + c_recall + eps)\n        return result\n    else:\n        return 0.0","metadata":{"execution":{"iopub.status.busy":"2022-12-19T15:26:35.85602Z","iopub.execute_input":"2022-12-19T15:26:35.85736Z","iopub.status.idle":"2022-12-19T15:26:35.873369Z","shell.execute_reply.started":"2022-12-19T15:26:35.857308Z","shell.execute_reply":"2022-12-19T15:26:35.872232Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Build Model","metadata":{}},{"cell_type":"code","source":"from keras_cv_attention_models import efficientnet\n\ndef build_model(model_name=CFG.model_name,\n                loss_name=CFG.loss,\n                dim=CFG.img_size,\n                compile_model=True,\n                include_top=False):         \n    base = getattr(efficientnet, model_name)(input_shape=(*dim,3),\n                                    pretrained='imagenet',\n                                    num_classes=0) # get base model (efficientnet), use imgnet weights\n    inp = base.inputs\n    x = base.output\n    x = tf.keras.layers.GlobalAveragePooling2D()(x) # use GAP to get pooling result form conv outputs\n    x = tf.keras.layers.Dense(32, activation='silu')(x) # use activation to apply non-linearity\n    x = tf.keras.layers.Dense(1,activation='sigmoid')(x) # use sigmoid to convert predictions to [0-1]\n    model = tf.keras.Model(inputs=inp,outputs=x)\n    if compile_model:\n        # optimizer\n        opt = tf.keras.optimizers.Adam(learning_rate=0.0001)\n        # loss\n        if loss_name == 'BCE':\n            loss = tf.keras.losses.BinaryCrossentropy(label_smoothing=0.05)\n        elif loss_name == 'Focal':\n            loss = tfa.losses.SigmoidFocalCrossEntropy(alpha=0.80, gamma=2.0)\n        # metric\n        auc = tf.keras.metrics.AUC(name='auc')\n        pf1 = pFBeta(name='pF1')\n        pf1_thr = pfbeta_thr\n        metrics = [pf1, pf1_thr, auc]\n        # compile\n        model.compile(optimizer=opt,\n                      loss=loss,\n                      metrics=metrics)\n    return model","metadata":{"execution":{"iopub.status.busy":"2022-12-19T15:30:20.806974Z","iopub.execute_input":"2022-12-19T15:30:20.807925Z","iopub.status.idle":"2022-12-19T15:30:20.817942Z","shell.execute_reply.started":"2022-12-19T15:30:20.807887Z","shell.execute_reply":"2022-12-19T15:30:20.816837Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Model Check","metadata":{}},{"cell_type":"code","source":"tmp = build_model(CFG.model_name, dim=CFG.img_size, compile_model=True)\n# tmp.summary()  # too long","metadata":{"_kg_hide-output":true,"execution":{"iopub.status.busy":"2022-12-19T15:30:22.96389Z","iopub.execute_input":"2022-12-19T15:30:22.964264Z","iopub.status.idle":"2022-12-19T15:30:28.135828Z","shell.execute_reply.started":"2022-12-19T15:30:22.964234Z","shell.execute_reply":"2022-12-19T15:30:28.134503Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Learning-Rate Scheduler","metadata":{}},{"cell_type":"code","source":"def get_lr_callback(batch_size=8, plot=False):\n    lr_start   = 0.000005\n    lr_max     = 0.00000105 * REPLICAS * batch_size\n    lr_min     = 0.000001\n    lr_ramp_ep = 4\n    lr_sus_ep  = 0\n    lr_decay   = 0.8\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        elif CFG.scheduler=='exp':\n            lr = (lr_max - lr_min) * lr_decay**(epoch - lr_ramp_ep - lr_sus_ep) + lr_min\n            \n        elif CFG.scheduler=='cosine':\n            decay_total_epochs = CFG.epochs - lr_ramp_ep - lr_sus_ep + 3\n            decay_epoch_index = epoch - lr_ramp_ep - lr_sus_ep\n            phase = math.pi * decay_epoch_index / decay_total_epochs\n            cosine_decay = 0.4 * (1 + math.cos(phase))\n            lr = (lr_max - lr_min) * cosine_decay + lr_min\n        return lr\n    if plot:\n        plt.figure(figsize=(10,5))\n        plt.plot(np.arange(CFG.epochs), [lrfn(epoch) for epoch in np.arange(CFG.epochs)], marker='o')\n        plt.xlabel('epoch'); plt.ylabel('learnig rate')\n        plt.title('Learning Rate Scheduler')\n        plt.show()\n\n    lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=False)\n    return lr_callback\n\n_=get_lr_callback(CFG.batch_size, plot=True )","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-12-19T15:30:30.270606Z","iopub.execute_input":"2022-12-19T15:30:30.271062Z","iopub.status.idle":"2022-12-19T15:30:30.489219Z","shell.execute_reply.started":"2022-12-19T15:30:30.271022Z","shell.execute_reply":"2022-12-19T15:30:30.487943Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Grad-CAM\nGradient-weighted Class Activation Mapping (Grad-CAM), uses the class-specific gradient information flowing into the final convolutional layer of a CNN to produce a coarse localization map of the important regions in the image. Grad-CAM is a strict generalization of the Class Activation Mapping. Grad-CAM provides visual explanations to better understand image classification problems.\n\n<img src=\"http://gradcam.cloudcv.org/static/images/network.png\" width=\"800\">","metadata":{}},{"cell_type":"code","source":"import matplotlib.cm as cm, cv2\nfrom tensorflow import keras\n\ndef gen_gradcam_heatmap(img, model, last_conv, pred_index=0):\n    # First, we create a model that maps the input image to the activations\n    # of the last conv layer as well as the output predictions\n    grad_model = tf.keras.models.Model(\n        [model.inputs], [model.get_layer(last_conv).output, model.output]\n    )\n\n    # Then, we compute the gradient of the top predicted class for our input image\n    # with respect to the activations of the last conv layer\n    with tf.GradientTape() as tape:\n        features, preds = grad_model(img)\n        if pred_index is None:\n            pred_index = tf.argmax(preds[0])\n        class_channel = preds[:, pred_index]\n\n    # This is the gradient of the output neuron (top predicted or chosen)\n    # with regard to the output feature map of the last conv layer\n    grads = tape.gradient(class_channel, features)\n\n    # This is a vector where each entry is the mean intensity of the gradient\n    # over a specific feature map channel\n    pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2))\n\n    # We multiply each channel in the feature map array\n    # by \"how important this channel is\" with regard to the top predicted class\n    # then sum all the channels to obtain the heatmap class activation\n    features = features[0]\n    heatmap = features @ pooled_grads[..., tf.newaxis]\n    heatmap = tf.squeeze(heatmap)\n\n    # For visualization purpose, we will also normalize the heatmap between 0 & 1\n    heatmap = tf.maximum(heatmap, 0) / tf.math.reduce_max(heatmap)\n    return heatmap.numpy()\n\ndef get_gradcam(img, model,  alpha=0.4, show=False):\n\n    heatmap = gen_gradcam_heatmap(img, model, last_conv='stack_6_block1_output', pred_index=0)\n    img     = img[0]\n    # Rescale heatmap to a range 0-255\n    heatmap = np.uint8(255 * heatmap)\n\n    # Use jet colormap to colorize heatmap\n    jet = cm.get_cmap(\"jet\")\n\n    # Use RGB values of the colormap\n    jet_colors  = jet(np.arange(256))[:, :3]\n    jet_heatmap = jet_colors[heatmap]\n\n    # Create an image with RGB colorized heatmap\n    jet_heatmap = cv2.resize(jet_heatmap, dsize=(img.shape[1], img.shape[0]))\n\n    # Superimpose the heatmap on original image\n    superimposed_img = jet_heatmap * alpha + img\n    superimposed_img = keras.preprocessing.image.array_to_img(superimposed_img)\n#     superimposed_img = np.uint8(superimposed_img*255.0)\n\n    # Display Grad CAM\n    if show:\n        plt.imshow(superimposed_img)\n        \n    return superimposed_img","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-12-19T16:56:55.960653Z","iopub.execute_input":"2022-12-19T16:56:55.961797Z","iopub.status.idle":"2022-12-19T16:56:55.975621Z","shell.execute_reply.started":"2022-12-19T16:56:55.961757Z","shell.execute_reply":"2022-12-19T16:56:55.974611Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Wandb** Logger\nLog:\n* Best Score\n* Attention MAP","metadata":{}},{"cell_type":"code","source":"# create directory to save gradcam imgs\n!mkdir -p gradcam\n\n# intialize wandb run\ndef wandb_init(fold):\n    config = {k:v for k,v in dict(vars(CFG)).items() if '__' not in k}\n    config.update({\"fold\":int(fold)})\n    yaml.dump(config, open(f'/kaggle/working/config fold-{fold}.yaml', 'w'),)\n    config = yaml.load(open(f'/kaggle/working/config fold-{fold}.yaml', 'r'), Loader=yaml.FullLoader)\n    run    = wandb.init(project=\"rsna-bcd-public\",\n               name=f\"fold-{fold}|dim-{CFG.img_size[0]}x{CFG.img_size[1]}|model-{CFG.model_name}\",\n               config=config,\n               anonymous=anonymous,\n               group=CFG.exp_name\n                    )\n    return run\n\ndef log_wandb(fold):\n    \"log best result for error analysis\"\n    valid_df = df.query(\"fold==@fold\").copy().reset_index(drop=True)\n    if CFG.debug:\n        valid_df = valid_df[:min_samples]\n    valid_df['pred'] = oof_pred[fold].reshape(-1)\n    valid_df['diff'] = abs(valid_df.cancer - valid_df.pred)\n    valid_df = valid_df.sort_values(by='diff', ascending=False)\n    \n    noimg_cols  = ['site_id', 'patient_id', 'image_id', 'laterality', 'view', 'age',\n                   'cancer', 'biopsy', 'invasive', 'BIRADS', 'implant', 'density',\n                   'machine_id', 'difficult_negative_case','width','height', 'fold'] + ['pred','diff']\n    \n    # select top and worst 10 cases for each class\n    gradcam_df  = pd.concat((valid_df.groupby('cancer').tail(10), \n                             valid_df.groupby('cancer').head(10)), axis=0, ignore_index=True)\n    gradcam_ds  = build_dataset(gradcam_df.image_path, labels=None, cache=False, batch_size=1,\n                   repeat=False, shuffle=False, augment=False)\n    \n    # create wandb table for upload\n    data = []\n    for idx, img in enumerate(tqdm(gradcam_ds, total=40, desc='gradcam ', position=0, leave=True)):\n        gradcam = get_gradcam(img, model)\n        row = gradcam_df[noimg_cols].iloc[idx].tolist()\n        img = img.numpy()[0]\n        img = (img*255.0).astype('uint8')\n        data+=[[*row, wandb.Image(img), wandb.Image(gradcam)]]\n        if idx<10: # save best ones\n            cv2.imwrite(f'gradcam/fold{fold}_{idx:02d}.png', np.concatenate([img, gradcam], axis=1))\n    wandb_table = wandb.Table(data=data, columns=[*noimg_cols, 'image', 'gradcam'])\n    \n    # log values to wandb\n    best_epoch = np.argmax(history.history['val_pF1_thr'])\n    wandb.log({\n               'best_pF1_batch':oof_val[-1], \n               'best_pF1':pF1,\n               'best_pF1_thr':pF1_thr,\n               'best_auc':auc,\n               'best_epoch':best_epoch,\n               'viz_table':wandb_table,\n              })","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## `WandbModelCheckpoint` and `WandbMetricsLogger`\nNewly released callbacks offers more flexibility in terms of customization and also they are compact comparing classic `WandbCallback` hence it easier to use. Here's a brief intro about them,\n\n* **WandbModelCheckpoint**: This callback saves model or weights using `tf.keras.callbacks.ModelCheckpoint`, hence we can harness the power of official tf callback to do so much more such log `tf.keras.Model` subclass model in TPU. \n\n* **WandbMetricsLogger**: This callback simply logs all the metrics and losses.\n\n* **WandbEvalCallback**: This one is even more special, we can use it to log model's prediction after certain epoch/frequency. We can use it to save segmentation mask, bounding boxes and gradcam within epochs to check intermediate result.\n\nFor more details, check [here](https://docs.wandb.ai/ref/python/integrations/keras)","metadata":{}},{"cell_type":"code","source":"# get wandb callbacks\ndef get_wb_callbacks(fold):\n    wb_ckpt = wandb.keras.WandbModelCheckpoint(filepath='fold-%i.h5'%fold, \n                                               monitor='val_pF1_thr',\n                                               verbose=CFG.verbose,\n                                               save_best_only=True,\n                                               save_weights_only=False,\n                                               mode='max',)\n    wb_metr = wandb.keras.WandbMetricsLogger()\n    return [wb_ckpt, wb_metr]","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Train Model\n* Cross-Validation: 5 fold\n* **WandB** dashboard is shown end of the each fold. So we don't need to plot anything. We can select best model from here.","metadata":{}},{"cell_type":"code","source":"oof_pred = []; oof_tar = []; oof_val = []; oof_ids = []; oof_folds = []\npreds = np.zeros((test_df.shape[0],1))\n\nfor fold in np.arange(CFG.folds):\n    \n    # ignore not selected folds\n    if fold not in CFG.selected_folds:\n        continue\n        \n    # init wandb\n    if CFG.wandb:\n        run = wandb_init(fold)\n        wb_callbacks = get_wb_callbacks(fold)\n            \n    # train and valid dataframe\n    train_df = df.query(\"fold!=@fold\")\n    valid_df = df.query(\"fold==@fold\")\n    \n    # upsample cancer data\n    pos_df = train_df.query(\"cancer==1\").sample(frac=CFG.upsample, replace=True)\n    neg_df = train_df.query(\"cancer==0\")\n    train_df = pd.concat([pos_df, neg_df], axis=0, ignore_index=True)\n    \n    # get image_paths and labels\n    train_paths = train_df.image_path.values; train_labels = train_df[CFG.target_col].values.astype(np.float32)\n    valid_paths = valid_df.image_path.values; valid_labels = valid_df[CFG.target_col].values.astype(np.float32)\n    test_paths  = test_df.image_path.values\n    \n    # shuffle train data\n    index = np.arange(len(train_df))\n    np.random.shuffle(index)\n    train_paths  = train_paths[index]\n    train_labels = train_labels[index]\n    \n    # min samples in debug mode\n    min_samples = CFG.batch_size*REPLICAS*2\n    \n    # compute class weight (imbalance)\n    class_weight = compute_class_weight(class_weight='balanced',\n                                        classes=train_df.cancer.unique(),\n                                        y=train_df.cancer.values)\n    class_weight = dict(zip(df.cancer.unique(), class_weight))\n    \n    # for debug model run on small portion\n    if CFG.debug:\n        train_paths = train_paths[:min_samples]; train_labels = train_labels[:min_samples]\n        valid_paths = valid_paths[:min_samples]; valid_labels = valid_labels[:min_samples]\n    \n    # show message\n    print('#'*40); print('#### FOLD: ',fold)\n    print('#### IMAGE_SIZE: (%i, %i) | MODEL_NAME: %s | BATCH_SIZE: %i'%\n          (CFG.img_size[0],CFG.img_size[1],CFG.model_name,CFG.batch_size*REPLICAS))\n    \n    # data stat\n    num_train = len(train_paths)\n    num_valid = len(valid_paths)\n    if CFG.wandb:\n        wandb.log({'num_train':num_train,\n                   'num_valid':num_valid})\n    print('#### NUM_TRAIN: {:,} | NUM_VALID: {:,}'.format(num_train, num_valid))\n    \n    # build model\n    K.clear_session()\n    with strategy.scope():\n        model = build_model(CFG.model_name, dim=CFG.img_size, compile_model=True)\n\n    # build dataset\n    cache = 0\n    train_ds = build_dataset(train_paths, train_labels, cache=cache, batch_size=CFG.batch_size*REPLICAS,\n                   repeat=True, shuffle=True, augment=CFG.augment)\n    val_ds = build_dataset(valid_paths, valid_labels, cache=cache, batch_size=CFG.batch_size*REPLICAS,\n                   repeat=False, shuffle=False, augment=False)\n    print('#'*40)   \n    \n    # callbacks\n    callbacks = []\n    ## save best model after each fold\n    sv = tf.keras.callbacks.ModelCheckpoint(\n        'fold-%i.h5'%fold, monitor='val_pF1_thr', verbose=CFG.verbose, save_best_only=True,\n        save_weights_only=False, mode='max', save_freq='epoch')\n    callbacks +=[sv]\n    ## lr-scheduler\n    callbacks += [get_lr_callback(CFG.batch_size)]\n    ## wandb callbacks\n    if CFG.wandb:\n        callbacks += wb_callbacks\n        \n    # train\n    print('Training...')\n    history = model.fit(\n        train_ds, \n        epochs=CFG.epochs if not CFG.debug else 2, \n        callbacks = callbacks, \n        steps_per_epoch=len(train_paths)/CFG.batch_size//REPLICAS,\n        validation_data=val_ds, \n        class_weight = class_weight if CFG.use_cw else None,\n        verbose=CFG.verbose\n    )\n    \n    # load best model for inference\n    print('Loading best model...')\n    model.load_weights('fold-%i.h5'%fold)  \n    \n    # predict on valid data\n    print('Predicting OOF with TTA...')\n    ds_valid = build_dataset(valid_paths, labels=None, cache=False, batch_size=CFG.batch_size*REPLICAS*2,\n                   repeat=True, shuffle=False, augment=CFG.tta>1)\n    ct_valid = len(valid_paths); STEPS = CFG.tta * ct_valid/CFG.batch_size/2/REPLICAS\n    pred = model.predict(ds_valid,steps=STEPS,verbose=CFG.verbose)[:CFG.tta*ct_valid,] \n    oof_pred.append(np.mean(pred.reshape((CFG.tta, ct_valid,-1)),axis=0))                 \n    \n    # get id and target for valid data\n    oof_tar.append(valid_df[CFG.target_col].values[:(min_samples if CFG.debug else len(valid_df))])\n    oof_folds.append(np.ones_like(oof_tar[-1],dtype='int8')*fold)\n    oof_ids.append(valid_df.image_path.tolist()[:(min_samples if CFG.debug else len(valid_df))])\n    \n#     # predict on test data\n#     print('Predicting Test...')\n#     ds_test = build_dataset(test_paths, labels=None, cache=False, \n#                     batch_size=(CFG.batch_size*2 if len(test_df)>4 else 1)*REPLICAS,\n#                    repeat=True, shuffle=False, augment=CFG.tta>1)\n#     ct_test = len(test_paths); STEPS = 1 if len(test_df)<=4 else (CFG.tta * ct_test/CFG.batch_size/2/REPLICAS)\n#     pred = model.predict(ds_test,steps=STEPS,verbose=CFG.verbose)[:CFG.tta*ct_test,] \n#     preds[:ct_test, :] += np.mean(pred.reshape((CFG.tta, ct_test,-1)),axis=0) / CFG.folds # not meaningful for DIBUG = True\n    \n    # store best results\n    y_true = oof_tar[-1].astype(np.float32); y_pred = oof_pred[-1]\n    pF1 = pfbeta(y_true, y_pred)\n    pF1_thr = pfbeta_thr(y_true, y_pred).numpy() # tf metric\n    auc = roc_auc_score(y_true, y_pred)\n    oof_val.append(np.max(history.history['val_pF1'] ))\n    print('>>>> FOLD %i OOF pF1_batch = %.3f, pF1 = %.3f, pF1_thr = %.3f, auc = %.3f\\n'%(fold,oof_val[-1], \n                                                                                         pF1, \n                                                                                         pF1_thr,\n                                                                                         auc))  # pF1_batch => pF1 batchwise canculated then aggregated\n    \n    # log best result on wandb & plot\n    if CFG.wandb:\n        log_wandb(fold) # log\n        wandb.run.finish() # finish the run\n        display(ipd.IFrame(run.url, width=1080, height=720)) # show wandb dashboard","metadata":{"_kg_hide-input":true,"_kg_hide-output":false,"execution":{"iopub.status.busy":"2022-12-19T15:31:07.464832Z","iopub.execute_input":"2022-12-19T15:31:07.465832Z","iopub.status.idle":"2022-12-19T16:54:05.552497Z","shell.execute_reply.started":"2022-12-19T15:31:07.465801Z","shell.execute_reply":"2022-12-19T16:54:05.550835Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Visualize Grad-CAM","metadata":{}},{"cell_type":"code","source":"from mpl_toolkits.axes_grid1 import ImageGrid\n\nimgs = [cv2.imread(path) for path in glob('/kaggle/working/gradcam/*')[:8]]\nfig = plt.figure(figsize=(20., 15.))\ngrid = ImageGrid(fig, 111,  # similar to subplot(111)\n                 nrows_ncols=(2, 4),  # creates 2x2 grid of axes\n                 axes_pad=0.25,  # pad between axes in inch.\n                 )\n\nfor ax, im in zip(grid, imgs):\n    # Iterating over the grid returns the Axes.\n    ax.imshow(im)\n    ax.set_xticks([])\n    ax.set_yticks([])\n\nplt.show()","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-12-19T17:00:14.808614Z","iopub.execute_input":"2022-12-19T17:00:14.80958Z","iopub.status.idle":"2022-12-19T17:00:16.939651Z","shell.execute_reply.started":"2022-12-19T17:00:14.809542Z","shell.execute_reply":"2022-12-19T17:00:16.938311Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Calculate OOF Score","metadata":{}},{"cell_type":"code","source":"# overall oof pF1\noof = np.concatenate(oof_pred); true = np.concatenate(oof_tar);\nids = np.concatenate(oof_ids); folds = np.concatenate(oof_folds)\npF1 = pfbeta(true.astype(np.float32),oof)\nprint('Overall OOF pF1 = %.3f'%pF1)","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-12-19T17:00:37.417025Z","iopub.execute_input":"2022-12-19T17:00:37.417965Z","iopub.status.idle":"2022-12-19T17:00:37.430503Z","shell.execute_reply.started":"2022-12-19T17:00:37.417924Z","shell.execute_reply":"2022-12-19T17:00:37.429308Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# save oof\ncolumns = ['image_path', 'true', 'pred']\ndf_oof = pd.DataFrame(np.concatenate([ids[:,None], true, oof], axis=1), columns=columns)\ndf_oof = df_oof.merge(df, on=['image_path'], how='left') # merge with train data\ndf_oof.to_csv('oof.csv',index=False)\ndf_oof.head(2)","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-12-19T17:00:44.951238Z","iopub.execute_input":"2022-12-19T17:00:44.952323Z","iopub.status.idle":"2022-12-19T17:00:45.153099Z","shell.execute_reply.started":"2022-12-19T17:00:44.952284Z","shell.execute_reply":"2022-12-19T17:00:45.151911Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# `pF1` Maximize","metadata":{}},{"cell_type":"code","source":"# calculate pf1 for multiple thresholds\nthrs = np.arange(0,1,0.05)\nscores = []\nfor thr in tqdm(thrs):\n    scores+=[pfbeta(df_oof.true.astype('float32'), df_oof.pred.astype('float32')>thr)]\n    \n# get best thr for max pF1\nbest_score_idx = np.argmax(scores)\nbest_score = np.max(scores)\nbest_thr = thrs[best_score_idx]\nprint(f'\\n## MAX pF1 = {best_score: 0.3f} @ {best_thr:0.3f}\\n')\n\n# plot thr vs pF1 graph\nfig, ax = plt.subplots(figsize=(8,4))\nax.fill_between(thrs, scores,\n                color='red', alpha=0.3, )\nax.plot(thrs, scores, '-ok');\nax.axvline(x=best_thr, color='blue', ls='--')\nax.plot(best_thr, best_score, color='blue', marker='o', markersize=12)\nax.set_xlabel('Threshold');\nax.set_ylabel('pF1');\nax.set_title('Threshold Vs pF1');","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-12-19T17:00:50.172625Z","iopub.execute_input":"2022-12-19T17:00:50.173623Z","iopub.status.idle":"2022-12-19T17:00:50.46975Z","shell.execute_reply.started":"2022-12-19T17:00:50.173585Z","shell.execute_reply":"2022-12-19T17:00:50.468636Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Prediction Distribution of OOF & Train \nCheck **Cancer** distribution of `train` and `oof`. ","metadata":{}},{"cell_type":"code","source":"import seaborn as sns\nsns.set(style='dark')\n\nplt.figure(figsize=(10*2,6))\n\nplt.subplot(1, 2, 1)\nsns.kdeplot(x=train_df[CFG.target_col[0]], color='b',fill=True);\nsns.kdeplot(x=df_oof.pred.values.astype('float32'), color='r',fill=True);\nplt.grid('ON')\nplt.xlabel(CFG.target_col[0]);plt.ylabel('freq');plt.title('KDE')\nplt.legend(['train', 'oof'])\n\nplt.subplot(1, 2, 2)\nsns.histplot(x=train_df[CFG.target_col[0]], color='b');\nsns.histplot(x=df_oof.pred.values.astype('float32'), color='r');\nplt.grid('ON')\nplt.xlabel(CFG.target_col[0]);plt.ylabel('freq');plt.title('Histogram')\nplt.legend(['train', 'oof'])\n\nplt.tight_layout()\nplt.show()","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-12-19T17:01:12.508065Z","iopub.execute_input":"2022-12-19T17:01:12.509048Z","iopub.status.idle":"2022-12-19T17:01:14.070003Z","shell.execute_reply.started":"2022-12-19T17:01:12.509005Z","shell.execute_reply":"2022-12-19T17:01:14.068787Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Remove Files","metadata":{}},{"cell_type":"code","source":"!rm -r /kaggle/working/wandb","metadata":{"execution":{"iopub.status.busy":"2022-12-13T07:59:22.701163Z","iopub.status.idle":"2022-12-13T07:59:22.701498Z","shell.execute_reply.started":"2022-12-13T07:59:22.701331Z","shell.execute_reply":"2022-12-13T07:59:22.701346Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Reference:\n1. [RANZCR: EfficientNet TPU Training](https://www.kaggle.com/xhlulu/ranzcr-efficientnet-tpu-training)\n1. [Triple Stratified KFold with TFRecords](https://www.kaggle.com/cdeotte/triple-stratified-kfold-with-tfrecords)","metadata":{}}]}