{"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)\n\n> Detect and classify traumatic abdominal injuries\n\n![](https://www.kaggle.com/competitions/52254/images/header)","metadata":{}},{"cell_type":"markdown","source":"# Idea:\n* Same as [RSNA-ATD: CNN [TPU][Train]](https://www.kaggle.com/awsaf49/rsna-atd-cnn-tpu-train/) but with **2.5D** data.\n* 2.5D method is simpling stacking different scan of same series to created a `RGB` like image but here each channel is associated with different scans.","metadata":{}},{"cell_type":"markdown","source":"# Notebooks\n* 2.5D:\n    * Train: [RSNA-ATD: 2.5D Series Image [Train]](https://www.kaggle.com/awsaf49/rsna-atd-2-5d-series-image-train)\n    * Infer: [RSNA-ATD: 2.5D Series Image [Infer]](https://www.kaggle.com/awsaf49/rsna-atd-2-5d-series-image-infer)\n* 2D:\n    * Train: [RSNA-ATD: CNN [TPU][Train]](https://www.kaggle.com/awsaf49/rsna-atd-cnn-tpu-train/)\n    * Infer: [RSNA-ATD: CNN [TPU][Infer]](https://www.kaggle.com/awsaf49/rsna-atd-cnn-tpu-infer/)","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-09-15T16:14:57.404656Z","iopub.execute_input":"2023-09-15T16:14:57.405082Z","iopub.status.idle":"2023-09-15T16:15:25.518607Z","shell.execute_reply.started":"2023-09-15T16:14:57.405042Z","shell.execute_reply":"2023-09-15T16:15:25.517439Z"},"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-09-15T16:15:25.520887Z","iopub.execute_input":"2023-09-15T16:15:25.521237Z","iopub.status.idle":"2023-09-15T16:16:09.783884Z","shell.execute_reply.started":"2023-09-15T16:15:25.521191Z","shell.execute_reply":"2023-09-15T16:16:09.7825Z"},"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-09-15T16:16:09.785332Z","iopub.execute_input":"2023-09-15T16:16:09.785646Z","iopub.status.idle":"2023-09-15T16:16:09.792836Z","shell.execute_reply.started":"2023-09-15T16:16:09.785615Z","shell.execute_reply":"2023-09-15T16:16:09.791941Z"},"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-09-15T16:16:09.795097Z","iopub.execute_input":"2023-09-15T16:16:09.795414Z","iopub.status.idle":"2023-09-15T16:16:12.623427Z","shell.execute_reply.started":"2023-09-15T16:16:09.795387Z","shell.execute_reply":"2023-09-15T16:16:12.622161Z"},"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 = 'awsaf49'\n    debug         = False\n    comment       = 'EfficientNetV1B0-512x512-lr2-vflip'\n    exp_name      = 'baseline-v5: ds-v3 + 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      = 2\n    display_plot = True\n\n    # device\n    device = \"TPU-VM\" #or \"GPU\"\n\n    model_name = 'Vit_base16'\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, 3, 4]\n\n    # size of the image\n    img_size = [512, 512]\n#     eq_dim = np.prod(img_size)**0.5\n\n    # batch_size and epochs\n    batch_size = 8\n    epochs = 20\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   = 'exp' # 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\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\"] # not using \"bowel_healthy\" & \"extravasation_healthy\"\n","metadata":{"execution":{"iopub.status.busy":"2023-09-15T16:16:12.624998Z","iopub.execute_input":"2023-09-15T16:16:12.625591Z","iopub.status.idle":"2023-09-15T16:16:12.638935Z","shell.execute_reply.started":"2023-09-15T16:16:12.625558Z","shell.execute_reply":"2023-09-15T16:16:12.638059Z"},"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-09-15T16:16:12.640074Z","iopub.execute_input":"2023-09-15T16:16:12.640397Z","iopub.status.idle":"2023-09-15T16:16:12.658088Z","shell.execute_reply.started":"2023-09-15T16:16:12.640372Z","shell.execute_reply":"2023-09-15T16:16:12.657203Z"},"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-09-15T16:16:12.659381Z","iopub.execute_input":"2023-09-15T16:16:12.659691Z","iopub.status.idle":"2023-09-15T16:16:20.588257Z","shell.execute_reply.started":"2023-09-15T16:16:12.659659Z","shell.execute_reply":"2023-09-15T16:16:20.587231Z"},"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-v3-dataset'","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-09-15T16:16:20.58957Z","iopub.execute_input":"2023-09-15T16:16:20.589888Z","iopub.status.idle":"2023-09-15T16:16:20.594032Z","shell.execute_reply.started":"2023-09-15T16:16:20.589851Z","shell.execute_reply":"2023-09-15T16:16:20.593112Z"},"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) +'.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) +'.png'\ntest_df = test_df.drop_duplicates()\nprint('\\nTest:')\ndisplay(test_df.head(2))","metadata":{"execution":{"iopub.status.busy":"2023-09-15T16:16:20.595054Z","iopub.execute_input":"2023-09-15T16:16:20.595378Z","iopub.status.idle":"2023-09-15T16:16:20.740847Z","shell.execute_reply.started":"2023-09-15T16:16:20.595351Z","shell.execute_reply":"2023-09-15T16:16:20.7399Z"},"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-09-15T16:16:20.745016Z","iopub.execute_input":"2023-09-15T16:16:20.745396Z","iopub.status.idle":"2023-09-15T16:16:20.771982Z","shell.execute_reply.started":"2023-09-15T16:16:20.745369Z","shell.execute_reply":"2023-09-15T16:16:20.771048Z"},"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-09-15T16:16:20.773054Z","iopub.execute_input":"2023-09-15T16:16:20.773378Z","iopub.status.idle":"2023-09-15T16:16:20.778366Z","shell.execute_reply.started":"2023-09-15T16:16:20.77335Z","shell.execute_reply":"2023-09-15T16:16:20.777484Z"},"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-09-15T16:16:20.779639Z","iopub.execute_input":"2023-09-15T16:16:20.779922Z","iopub.status.idle":"2023-09-15T16:16:22.466965Z","shell.execute_reply.started":"2023-09-15T16:16:20.779897Z","shell.execute_reply":"2023-09-15T16:16:22.465809Z"},"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 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\ndef 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,4])\n        image = image[:, pad[0]:-pad[1],:]\n    elif DIM[1]>DIM[0]:\n        image=tf.reshape(image, [NEW_DIM, NEW_DIM,4])\n        image = image[pad[0]:-pad[1],:,:]\n    image = tf.reshape(image, [*DIM, 4])    \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,4], 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,4])\n\n#     image = tf.reshape(image,[*DIM,3])\n    return image\n\n\ndef ColorAug(img, prob):\n    if random_float() > prob:\n        return img\n    # Get the shape of the input image\n    shape = tf.shape(img)\n    # Separate the alpha channel from the image\n    img_rgb, img_alpha = img[..., :3], img[..., 3:]\n    # Apply random adjustments to the RGB channels\n    img_rgb = tf.image.random_hue(img_rgb, CFG.hue)\n    img_rgb = tf.image.random_saturation(img_rgb, CFG.sat[0], CFG.sat[1])\n    img_rgb = tf.image.random_contrast(img_rgb, CFG.cont[0], CFG.cont[1])\n    img_rgb = tf.image.random_brightness(img_rgb, CFG.bri)\n    # Combine the adjusted RGB channels with the original alpha channel\n    img = tf.concat([img_rgb, img_alpha], axis=-1)\n    # Reshape the image to the original input shape\n    img = tf.reshape(img, shape)\n    return img","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-09-15T16:16:22.468385Z","iopub.execute_input":"2023-09-15T16:16:22.468759Z","iopub.status.idle":"2023-09-15T16:16:22.516445Z","shell.execute_reply.started":"2023-09-15T16:16:22.468727Z","shell.execute_reply":"2023-09-15T16:16:22.515408Z"},"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=4, 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, 4])\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        img = ColorAug(img, prob=CFG.pixel_aug)\n        img = tf.clip_by_value(img, 0, 1)  if CFG.clip else img         \n        img = tf.reshape(img, [*dim, 4])\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    ds = ds.prefetch(AUTO)\n    return ds","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-09-15T16:16:22.517588Z","iopub.execute_input":"2023-09-15T16:16:22.517967Z","iopub.status.idle":"2023-09-15T16:16:22.541321Z","shell.execute_reply.started":"2023-09-15T16:16:22.51794Z","shell.execute_reply":"2023-09-15T16:16:22.540424Z"},"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-09-15T16:16:22.542415Z","iopub.execute_input":"2023-09-15T16:16:22.542731Z","iopub.status.idle":"2023-09-15T16:16:22.556935Z","shell.execute_reply.started":"2023-09-15T16:16:22.542703Z","shell.execute_reply":"2023-09-15T16:16:22.555998Z"},"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-09-15T16:16:22.558Z","iopub.execute_input":"2023-09-15T16:16:22.558374Z","iopub.status.idle":"2023-09-15T16:16:23.322643Z","shell.execute_reply.started":"2023-09-15T16:16:22.558349Z","shell.execute_reply":"2023-09-15T16:16:23.321449Z"},"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-09-15T16:16:23.324052Z","iopub.execute_input":"2023-09-15T16:16:23.324419Z","iopub.status.idle":"2023-09-15T16:16:23.980841Z","shell.execute_reply.started":"2023-09-15T16:16:23.324387Z","shell.execute_reply":"2023-09-15T16:16:23.979757Z"},"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-09-15T16:16:23.981965Z","iopub.execute_input":"2023-09-15T16:16:23.982319Z","iopub.status.idle":"2023-09-15T16:16:26.369129Z","shell.execute_reply.started":"2023-09-15T16:16:23.982289Z","shell.execute_reply":"2023-09-15T16:16:26.36814Z"},"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-09-15T16:16:26.370277Z","iopub.execute_input":"2023-09-15T16:16:26.370565Z","iopub.status.idle":"2023-09-15T16:16:29.553319Z","shell.execute_reply.started":"2023-09-15T16:16:26.370539Z","shell.execute_reply":"2023-09-15T16:16:29.55219Z"},"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":"!pip install -q vit-keras\nfrom vit_keras import vit","metadata":{"execution":{"iopub.status.busy":"2023-09-15T16:16:29.554627Z","iopub.execute_input":"2023-09-15T16:16:29.554971Z","iopub.status.idle":"2023-09-15T16:16:35.922162Z","shell.execute_reply.started":"2023-09-15T16:16:29.554945Z","shell.execute_reply":"2023-09-15T16:16:35.920813Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from vit_keras import vit\ndef channel_squeezer(x):\n    # Expand 4 channels to 32 features\n    x = tf.keras.layers.Conv2D(32, (3, 3), padding='same', activation='gelu')(x)\n    # Squeeze 32 features into 3 channels\n    x = tf.keras.layers.Conv2D(3, (3, 3), padding='same', activation='gelu')(x)\n    return x\ndef build_custom_vit_model(dim=CFG.img_size, compile_model=True):\n    # Define backbone using ViT model\n    base = vit.vit_b16(\n        image_size=dim[0],\n        pretrained=True,\n        include_top=False,\n        pretrained_top=False,\n        classes=0  # The original model has no classification head\n    )\n\n    inp = tf.keras.layers.Input((*dim, 4))\n    # Squeeze 4 channels to 3 channels\n    x = channel_squeezer(inp)\n    mlp = tf.keras.Sequential([\n        base,\n        tf.keras.layers.Flatten(),\n#         tf.keras.layers.BatchNormalization(),\n#         tf.keras.layers.Dense(128, activation = tfa.activations.gelu),\n        tf.keras.layers.BatchNormalization(),\n        tf.keras.layers.Dense(64, activation = tfa.activations.gelu)\n    ],\n    name = 'vit_b16_mlp')\n    x = mlp(x)\n#     x = tf.keras.layers.GlobalAveragePooling2D()(x)\n\n    # Define 'necks' for each head\n    x_bowel = tf.keras.layers.Dense(32, activation='gelu')(x)\n    x_extra = tf.keras.layers.Dense(32, activation='gelu')(x)\n    x_liver = tf.keras.layers.Dense(32, activation='gelu')(x)\n    x_kidney = tf.keras.layers.Dense(32, activation='gelu')(x)\n    x_spleen = tf.keras.layers.Dense(32, activation='gelu')(x)\n\n    # Define heads\n    out_bowel = tf.keras.layers.Dense(1, name='bowel', activation='sigmoid')(x_bowel)\n    out_extra = tf.keras.layers.Dense(1, name='extra', activation='sigmoid')(x_extra)\n    out_liver = tf.keras.layers.Dense(3, name='liver', activation='softmax')(x_liver)\n    out_kidney = tf.keras.layers.Dense(3, name='kidney', activation='softmax')(x_kidney)\n    out_spleen = tf.keras.layers.Dense(3, name='spleen', activation='softmax')(x_spleen)\n\n    # Combine outputs\n    outputs = [out_bowel, out_extra, out_liver, out_kidney, out_spleen]\n\n    # Create model\n    model = tf.keras.Model(inputs=inp, outputs=outputs)\n\n    if compile_model:\n        # Optimizer\n        opt = tf.keras.optimizers.Adam(learning_rate=0.0001)\n\n        # Loss functions and metrics for each head\n        loss = {\n            'bowel': 'binary_crossentropy',\n            'extra': 'binary_crossentropy',\n            'liver': 'categorical_crossentropy',\n            'kidney': 'categorical_crossentropy',\n            'spleen': 'categorical_crossentropy',\n        }\n\n        metrics = {\n            'bowel': ['accuracy'],\n            'extra': ['accuracy'],\n            'liver': ['accuracy'],\n            'kidney': ['accuracy'],\n            'spleen': ['accuracy'],\n        }\n\n        # Compile the model\n        model.compile(optimizer=opt, loss=loss, metrics=metrics)\n\n    return model\n","metadata":{"execution":{"iopub.status.busy":"2023-09-15T16:16:35.923968Z","iopub.execute_input":"2023-09-15T16:16:35.92437Z","iopub.status.idle":"2023-09-15T16:16:35.944717Z","shell.execute_reply.started":"2023-09-15T16:16:35.924333Z","shell.execute_reply":"2023-09-15T16:16:35.943615Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tmp = build_custom_vit_model(dim=CFG.img_size, compile_model=True)\ntmp.summary()  # too long","metadata":{"execution":{"iopub.status.busy":"2023-09-15T16:16:35.94603Z","iopub.execute_input":"2023-09-15T16:16:35.946329Z","iopub.status.idle":"2023-09-15T16:16:45.791985Z","shell.execute_reply.started":"2023-09-15T16:16:35.946304Z","shell.execute_reply":"2023-09-15T16:16:45.79055Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras_cv_attention_models import efficientnet\n\ndef channel_squeezer(x):\n    # Expand 4 channels to 32 features\n    x = tf.keras.layers.Conv2D(32, (3, 3), padding='same', activation='gelu')(x)\n    # Squeeze 32 features into 3 channels\n    x = tf.keras.layers.Conv2D(3, (3, 3), padding='same', activation='gelu')(x)\n    return x\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    # Input layer for 4-channel images\n    inp = tf.keras.layers.Input(shape=(*dim, 4))\n    # Squeeze 4 channels to 3 channels\n    x = channel_squeezer(inp)\n    # Define backbone\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    x = base(x)\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(32, activation='silu')(x)\n    x_extra = tf.keras.layers.Dense(32, activation='silu')(x)\n    x_liver = tf.keras.layers.Dense(32, activation='silu')(x)\n    x_kidney = tf.keras.layers.Dense(32, activation='silu')(x)\n    x_spleen = tf.keras.layers.Dense(32, activation='silu')(x)\n\n    # Define heads\n    out_bowel = tf.keras.layers.Dense(1, name='bowel', activation='sigmoid')(x_bowel) # use sigmoid to convert predictions to [0-1]\n    out_extra = tf.keras.layers.Dense(1, name='extra', activation='sigmoid')(x_extra) # use sigmoid to convert predictions to [0-1]\n    out_liver = tf.keras.layers.Dense(3, name='liver', activation='softmax')(x_liver) # use softmax for the liver head\n    out_kidney = tf.keras.layers.Dense(3, name='kidney', activation='softmax')(x_kidney) # use softmax for the kidney head\n    out_spleen = tf.keras.layers.Dense(3, name='spleen', activation='softmax')(x_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-09-15T16:16:45.793621Z","iopub.execute_input":"2023-09-15T16:16:45.793965Z","iopub.status.idle":"2023-09-15T16:16:45.883111Z","shell.execute_reply.started":"2023-09-15T16:16:45.793934Z","shell.execute_reply":"2023-09-15T16:16:45.881741Z"},"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":"2023-09-15T16:16:45.884555Z","iopub.execute_input":"2023-09-15T16:16:45.884894Z","iopub.status.idle":"2023-09-15T16:16:45.889512Z","shell.execute_reply.started":"2023-09-15T16:16:45.884864Z","shell.execute_reply":"2023-09-15T16:16:45.888261Z"},"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.00000080 * 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":"2023-09-15T16:16:45.890861Z","iopub.execute_input":"2023-09-15T16:16:45.891175Z","iopub.status.idle":"2023-09-15T16:16:46.256739Z","shell.execute_reply.started":"2023-09-15T16:16:45.891147Z","shell.execute_reply":"2023-09-15T16:16:46.255563Z"},"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.comment\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+1,\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-09-15T16:16:46.258166Z","iopub.execute_input":"2023-09-15T16:16:46.258569Z","iopub.status.idle":"2023-09-15T16:16:47.438655Z","shell.execute_reply.started":"2023-09-15T16:16:46.258536Z","shell.execute_reply":"2023-09-15T16:16:47.437139Z"},"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-09-15T16:16:47.440259Z","iopub.execute_input":"2023-09-15T16:16:47.440603Z","iopub.status.idle":"2023-09-15T16:16:47.44746Z","shell.execute_reply.started":"2023-09-15T16:16:47.440564Z","shell.execute_reply":"2023-09-15T16:16:47.446586Z"},"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[df.fold != fold]\n    valid_df = df[df.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_custom_vit_model(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=0, 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 + 1}\\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-09-15T16:16:47.452843Z","iopub.execute_input":"2023-09-15T16:16:47.453138Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.save('/kaggle/working//my_vit_model_25.h5')","metadata":{"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')\n","metadata":{"_kg_hide-input":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Remove Files","metadata":{}},{"cell_type":"code","source":"!rm -r /kaggle/working/wandb","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"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":{}}]}