{"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 2023 Abdominal Trauma Detection](https://www.kaggle.com/competitions/rsna-2023-abdominal-trauma-detection)","metadata":{}},{"cell_type":"markdown","source":"# Idea:\n* In this notebook we will classify `Detect and classify traumatic abdominal injuries` from CT scans.\n* For this ntoebook, we'll use classic **CNN** model: EfficientNet for our training.\n* **Wandb** is integrated hence we can use this notebook to track which experiemnt is peforming better.\n* We'll maximize the `binary_cross_entropy` score using as it similar to `log_loss`.","metadata":{}},{"cell_type":"markdown","source":"# Overview\n\n## Augmentations:\n* Random - Horizontal Flip\n* Random - Brightness, Contrast, Hue, Saturation\n* Coarse Dropout\n\n## WandB Integration:\n* You can track your training using **wandb**\n* It's very easy to compare model's performance using **wandb**.","metadata":{}},{"cell_type":"markdown","source":"# Install Libraries","metadata":{}},{"cell_type":"code","source":"!pip install -q keras-cv-attention-models\n!pip install -qU wandb\n!pip install -qU scikit-learn\n!pip install -q seaborn","metadata":{"_kg_hide-output":true,"_kg_hide-input":false,"execution":{"iopub.status.busy":"2023-10-14T09:27:23.208554Z","iopub.execute_input":"2023-10-14T09:27:23.208878Z","iopub.status.idle":"2023-10-14T09:28:08.278493Z","shell.execute_reply.started":"2023-10-14T09:27:23.208848Z","shell.execute_reply":"2023-10-14T09:28:08.277206Z"},"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":{"_kg_hide-output":true,"execution":{"iopub.status.busy":"2023-10-14T09:28:08.280467Z","iopub.execute_input":"2023-10-14T09:28:08.280798Z","iopub.status.idle":"2023-10-14T09:28:18.105376Z","shell.execute_reply.started":"2023-10-14T09:28:08.280773Z","shell.execute_reply":"2023-10-14T09:28:18.104327Z"},"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":"2023-10-14T09:28:18.10689Z","iopub.execute_input":"2023-10-14T09:28:18.107472Z","iopub.status.idle":"2023-10-14T09:28:18.118114Z","shell.execute_reply.started":"2023-10-14T09:28:18.10742Z","shell.execute_reply":"2023-10-14T09:28:18.114124Z"},"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":"2023-10-14T09:28:18.121532Z","iopub.execute_input":"2023-10-14T09:28:18.121946Z","iopub.status.idle":"2023-10-14T09:28:22.414009Z","shell.execute_reply.started":"2023-10-14T09:28:18.121909Z","shell.execute_reply":"2023-10-14T09:28:22.413022Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Configuration","metadata":{}},{"cell_type":"code","source":"class CFG:\n    wandb         = True\n    competition   = 'rsna-atd' \n    _wandb_kernel = 'narayana_r'\n    debug         = False\n    comment       = 'EfficientNetV1B0-256x256-low_lr-vflip'\n    exp_name      = 'baseline-v4: new_ds + multi_head' # name of the experiment, folds will be grouped using 'exp_name'\n    \n    # use verbose=0 for silent, vebose=1 for interactive,\n    verbose      = 0\n    display_plot = True\n\n    # device\n    device = \"GPU\" #or \"TPU-VM\"\n\n    model_name = 'ResNet50D'\n\n    # seed for data-split, layer init, augs\n    seed = 69\n\n    # number of folds for data-split\n    folds = 4\n    \n    # which folds to train\n    selected_folds = [0, 1, 2]\n\n    # size of the image\n    img_size = [256, 256]\n\n    # batch_size and epochs\n    batch_size = 48\n    epochs = 10\n\n    # loss\n    loss      = 'BCE & CCE'  # BCE, Focal\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   = 'cosine' # cosine\n\n    # dropout\n    drop_prob   = 0.6\n    drop_cnt    = 5\n    drop_size   = 0.05\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 # not using \"bowel_healthy\" & \"extravasation_healthy\"\n    target_col  = [ \"bowel_injury\", \"extravasation_injury\", \"kidney_healthy\", \"kidney_low\",\n                   \"kidney_high\", \"liver_healthy\", \"liver_low\", \"liver_high\",\n                   \"spleen_healthy\", \"spleen_low\", \"spleen_high\"] \n","metadata":{"execution":{"iopub.status.busy":"2023-10-14T09:28:22.415331Z","iopub.execute_input":"2023-10-14T09:28:22.416058Z","iopub.status.idle":"2023-10-14T09:28:22.42687Z","shell.execute_reply.started":"2023-10-14T09:28:22.41601Z","shell.execute_reply":"2023-10-14T09:28:22.425509Z"},"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":"2023-10-14T09:28:22.428643Z","iopub.execute_input":"2023-10-14T09:28:22.429207Z","iopub.status.idle":"2023-10-14T09:28:22.461574Z","shell.execute_reply.started":"2023-10-14T09:28:22.429171Z","shell.execute_reply":"2023-10-14T09:28:22.460625Z"},"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":"2023-10-14T09:28:22.463375Z","iopub.execute_input":"2023-10-14T09:28:22.464089Z","iopub.status.idle":"2023-10-14T09:28:22.901993Z","shell.execute_reply.started":"2023-10-14T09:28:22.464054Z","shell.execute_reply":"2023-10-14T09:28:22.900806Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# ROOT PATH","metadata":{}},{"cell_type":"code","source":"BASE_PATH = f'/kaggle/input/rsna-atd-512x512-png-v2-dataset'","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-10-14T09:28:22.903438Z","iopub.execute_input":"2023-10-14T09:28:22.904107Z","iopub.status.idle":"2023-10-14T09:28:22.908603Z","shell.execute_reply.started":"2023-10-14T09:28:22.904043Z","shell.execute_reply":"2023-10-14T09:28:22.907422Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Meta Data\n\nThe `train.csv` file contains the following meta information:\n\n- `patient_id`: A unique ID code for each patient.\n- `series_id`: A unique ID code for each scan.\n- `instance_number`: The image number within the scan. The lowest instance number for many series is above zero as the original scans were cropped to the abdomen.\n- `[bowel/extravasation]_[healthy/injury]`: The two injury types with binary targets.\n- `[kidney/liver/spleen]_[healthy/low/high]`: The three injury types with three target levels.\n- `any_injury`: Whether the patient had any injury at all.\n","metadata":{}},{"cell_type":"code","source":"# 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.series_id.astype(str)\\\n                    + '/' + df.instance_number.astype(str) +'.png'\ndf = df.drop_duplicates()\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.series_id.astype(str)\\\n                    + '/' + test_df.instance_number.astype(str) +'.png'\ntest_df = test_df.drop_duplicates()\nprint('\\nTest:')\ndisplay(test_df.head(2))","metadata":{"execution":{"iopub.status.busy":"2023-10-14T09:28:22.910473Z","iopub.execute_input":"2023-10-14T09:28:22.911148Z","iopub.status.idle":"2023-10-14T09:28:23.076256Z","shell.execute_reply.started":"2023-10-14T09:28:22.911116Z","shell.execute_reply":"2023-10-14T09:28:23.075273Z"},"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":"2023-10-14T09:28:23.080423Z","iopub.execute_input":"2023-10-14T09:28:23.081332Z","iopub.status.idle":"2023-10-14T09:28:23.10729Z","shell.execute_reply.started":"2023-10-14T09:28:23.081289Z","shell.execute_reply":"2023-10-14T09:28:23.106301Z"},"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":"2023-10-14T09:28:23.108681Z","iopub.execute_input":"2023-10-14T09:28:23.109345Z","iopub.status.idle":"2023-10-14T09:28:23.114687Z","shell.execute_reply.started":"2023-10-14T09:28:23.109311Z","shell.execute_reply":"2023-10-14T09:28:23.113777Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Class Dependency\n\nIn the context of our analysis, class dependencies refer to inherent relationships between different classes. For instance, the status of a scan cannot be simultaneously classified as `injured` and `healthy`. This correlation becomes evident when we visualize the data through a heatmap. It's worth noting that identifying and understanding these relationships allow us to simplify our model by removing redundant information.\n\n## Dependencies Between `injury` and `healthy` in `bowel` and`extravasation`\n\nA key observation from our data visualizations is the perfect complementarity between `bowel_injury` and `bowel_healthy`, as well as between `extravasation_injury` and `extravasation_healthy`. This essentially means that the sum of each pair will always equal `1.0`. \n\nFor the purpose of our model, we will leverage this relationship by only including `{bowel/extravasation}_injury` as variables. We can then calculate the complementary `healthy` status by applying a `sigmoid` function to the corresponding `injury` status.\n\n## Dependencies Between `healthy`, `low`, and `high` in `kidney`, `liver`, and `spleen` \n\nAnother notable relationship in our data pertains to the `{kidney/liver/spleen}_[healthy/low/high]` classifications. These variables are \"softmaxed,\" meanining that the combined probabilities of `healthy`, `low`, and `high` for each organ (`kidney`, `liver`, and `spleen`) sum up to `1.0`.  \n\nIn our model, we will apply the `softmax` function to these variables, effectively reducing the complexity of the model while preserving the essential information for each classification.\n","metadata":{}},{"cell_type":"code","source":"import seaborn as sns\nimport matplotlib.pyplot as plt\n\nsns.set_theme(style=\"white\")\n\n# Compute the correlation matrix\ncorr = df[df.columns[1:14]].corr().round(2)\n\n# Generate a mask for the upper triangle\nmask = np.triu(np.ones_like(corr, dtype=bool))\n\n# Generate a custom diverging colormap\ncmap = sns.diverging_palette(230, 20, as_cmap=True)\n\n# Set up the matplotlib figure\nf, ax = plt.subplots(figsize=(11, 9))\n\n# Draw the heatmap with the mask and correct aspect ratio\nsns.heatmap(corr, mask=mask, annot=True, cmap=cmap, vmax=.3, center=0,\n            square=True, linewidths=.5, cbar_kws={\"shrink\": .5})\nplt.show();","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-10-14T09:28:23.116362Z","iopub.execute_input":"2023-10-14T09:28:23.117039Z","iopub.status.idle":"2023-10-14T09:28:24.034231Z","shell.execute_reply.started":"2023-10-14T09:28:23.11695Z","shell.execute_reply":"2023-10-14T09:28:24.033322Z"},"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":"df['stratify'] = ''\nfor col in CFG.target_col:\n    df['stratify'] += df[col].astype(str)\n\ndf = df.reset_index(drop=True)\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', 'patient_id']).size())","metadata":{"execution":{"iopub.status.busy":"2023-10-14T09:28:24.035236Z","iopub.execute_input":"2023-10-14T09:28:24.035617Z","iopub.status.idle":"2023-10-14T09:28:24.207588Z","shell.execute_reply.started":"2023-10-14T09:28:24.035583Z","shell.execute_reply":"2023-10-14T09:28:24.206639Z"},"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":"2023-10-14T09:28:24.209322Z","iopub.execute_input":"2023-10-14T09:28:24.210027Z","iopub.status.idle":"2023-10-14T09:28:24.229058Z","shell.execute_reply.started":"2023-10-14T09:28:24.209992Z","shell.execute_reply":"2023-10-14T09:28:24.228062Z"},"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":"2023-10-14T09:28:24.230517Z","iopub.execute_input":"2023-10-14T09:28:24.230829Z","iopub.status.idle":"2023-10-14T09:28:24.247771Z","shell.execute_reply.started":"2023-10-14T09:28:24.230797Z","shell.execute_reply":"2023-10-14T09:28:24.246852Z"},"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_image(path):\n        file_bytes = tf.io.read_file(path)\n        if ext == 'png':\n            img = tf.image.decode_png(file_bytes, channels=3, dtype=tf.uint8)\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_label(label):\n        label = tf.cast(label, tf.float32)\n        return (label[0:1], label[1:2], label[2:5], label[5:8], label[8:11])\n    \n    def decode_with_labels(path, label):\n        return decode_image(path), decode_label(label)\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":"2023-10-14T09:28:24.24906Z","iopub.execute_input":"2023-10-14T09:28:24.249887Z","iopub.status.idle":"2023-10-14T09:28:24.266066Z","shell.execute_reply.started":"2023-10-14T09:28:24.249855Z","shell.execute_reply":"2023-10-14T09:28:24.265049Z"},"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 = tf.concat(tars,axis=-1).numpy()\n    plt.figure(figsize=(size*5, 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'{tars[img_idx].round(2)}', fontsize=12)\n        img = imgs[img_idx,]\n        plt.imshow(img)\n        plt.xticks([]); plt.yticks([])\n    plt.tight_layout()\n    plt.show() ","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-10-14T09:28:24.267486Z","iopub.execute_input":"2023-10-14T09:28:24.268126Z","iopub.status.idle":"2023-10-14T09:28:24.282032Z","shell.execute_reply.started":"2023-10-14T09:28:24.268096Z","shell.execute_reply":"2023-10-14T09:28:24.280901Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Generate Image","metadata":{}},{"cell_type":"code","source":"fold = 0\nfold_df = df[df.fold==fold].sample(frac=1.0)\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":"2023-10-14T09:28:24.283572Z","iopub.execute_input":"2023-10-14T09:28:24.284414Z","iopub.status.idle":"2023-10-14T09:28:28.214062Z","shell.execute_reply.started":"2023-10-14T09:28:24.284381Z","shell.execute_reply":"2023-10-14T09:28:28.213099Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## No-Augmentation","metadata":{}},{"cell_type":"code","source":"display_batch(batch, 3);","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-10-14T09:28:28.215439Z","iopub.execute_input":"2023-10-14T09:28:28.215762Z","iopub.status.idle":"2023-10-14T09:28:28.848063Z","shell.execute_reply.started":"2023-10-14T09:28:28.215732Z","shell.execute_reply":"2023-10-14T09:28:28.847225Z"},"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), 3);","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-10-14T09:28:28.849431Z","iopub.execute_input":"2023-10-14T09:28:28.850334Z","iopub.status.idle":"2023-10-14T09:28:31.324151Z","shell.execute_reply.started":"2023-10-14T09:28:28.850299Z","shell.execute_reply":"2023-10-14T09:28:31.322504Z"},"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), 3);","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-10-14T09:28:31.326839Z","iopub.execute_input":"2023-10-14T09:28:31.327553Z","iopub.status.idle":"2023-10-14T09:28:36.368016Z","shell.execute_reply.started":"2023-10-14T09:28:31.32752Z","shell.execute_reply":"2023-10-14T09:28:36.367179Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Loss Function\nWe'll use Binary Cross Entropy loss for `bowel` and `extravasation` at the same time we'll use Categorical Cross Entropy for `kidney`, `liver` and `spleen`.\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":"# Build Model","metadata":{}},{"cell_type":"code","source":"from keras_cv_attention_models import resnet_family\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    \n    # Define backbone\n    base = getattr(resnet_family, model_name)(input_shape=(*dim,3),\n                                    pretrained='imagenet',\n                                    num_classes=0) # get base model (efficientnet), use imgnet weights\n\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\n    # Define 'necks' for each head\n    x_bowel = tf.keras.layers.Dense(64, activation='silu')(x)\n    x_extra = tf.keras.layers.Dense(64, activation='silu')(x)\n    x_liver = tf.keras.layers.Dense(64, activation='silu')(x)\n    x_kidney = tf.keras.layers.Dense(64, activation='silu')(x)\n    x_spleen = tf.keras.layers.Dense(64, activation='silu')(x)\n    \n    hid_bowel = tf.keras.layers.Dense(32, activation='silu')(x_bowel)\n    hid_extra = tf.keras.layers.Dense(32, activation='silu')(x_extra)\n    hid_liver = tf.keras.layers.Dense(32, activation='silu')(x_liver)\n    hid_kidney = tf.keras.layers.Dense(32, activation='silu')(x_kidney)\n    hid_spleen = tf.keras.layers.Dense(32, activation='silu')(x_spleen)\n\n    # Define heads\n    out_bowel = tf.keras.layers.Dense(1, name='bowel', activation='sigmoid')(hid_bowel) # use sigmoid to convert predictions to [0-1]\n    out_extra = tf.keras.layers.Dense(1, name='extra', activation='sigmoid')(hid_extra) # use sigmoid to convert predictions to [0-1]\n    out_liver = tf.keras.layers.Dense(3, name='liver', activation='softmax')(hid_liver) # use softmax for the liver head\n    out_kidney = tf.keras.layers.Dense(3, name='kidney', activation='softmax')(hid_kidney) # use softmax for the kidney head\n    out_spleen = tf.keras.layers.Dense(3, name='spleen', activation='softmax')(hid_spleen) # use softmax for the spleen head\n\n    # Combine outputs\n#     out = tf.keras.layers.Concatenate()([out_bowel, out_extra, \n#                                          out_liver, out_kidney, out_spleen])\n    out = [out_bowel, out_extra, out_liver, out_kidney, out_spleen]\n\n    # Create model\n    model = tf.keras.Model(inputs=inp, outputs=out)\n\n    \n    if compile_model:\n        # optimizer\n        opt = tf.keras.optimizers.Adam(learning_rate=0.0001)\n        # loss\n        loss = {\n            'bowel':tf.keras.losses.BinaryCrossentropy(label_smoothing=0.05),\n            'extra':tf.keras.losses.BinaryCrossentropy(label_smoothing=0.05),\n            'liver':tf.keras.losses.CategoricalCrossentropy(label_smoothing=0.05),\n            'kidney':tf.keras.losses.CategoricalCrossentropy(label_smoothing=0.05),\n            'spleen':tf.keras.losses.CategoricalCrossentropy(label_smoothing=0.05),\n        }\n        # metric\n        metrics = {\n            'bowel':['accuracy'],\n            'extra':['accuracy'],\n            'liver':['accuracy'],\n            'kidney':['accuracy'],\n            'spleen':['accuracy'],\n        }\n        # compile\n        model.compile(optimizer=opt,\n                      loss=loss,\n                      metrics=metrics)\n    return model","metadata":{"execution":{"iopub.status.busy":"2023-10-14T09:28:36.369674Z","iopub.execute_input":"2023-10-14T09:28:36.370309Z","iopub.status.idle":"2023-10-14T09:28:36.441217Z","shell.execute_reply.started":"2023-10-14T09:28:36.370256Z","shell.execute_reply":"2023-10-14T09:28:36.440312Z"},"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)\ntmp.summary()  # too long","metadata":{"_kg_hide-output":true,"scrolled":true,"execution":{"iopub.status.busy":"2023-10-14T09:28:36.442628Z","iopub.execute_input":"2023-10-14T09:28:36.442948Z","iopub.status.idle":"2023-10-14T09:28:42.446003Z","shell.execute_reply.started":"2023-10-14T09:28:36.442918Z","shell.execute_reply":"2023-10-14T09:28:42.445254Z"},"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.00000050 * REPLICAS * batch_size\n    lr_min     = 0.000001\n    lr_ramp_ep = 3\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    \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":"2023-10-14T09:28:42.447048Z","iopub.execute_input":"2023-10-14T09:28:42.447461Z","iopub.status.idle":"2023-10-14T09:28:42.99487Z","shell.execute_reply.started":"2023-10-14T09:28:42.447402Z","shell.execute_reply":"2023-10-14T09:28:42.993743Z"},"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-atd-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    # log values to wandb\n    wandb.log({\n               'best_acc': best_acc,\n               'best_loss': best_loss,\n               'best_epoch': best_epoch,\n               'best_acc_bowel': best_acc_bowel,\n               'best_acc_extra': best_acc_extra,\n               'best_acc_liver': best_acc_liver,\n               'best_acc_kidney': best_acc_kidney,\n               'best_acc_spleen': best_acc_spleen,\n              })\n","metadata":{"execution":{"iopub.status.busy":"2023-10-14T09:28:42.996263Z","iopub.execute_input":"2023-10-14T09:28:42.997148Z","iopub.status.idle":"2023-10-14T09:28:44.101218Z","shell.execute_reply.started":"2023-10-14T09:28:42.997113Z","shell.execute_reply":"2023-10-14T09:28:44.099832Z"},"trusted":true},"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_loss',\n                                               verbose=CFG.verbose,\n                                               save_best_only=True,\n                                               save_weights_only=False,\n                                               mode='min',)\n    wb_metr = wandb.keras.WandbMetricsLogger()\n    return [wb_ckpt, wb_metr]","metadata":{"execution":{"iopub.status.busy":"2023-10-14T09:28:44.103046Z","iopub.execute_input":"2023-10-14T09:28:44.103429Z","iopub.status.idle":"2023-10-14T09:28:44.110216Z","shell.execute_reply.started":"2023-10-14T09:28:44.103392Z","shell.execute_reply":"2023-10-14T09:28:44.108983Z"},"trusted":true},"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":"scores = []\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(f\"fold!={fold}\")\n    valid_df = df.query(f\"fold=={fold}\")\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    # 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 = 1 if 'TPU' in CFG.device else 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_loss', verbose=CFG.verbose, save_best_only=True,\n        save_weights_only=False, mode='min', 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        verbose=CFG.verbose\n    )\n    \n    # store best results\n    best_epoch = np.argmin(history.history['val_loss'])\n    best_loss = history.history['val_loss'][best_epoch]\n    best_acc_bowel = history.history['val_bowel_accuracy'][best_epoch]\n    best_acc_extra = history.history['val_extra_accuracy'][best_epoch]\n    best_acc_liver = history.history['val_liver_accuracy'][best_epoch]\n    best_acc_kidney = history.history['val_kidney_accuracy'][best_epoch]\n    best_acc_spleen = history.history['val_spleen_accuracy'][best_epoch]\n\n    # Find mean accuracy\n    best_acc = np.mean([best_acc_bowel, best_acc_extra, \n                        best_acc_liver, best_acc_kidney, best_acc_spleen])\n\n    print(f'\\n{\"=\"*17} FOLD {fold} RESULTS {\"=\"*17}')\n    print(f'>>>> BEST Loss  : {best_loss:.3f}\\n>>>> BEST Acc   : {best_acc:.3f}\\n>>>> BEST Epoch : {best_epoch}\\n')\n    print('ORGAN Acc:')\n    print(f'  >>>> {\"Bowel\".ljust(15)} : {best_acc_bowel:.3f}')\n    print(f'  >>>> {\"Extravasation\".ljust(15)} : {best_acc_extra:.3f}')\n    print(f'  >>>> {\"Liver\".ljust(15)} : {best_acc_liver:.3f}')\n    print(f'  >>>> {\"Kidney\".ljust(15)} : {best_acc_kidney:.3f}')\n    print(f'  >>>> {\"Spleen\".ljust(15)} : {best_acc_spleen:.3f}')\n\n    print(f'{\"=\"*50}\\n')\n\n    scores.append([best_loss, best_acc,\n                   best_acc_bowel, best_acc_extra,\n                   best_acc_liver, best_acc_kidney, best_acc_spleen])\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":"2023-10-14T09:28:44.112027Z","iopub.execute_input":"2023-10-14T09:28:44.112773Z","iopub.status.idle":"2023-10-14T10:37:10.55594Z","shell.execute_reply.started":"2023-10-14T09:28:44.112738Z","shell.execute_reply":"2023-10-14T10:37:10.554985Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Calculate OOF Score","metadata":{}},{"cell_type":"code","source":"# overall oof pF1\noof_loss, oof_acc, oof_acc_bowel, oof_acc_extra, oof_acc_liver, oof_acc_kidney, oof_acc_spleen = np.array(scores).mean(axis=0)\n\nprint(f'\\n{\"=\"*15} OVERALL OOF RESULTS {\"=\"*15}')\nprint(f'>>>> OOF BEST Loss : {oof_loss:.3f}\\n>>>> OOF BEST Acc  : {oof_acc:.3f}\\n')\nprint('ORGAN OOF Acc:')\nprint(f'  >>>> {\"Bowel\".ljust(15)} : {oof_acc_bowel:.3f}')\nprint(f'  >>>> {\"Extravasation\".ljust(15)} : {oof_acc_extra:.3f}')\nprint(f'  >>>> {\"Liver\".ljust(15)} : {oof_acc_liver:.3f}')\nprint(f'  >>>> {\"Kidney\".ljust(15)} : {oof_acc_kidney:.3f}')\nprint(f'  >>>> {\"Spleen\".ljust(15)} : {oof_acc_spleen:.3f}')\nprint(f'{\"=\"*50}\\n')","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-10-14T10:37:10.560325Z","iopub.execute_input":"2023-10-14T10:37:10.560588Z","iopub.status.idle":"2023-10-14T10:37:10.567485Z","shell.execute_reply.started":"2023-10-14T10:37:10.560564Z","shell.execute_reply":"2023-10-14T10:37:10.566612Z"},"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":"2023-10-14T10:37:10.56874Z","iopub.execute_input":"2023-10-14T10:37:10.569594Z","iopub.status.idle":"2023-10-14T10:37:11.753729Z","shell.execute_reply.started":"2023-10-14T10:37:10.56956Z","shell.execute_reply":"2023-10-14T10:37:11.752344Z"},"trusted":true},"execution_count":null,"outputs":[]}]}