{"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":"code","source":"!pip install -q /lib/wheels/tensorflow-2.9.1-cp38-cp38-linux_x86_64.whl\n!pip install -q tensorflow-addons==0.18.0\n!pip install -q tensorflow-probability==0.17.0\n!pip install -q opencv-python-headless\n!pip install -q seaborn","metadata":{"execution":{"iopub.status.busy":"2023-03-25T21:55:01.498834Z","iopub.execute_input":"2023-03-25T21:55:01.499105Z","iopub.status.idle":"2023-03-25T21:56:11.907288Z","shell.execute_reply.started":"2023-03-25T21:55:01.499078Z","shell.execute_reply":"2023-03-25T21:56:11.906085Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install -q keras-cv-attention-models\n!pip install -qU wandb\n!pip install -qU scikit-learn","metadata":{"execution":{"iopub.status.busy":"2023-03-25T21:56:11.9094Z","iopub.execute_input":"2023-03-25T21:56:11.909744Z","iopub.status.idle":"2023-03-25T21:56:30.598893Z","shell.execute_reply.started":"2023-03-25T21:56:11.909711Z","shell.execute_reply":"2023-03-25T21:56:30.597915Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'  # to avoid too many logging messages\nimport pandas as pd, numpy as np, random, shutil\nimport tensorflow as tf, re, math\nimport tensorflow.keras.backend as K\nimport sklearn\nimport matplotlib.pyplot as plt\nimport tensorflow_addons as tfa\nimport tensorflow_probability as tfp\nimport wandb\nimport yaml\n\nfrom IPython import display as ipd\nfrom glob import glob\nfrom tqdm import tqdm\nfrom sklearn.model_selection import KFold, StratifiedKFold, GroupKFold, StratifiedGroupKFold\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.utils.class_weight import compute_class_weight","metadata":{"execution":{"iopub.status.busy":"2023-03-25T21:56:30.600191Z","iopub.execute_input":"2023-03-25T21:56:30.600529Z","iopub.status.idle":"2023-03-25T21:56:48.225445Z","shell.execute_reply.started":"2023-03-25T21:56:30.600499Z","shell.execute_reply":"2023-03-25T21:56:48.224353Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-03-25T21:56:48.228295Z","iopub.execute_input":"2023-03-25T21:56:48.228585Z","iopub.status.idle":"2023-03-25T21:56:48.234449Z","shell.execute_reply.started":"2023-03-25T21:56:48.228553Z","shell.execute_reply":"2023-03-25T21:56:48.233701Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-03-25T21:56:48.235409Z","iopub.execute_input":"2023-03-25T21:56:48.23571Z","iopub.status.idle":"2023-03-25T21:56:50.698111Z","shell.execute_reply.started":"2023-03-25T21:56:48.235682Z","shell.execute_reply":"2023-03-25T21:56:50.696921Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class CFG:\n    wandb         = True\n    competition   = 'rsna-bcd' \n    _wandb_kernel = 'awsaf49'\n    debug         = False\n    comment       = 'EfficientNetV1B4-1024x512-roi-up=10-lr4-focal-vflip-wb'\n    exp_name      = 'roi-v2-fix' # name of the experiment, folds will be grouped using 'exp_name'\n    \n    # use verbose=0 for silent, vebose=1 for interactive,\n    verbose      = 1\n    display_plot = True\n\n    # device\n    device = \"TPU-VM\" #or \"GPU\"\n\n    model_name = 'EfficientNetV1B4'\n\n    # seed for data-split, layer init, augs\n    seed = 42\n\n    # number of folds for data-split\n    folds = 5\n    \n    # which folds to train\n    selected_folds = [0, 1, 2]\n\n    # size of the image\n    img_size = [1024, 512]\n#     eq_dim = np.prod(img_size)**0.5\n\n    # batch_size and epochs\n    batch_size = 28\n    epochs = 8\n    \n    # upsample\n    upsample = 10\n\n    # loss\n    loss      = 'Focal'  # BCE, Focal\n    use_cw    = False  # use class weight or not\n    \n    # optimizer\n    optimizer = 'Adam'\n\n    # augmentation\n    augment   = True\n\n    # scale-shift-rotate-shear\n    transform = 0.90  # transform prob\n    fill_mode = 'constant'\n    rot    = 2.0\n    shr    = 2.0\n    hzoom  = 50.0\n    wzoom  = 50.0\n    hshift = 10.0\n    wshift = 10.0\n\n    # flip\n    hflip = True\n    vflip = True\n\n    # clip\n    clip = False\n\n    # lr-scheduler\n    scheduler   = 'exp' # cosine\n\n    # dropout\n    drop_prob   = 0.6\n    drop_cnt    = 10\n    drop_size   = 0.08\n    \n    # cut-mix-up\n    mixup_prob = 0.0\n    mixup_alpha = 0.5\n    \n    cutmix_prob = 0.0\n    cutmix_alpha = 2.5\n\n    # pixel-augment\n    pixel_aug = 0.90  # prob of pixel_aug\n    sat  = [0.7, 1.3]\n    cont = [0.8, 1.2]\n    bri  = 0.15\n    hue  = 0.05\n\n    # test-time augs\n    tta = 1\n    \n    # target column\n    target_col  = ['cancer']","metadata":{"execution":{"iopub.status.busy":"2023-03-25T21:56:50.699674Z","iopub.execute_input":"2023-03-25T21:56:50.700511Z","iopub.status.idle":"2023-03-25T21:56:50.71282Z","shell.execute_reply.started":"2023-03-25T21:56:50.700474Z","shell.execute_reply":"2023-03-25T21:56:50.711922Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-03-25T21:56:50.71397Z","iopub.execute_input":"2023-03-25T21:56:50.714271Z","iopub.status.idle":"2023-03-25T21:56:50.728187Z","shell.execute_reply.started":"2023-03-25T21:56:50.714243Z","shell.execute_reply":"2023-03-25T21:56:50.727215Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2023-03-25T21:56:50.729281Z","iopub.execute_input":"2023-03-25T21:56:50.729928Z","iopub.status.idle":"2023-03-25T21:57:00.261108Z","shell.execute_reply.started":"2023-03-25T21:56:50.729899Z","shell.execute_reply":"2023-03-25T21:57:00.260038Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"BASE_PATH = f'/kaggle/input/rsna-bcd-roi-{CFG.img_size[0]}x{CFG.img_size[1]}-png-v2-dataset'\n\nif CFG.device==\"TPU\":\n    from kaggle_datasets import KaggleDatasets\n    GCS_PATH = KaggleDatasets().get_gcs_path(BASE_PATH.split('/')[-1])","metadata":{"execution":{"iopub.status.busy":"2023-03-25T21:57:00.262729Z","iopub.execute_input":"2023-03-25T21:57:00.263132Z","iopub.status.idle":"2023-03-25T21:57:00.268806Z","shell.execute_reply.started":"2023-03-25T21:57:00.263097Z","shell.execute_reply":"2023-03-25T21:57:00.267447Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# use gcs_path for remote-tpu\nif CFG.device==\"TPU\":\n    BASE_PATH = GCS_PATH\n\n# train\ndf = pd.read_csv(f'{BASE_PATH}/train.csv')\ndf['image_path'] = f'{BASE_PATH}/train_images'\\\n                    + '/' + df.patient_id.astype(str)\\\n                    + '/' + df.image_id.astype(str)\\\n                    + '.png'\nprint('Train:')\ndisplay(df.head(2))\n\n# test\ntest_df = pd.read_csv(f'{BASE_PATH}/test.csv')\ntest_df['image_path'] = f'{BASE_PATH}/test_images'\\\n                    + '/' + test_df.patient_id.astype(str)\\\n                    + '/' + test_df.image_id.astype(str)\\\n                    + '.png'\nprint('\\nTest:')\ndisplay(test_df.head(2))","metadata":{"execution":{"iopub.status.busy":"2023-03-25T21:57:00.270362Z","iopub.execute_input":"2023-03-25T21:57:00.270675Z","iopub.status.idle":"2023-03-25T21:57:00.653864Z","shell.execute_reply.started":"2023-03-25T21:57:00.270646Z","shell.execute_reply":"2023-03-25T21:57:00.652813Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-03-25T21:57:00.658485Z","iopub.execute_input":"2023-03-25T21:57:00.658847Z","iopub.status.idle":"2023-03-25T21:57:00.697059Z","shell.execute_reply.started":"2023-03-25T21:57:00.658815Z","shell.execute_reply":"2023-03-25T21:57:00.695907Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('train_files:',df.shape[0])\nprint('test_files:',test_df.shape[0])","metadata":{"execution":{"iopub.status.busy":"2023-03-25T21:57:00.698363Z","iopub.execute_input":"2023-03-25T21:57:00.698669Z","iopub.status.idle":"2023-03-25T21:57:00.704035Z","shell.execute_reply.started":"2023-03-25T21:57:00.698639Z","shell.execute_reply":"2023-03-25T21:57:00.703066Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"num_bins = 5\ndf[\"age_bin\"] = pd.cut(df['age'].values.reshape(-1), bins=num_bins, labels=False)\n\nstrat_cols = [\n    'laterality', 'view', 'biopsy','invasive', 'BIRADS', 'age_bin',\n    'implant', 'density','machine_id', 'difficult_negative_case',\n    'cancer',\n]\n\ndf['stratify'] = ''\nfor col in strat_cols:\n    df['stratify'] += df[col].astype(str)\n\nskf = StratifiedGroupKFold(n_splits=CFG.folds, shuffle=True, random_state=CFG.seed)\nfor fold, (train_idx, val_idx) in enumerate(skf.split(df, df['stratify'], df[\"patient_id\"])):\n    df.loc[val_idx, 'fold'] = fold\ndisplay(df.groupby(['fold', \"cancer\"]).size())","metadata":{"execution":{"iopub.status.busy":"2023-03-25T21:57:00.705351Z","iopub.execute_input":"2023-03-25T21:57:00.705769Z","iopub.status.idle":"2023-03-25T21:57:10.508149Z","shell.execute_reply.started":"2023-03-25T21:57:00.705731Z","shell.execute_reply":"2023-03-25T21:57:10.506594Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2023-03-25T21:57:10.509741Z","iopub.execute_input":"2023-03-25T21:57:10.510089Z","iopub.status.idle":"2023-03-25T21:57:10.542899Z","shell.execute_reply.started":"2023-03-25T21:57:10.510059Z","shell.execute_reply":"2023-03-25T21:57:10.541915Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2023-03-25T21:57:10.544399Z","iopub.execute_input":"2023-03-25T21:57:10.545052Z","iopub.status.idle":"2023-03-25T21:57:10.572066Z","shell.execute_reply.started":"2023-03-25T21:57:10.545Z","shell.execute_reply":"2023-03-25T21:57:10.57105Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def build_decoder(with_labels=True, target_size=CFG.img_size, ext='png'):\n    def decode(path):\n        file_bytes = tf.io.read_file(path)\n        if ext == 'png':\n            img = tf.image.decode_png(file_bytes, channels=3)\n        elif ext in ['jpg', 'jpeg']:\n            img = tf.image.decode_jpeg(file_bytes, channels=3)\n        else:\n            raise ValueError(\"Image extension not supported\")\n\n        img = tf.image.resize(img, target_size, method='bilinear')\n        img = tf.cast(img, tf.float32) / 255.0\n        img = tf.reshape(img, [*target_size, 3])\n\n        return img\n    \n    def decode_with_labels(path, label):\n        return decode(path), tf.cast(label, tf.float32)\n    \n    return decode_with_labels if with_labels else decode\n\n\ndef build_augmenter(with_labels=True, dim=CFG.img_size):\n    def augment(img, dim=dim):\n        if random_float() < CFG.transform:\n            img = transform(img,DIM=dim)\n        img = tf.image.random_flip_left_right(img) if CFG.hflip else img\n        img = tf.image.random_flip_up_down(img) if CFG.vflip else img\n        if random_float() < CFG.pixel_aug:\n            img = tf.image.random_hue(img, CFG.hue)\n            img = tf.image.random_saturation(img, CFG.sat[0], CFG.sat[1])\n            img = tf.image.random_contrast(img, CFG.cont[0], CFG.cont[1])\n            img = tf.image.random_brightness(img, CFG.bri)\n        img = tf.clip_by_value(img, 0, 1)  if CFG.clip else img         \n        img = tf.reshape(img, [*dim, 3])\n        return img\n    \n    def augment_with_labels(img, label):    \n        return augment(img), label\n    \n    return augment_with_labels if with_labels else augment\n\n\ndef build_dataset(paths, labels=None, batch_size=32, cache=True,\n                  decode_fn=None, augment_fn=None,\n                  augment=True, repeat=True, shuffle=1024, \n                  cache_dir=\"\", drop_remainder=False):\n    if cache_dir != \"\" and cache is True:\n        os.makedirs(cache_dir, exist_ok=True)\n    \n    if decode_fn is None:\n        decode_fn = build_decoder(labels is not None)\n    \n    if augment_fn is None:\n        augment_fn = build_augmenter(labels is not None)\n    \n    AUTO = tf.data.experimental.AUTOTUNE\n    slices = paths if labels is None else (paths, labels)\n    \n    ds = tf.data.Dataset.from_tensor_slices(slices)\n    ds = ds.map(decode_fn, num_parallel_calls=AUTO)\n    ds = ds.cache(cache_dir) if cache else ds\n    ds = ds.repeat() if repeat else ds\n    if shuffle: \n        ds = ds.shuffle(shuffle, seed=CFG.seed)\n        opt = tf.data.Options()\n        opt.experimental_deterministic = False\n        ds = ds.with_options(opt)\n    ds = ds.map(augment_fn, num_parallel_calls=AUTO) if augment else ds\n    if augment and labels is not None:\n        ds = ds.map(lambda img, label: (dropout(img, \n                                               DIM=CFG.img_size, \n                                               PROBABILITY=CFG.drop_prob, \n                                               CT=CFG.drop_cnt,\n                                               SZ=CFG.drop_size), label),num_parallel_calls=AUTO)\n    ds = ds.batch(batch_size, drop_remainder=drop_remainder)\n    if augment and labels is not None:\n        if CFG.cutmix_prob:\n            ds = ds.map(get_cutmix(alpha=CFG.cutmix_alpha,prob=CFG.cutmix_prob),num_parallel_calls=AUTO)\n        if CFG.mixup_prob:\n            ds = ds.map(get_mixup(alpha=CFG.mixup_alpha,prob=CFG.mixup_prob),num_parallel_calls=AUTO)\n    ds = ds.prefetch(AUTO)\n    return ds","metadata":{"execution":{"iopub.status.busy":"2023-03-25T21:57:10.573728Z","iopub.execute_input":"2023-03-25T21:57:10.574034Z","iopub.status.idle":"2023-03-25T21:57:10.60184Z","shell.execute_reply.started":"2023-03-25T21:57:10.573993Z","shell.execute_reply":"2023-03-25T21:57:10.600897Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def display_batch(batch, size=2):\n    if isinstance(batch, tuple):\n        imgs, tars = batch\n    else:\n        imgs = batch\n        tars = None\n    tars = tars.numpy().squeeze()\n    plt.figure(figsize=(size*2, 10))\n    for img_idx in range(size):\n        plt.subplot(1, size, img_idx+1)\n        if tars is not None:\n            plt.title(f'{CFG.target_col[0]}: {tars[img_idx]:0.3f}', fontsize=10)\n        plt.imshow(imgs[img_idx,:, :, :])\n        plt.xticks([]); plt.yticks([])\n    plt.tight_layout()\n    plt.show() ","metadata":{"execution":{"iopub.status.busy":"2023-03-25T21:57:10.603155Z","iopub.execute_input":"2023-03-25T21:57:10.603828Z","iopub.status.idle":"2023-03-25T21:57:10.61446Z","shell.execute_reply.started":"2023-03-25T21:57:10.603794Z","shell.execute_reply":"2023-03-25T21:57:10.613477Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fold = 0\nfold_df = df.groupby('cancer').head(16)\npaths  = fold_df.image_path.tolist()\nlabels = fold_df[CFG.target_col].values\nds = build_dataset(paths, labels, cache=False, batch_size=32,\n                   repeat=True, shuffle=True, augment=False)\nds = ds.unbatch().batch(20)\nbatch = next(iter(ds))","metadata":{"execution":{"iopub.status.busy":"2023-03-25T21:57:10.615551Z","iopub.execute_input":"2023-03-25T21:57:10.615848Z","iopub.status.idle":"2023-03-25T21:57:11.082377Z","shell.execute_reply.started":"2023-03-25T21:57:10.615822Z","shell.execute_reply":"2023-03-25T21:57:11.08099Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"display_batch(batch, 5);","metadata":{"execution":{"iopub.status.busy":"2023-03-25T21:57:11.084051Z","iopub.execute_input":"2023-03-25T21:57:11.084414Z","iopub.status.idle":"2023-03-25T21:57:11.962857Z","shell.execute_reply.started":"2023-03-25T21:57:11.084381Z","shell.execute_reply":"2023-03-25T21:57:11.961809Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mixup = get_mixup(alpha=2.5, prob=1)\nmimgs, mtars = mixup(batch[0], batch[1])\ndisplay_batch((mimgs, mtars), 5);","metadata":{"execution":{"iopub.status.busy":"2023-03-25T21:57:11.964174Z","iopub.execute_input":"2023-03-25T21:57:11.964466Z","iopub.status.idle":"2023-03-25T21:57:13.539598Z","shell.execute_reply.started":"2023-03-25T21:57:11.964439Z","shell.execute_reply":"2023-03-25T21:57:13.538393Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cutmix = get_cutmix(alpha=2.5, prob=1)\ncimgs, ctars = cutmix(batch[0], batch[1])\ndisplay_batch((cimgs, ctars), 5);","metadata":{"execution":{"iopub.status.busy":"2023-03-25T21:57:13.540953Z","iopub.execute_input":"2023-03-25T21:57:13.541268Z","iopub.status.idle":"2023-03-25T21:57:15.358493Z","shell.execute_reply.started":"2023-03-25T21:57:13.541239Z","shell.execute_reply":"2023-03-25T21:57:15.357443Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dimgs = tf.map_fn(lambda img: dropout(img,\n                DIM=CFG.img_size, \n                PROBABILITY=1.0, \n                CT=10,\n                SZ=0.08), batch[0])\ndtars = batch[1]\ndisplay_batch((dimgs, dtars), 5);","metadata":{"execution":{"iopub.status.busy":"2023-03-25T21:57:15.35977Z","iopub.execute_input":"2023-03-25T21:57:15.360103Z","iopub.status.idle":"2023-03-25T21:57:17.566638Z","shell.execute_reply.started":"2023-03-25T21:57:15.360075Z","shell.execute_reply":"2023-03-25T21:57:17.565577Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"timgs = tf.map_fn(lambda img: transform(img,DIM=CFG.img_size), batch[0])\nttars = batch[1]\ndisplay_batch((timgs, ttars), 5);","metadata":{"execution":{"iopub.status.busy":"2023-03-25T21:57:17.567775Z","iopub.execute_input":"2023-03-25T21:57:17.568383Z","iopub.status.idle":"2023-03-25T21:57:20.679607Z","shell.execute_reply.started":"2023-03-25T21:57:17.568341Z","shell.execute_reply":"2023-03-25T21:57:20.678515Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# tensorflow\n\nclass pFBeta(tf.keras.metrics.Metric):\n    \"\"\"Compute overall probabilistic F-beta score.\"\"\"\n    def __init__(self, beta=1, epsilon=1e-5, name='pF1', **kwargs):\n        super().__init__(name=name, **kwargs)\n        self.beta = beta\n        self.epsilon = epsilon\n        self.pos = self.add_weight(name='pos', initializer='zeros')\n        self.ctp = self.add_weight(name='ctp', initializer='zeros')\n        self.cfp = self.add_weight(name='cfp', initializer='zeros')\n\n    def update_state(self, y_true, y_pred, sample_weight=None):\n        y_true = tf.cast(y_true, tf.float32)\n        y_pred = tf.clip_by_value(y_pred, 0, 1)\n        pos = tf.reduce_sum(y_true)\n        ctp = tf.reduce_sum(y_pred[y_true==1])\n        cfp = tf.reduce_sum(y_pred[y_true==0])\n        self.pos.assign_add(pos)\n        self.ctp.assign_add(ctp)\n        self.cfp.assign_add(cfp)\n\n    def result(self):\n        beta_squared = self.beta * self.beta\n        c_precision = self.ctp / (self.ctp + self.cfp + self.epsilon)\n        c_recall = self.ctp / (self.pos + self.epsilon)\n        result = (1 + beta_squared) * (c_precision * c_recall) / (beta_squared * c_precision + c_recall)\n        return tf.cond(c_precision > 0 and c_recall > 0, lambda: result, lambda: 0.0)\n\n\n# computes batch-wise pfbeta\ndef pfbeta_tf(labels, preds, beta=1):\n    eps = 1e-5\n    preds = tf.clip_by_value(preds, 0, 1)\n    y_true_count = tf.reduce_sum(labels)\n    ctp = tf.reduce_sum(preds[labels==1])\n    cfp = tf.reduce_sum(preds[labels==0])\n    beta_squared = beta * beta\n    c_precision = ctp / (ctp + cfp + eps)\n    c_recall = ctp / (y_true_count + eps)\n    if (c_precision > 0 and c_recall > 0):\n        result = (1 + beta_squared) * (c_precision * c_recall) / (beta_squared * c_precision + c_recall + eps)\n        return result\n    else:\n        return tf.constant(0.0, dtype=tf.float32)\n\n# finds best pf1 using thresholds\ndef pfbeta_thr(labels, preds):\n    thrs = tf.range(0, 1, 0.05)\n    best_score = tf.constant(0, dtype=tf.float32)\n    for thr in thrs:\n        score = pfbeta_tf(labels, tf.cast(preds>thr, tf.float32))\n        best_score = tf.cond(score > best_score, lambda: score, lambda: best_score)\n    return best_score\n\npfbeta_thr.__name__='pF1_thr'\n\n\n# numpy\ndef pfbeta(labels, preds, beta=1):\n    eps = 1e-5\n    preds = preds.clip(0, 1)\n    y_true_count = labels.sum()\n    ctp = preds[labels==1].sum()\n    cfp = preds[labels==0].sum()\n    beta_squared = beta * beta\n    c_precision = ctp / (ctp + cfp + eps)\n    c_recall = ctp / (y_true_count + eps)\n    if (c_precision > 0 and c_recall > 0):\n        result = (1 + beta_squared) * (c_precision * c_recall) / (beta_squared * c_precision + c_recall + eps)\n        return result\n    else:\n        return 0.0","metadata":{"execution":{"iopub.status.busy":"2023-03-25T21:57:20.680851Z","iopub.execute_input":"2023-03-25T21:57:20.681223Z","iopub.status.idle":"2023-03-25T21:57:20.704403Z","shell.execute_reply.started":"2023-03-25T21:57:20.681195Z","shell.execute_reply":"2023-03-25T21:57:20.703572Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras_cv_attention_models import efficientnet\n\ndef build_model(model_name=CFG.model_name,\n                loss_name=CFG.loss,\n                dim=CFG.img_size,\n                compile_model=True,\n                include_top=False):         \n    base = getattr(efficientnet, model_name)(input_shape=(*dim,3),\n                                    pretrained='imagenet',\n                                    num_classes=0) # get base model (efficientnet), use imgnet weights\n    inp = base.inputs\n    x = base.output\n    x = tf.keras.layers.GlobalAveragePooling2D()(x) # use GAP to get pooling result form conv outputs\n    x = tf.keras.layers.Dense(32, activation='silu')(x) # use activation to apply non-linearity\n    x = tf.keras.layers.Dense(1,activation='sigmoid')(x) # use sigmoid to convert predictions to [0-1]\n    model = tf.keras.Model(inputs=inp,outputs=x)\n    if compile_model:\n        # optimizer\n        opt = tf.keras.optimizers.Adam(learning_rate=0.0001)\n        # loss\n        if loss_name == 'BCE':\n            loss = tf.keras.losses.BinaryCrossentropy(label_smoothing=0.05)\n        elif loss_name == 'Focal':\n            loss = tfa.losses.SigmoidFocalCrossEntropy(alpha=0.80, gamma=2.0)\n        # metric\n        auc = tf.keras.metrics.AUC(name='auc')\n        pf1 = pFBeta(name='pF1')\n        pf1_thr = pfbeta_thr\n        metrics = [pf1, pf1_thr, auc]\n        # compile\n        model.compile(optimizer=opt,\n                      loss=loss,\n                      metrics=metrics)\n    return model","metadata":{"execution":{"iopub.status.busy":"2023-03-25T21:57:20.705414Z","iopub.execute_input":"2023-03-25T21:57:20.705743Z","iopub.status.idle":"2023-03-25T21:57:20.762666Z","shell.execute_reply.started":"2023-03-25T21:57:20.705718Z","shell.execute_reply":"2023-03-25T21:57:20.761842Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tmp = build_model(CFG.model_name, dim=CFG.img_size, compile_model=True)\n# tmp.summary()  # too long","metadata":{"execution":{"iopub.status.busy":"2023-03-25T21:57:20.763669Z","iopub.execute_input":"2023-03-25T21:57:20.763948Z","iopub.status.idle":"2023-03-25T21:57:25.689063Z","shell.execute_reply.started":"2023-03-25T21:57:20.763923Z","shell.execute_reply":"2023-03-25T21:57:25.688011Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_lr_callback(batch_size=8, plot=False):\n    lr_start   = 0.000005\n    lr_max     = 0.00000105 * REPLICAS * batch_size\n    lr_min     = 0.000001\n    lr_ramp_ep = 4\n    lr_sus_ep  = 0\n    lr_decay   = 0.8\n   \n    def lrfn(epoch):\n        if epoch < lr_ramp_ep:\n            lr = (lr_max - lr_start) / lr_ramp_ep * epoch + lr_start\n            \n        elif epoch < lr_ramp_ep + lr_sus_ep:\n            lr = lr_max\n            \n        elif CFG.scheduler=='exp':\n            lr = (lr_max - lr_min) * lr_decay**(epoch - lr_ramp_ep - lr_sus_ep) + lr_min\n            \n        elif CFG.scheduler=='cosine':\n            decay_total_epochs = CFG.epochs - lr_ramp_ep - lr_sus_ep + 3\n            decay_epoch_index = epoch - lr_ramp_ep - lr_sus_ep\n            phase = math.pi * decay_epoch_index / decay_total_epochs\n            cosine_decay = 0.4 * (1 + math.cos(phase))\n            lr = (lr_max - lr_min) * cosine_decay + lr_min\n        return lr\n    if plot:\n        plt.figure(figsize=(10,5))\n        plt.plot(np.arange(CFG.epochs), [lrfn(epoch) for epoch in np.arange(CFG.epochs)], marker='o')\n        plt.xlabel('epoch'); plt.ylabel('learnig rate')\n        plt.title('Learning Rate Scheduler')\n        plt.show()\n\n    lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=False)\n    return lr_callback\n\n_=get_lr_callback(CFG.batch_size, plot=True )","metadata":{"execution":{"iopub.status.busy":"2023-03-25T21:57:25.690379Z","iopub.execute_input":"2023-03-25T21:57:25.690687Z","iopub.status.idle":"2023-03-25T21:57:25.919146Z","shell.execute_reply.started":"2023-03-25T21:57:25.690658Z","shell.execute_reply":"2023-03-25T21:57:25.918215Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.cm as cm, cv2\nfrom tensorflow import keras\n\ndef gen_gradcam_heatmap(img, model, last_conv, pred_index=0):\n    # First, we create a model that maps the input image to the activations\n    # of the last conv layer as well as the output predictions\n    grad_model = tf.keras.models.Model(\n        [model.inputs], [model.get_layer(last_conv).output, model.output]\n    )\n\n    # Then, we compute the gradient of the top predicted class for our input image\n    # with respect to the activations of the last conv layer\n    with tf.GradientTape() as tape:\n        features, preds = grad_model(img)\n        if pred_index is None:\n            pred_index = tf.argmax(preds[0])\n        class_channel = preds[:, pred_index]\n\n    # This is the gradient of the output neuron (top predicted or chosen)\n    # with regard to the output feature map of the last conv layer\n    grads = tape.gradient(class_channel, features)\n\n    # This is a vector where each entry is the mean intensity of the gradient\n    # over a specific feature map channel\n    pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2))\n\n    # We multiply each channel in the feature map array\n    # by \"how important this channel is\" with regard to the top predicted class\n    # then sum all the channels to obtain the heatmap class activation\n    features = features[0]\n    heatmap = features @ pooled_grads[..., tf.newaxis]\n    heatmap = tf.squeeze(heatmap)\n\n    # For visualization purpose, we will also normalize the heatmap between 0 & 1\n    heatmap = tf.maximum(heatmap, 0) / tf.math.reduce_max(heatmap)\n    return heatmap.numpy()\n\ndef get_gradcam(img, model,  alpha=0.4, show=False):\n\n    heatmap = gen_gradcam_heatmap(img, model, last_conv='stack_6_block1_output', pred_index=0)\n    img     = img[0]\n    # Rescale heatmap to a range 0-255\n    heatmap = np.uint8(255 * heatmap)\n\n    # Use jet colormap to colorize heatmap\n    jet = cm.get_cmap(\"jet\")\n\n    # Use RGB values of the colormap\n    jet_colors  = jet(np.arange(256))[:, :3]\n    jet_heatmap = jet_colors[heatmap]\n\n    # Create an image with RGB colorized heatmap\n    jet_heatmap = cv2.resize(jet_heatmap, dsize=(img.shape[1], img.shape[0]))\n\n    # Superimpose the heatmap on original image\n    superimposed_img = jet_heatmap * alpha + img\n    superimposed_img = keras.preprocessing.image.array_to_img(superimposed_img)\n#     superimposed_img = np.uint8(superimposed_img*255.0)\n\n    # Display Grad CAM\n    if show:\n        plt.imshow(superimposed_img)\n        \n    return superimposed_img","metadata":{"execution":{"iopub.status.busy":"2023-03-25T21:57:25.920335Z","iopub.execute_input":"2023-03-25T21:57:25.920649Z","iopub.status.idle":"2023-03-25T21:57:26.682793Z","shell.execute_reply.started":"2023-03-25T21:57:25.920619Z","shell.execute_reply":"2023-03-25T21:57:26.681879Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# create directory to save gradcam imgs\n!mkdir -p gradcam\n\n# intialize wandb run\ndef wandb_init(fold):\n    config = {k:v for k,v in dict(vars(CFG)).items() if '__' not in k}\n    config.update({\"fold\":int(fold)})\n    yaml.dump(config, open(f'/kaggle/working/config fold-{fold}.yaml', 'w'),)\n    config = yaml.load(open(f'/kaggle/working/config fold-{fold}.yaml', 'r'), Loader=yaml.FullLoader)\n    run    = wandb.init(project=\"rsna-bcd-public\",\n               name=f\"fold-{fold}|dim-{CFG.img_size[0]}x{CFG.img_size[1]}|model-{CFG.model_name}\",\n               config=config,\n               anonymous=anonymous,\n               group=CFG.exp_name\n                    )\n    return run\n\ndef log_wandb(fold):\n    \"log best result for error analysis\"\n    valid_df = df.query(\"fold==@fold\").copy().reset_index(drop=True)\n    if CFG.debug:\n        valid_df = valid_df[:min_samples]\n    valid_df['pred'] = oof_pred[fold].reshape(-1)\n    valid_df['diff'] = abs(valid_df.cancer - valid_df.pred)\n    valid_df = valid_df.sort_values(by='diff', ascending=False)\n    \n    noimg_cols  = ['site_id', 'patient_id', 'image_id', 'laterality', 'view', 'age',\n                   'cancer', 'biopsy', 'invasive', 'BIRADS', 'implant', 'density',\n                   'machine_id', 'difficult_negative_case','width','height', 'fold'] + ['pred','diff']\n    \n    # select top and worst 10 cases for each class\n    gradcam_df  = pd.concat((valid_df.groupby('cancer').tail(10), \n                             valid_df.groupby('cancer').head(10)), axis=0, ignore_index=True)\n    gradcam_ds  = build_dataset(gradcam_df.image_path, labels=None, cache=False, batch_size=1,\n                   repeat=False, shuffle=False, augment=False)\n    \n    # create wandb table for upload\n    data = []\n    for idx, img in enumerate(tqdm(gradcam_ds, total=40, desc='gradcam ', position=0, leave=True)):\n        gradcam = get_gradcam(img, model)\n        row = gradcam_df[noimg_cols].iloc[idx].tolist()\n        img = img.numpy()[0]\n        img = (img*255.0).astype('uint8')\n        data+=[[*row, wandb.Image(img), wandb.Image(gradcam)]]\n        if idx<10: # save best ones\n            cv2.imwrite(f'gradcam/fold{fold}_{idx:02d}.png', np.concatenate([img, gradcam], axis=1))\n    wandb_table = wandb.Table(data=data, columns=[*noimg_cols, 'image', 'gradcam'])\n    \n    # log values to wandb\n    best_epoch = np.argmax(history.history['val_pF1_thr'])\n    wandb.log({\n               'best_pF1_batch':oof_val[-1], \n               'best_pF1':pF1,\n               'best_pF1_thr':pF1_thr,\n               'best_auc':auc,\n               'best_epoch':best_epoch,\n               'viz_table':wandb_table,\n              })","metadata":{"execution":{"iopub.status.busy":"2023-03-25T21:57:26.683928Z","iopub.execute_input":"2023-03-25T21:57:26.684209Z","iopub.status.idle":"2023-03-25T21:57:27.511536Z","shell.execute_reply.started":"2023-03-25T21:57:26.684183Z","shell.execute_reply":"2023-03-25T21:57:27.510194Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# get wandb callbacks\ndef get_wb_callbacks(fold):\n    wb_ckpt = wandb.keras.WandbModelCheckpoint(filepath='fold-%i.h5'%fold, \n                                               monitor='val_pF1_thr',\n                                               verbose=CFG.verbose,\n                                               save_best_only=True,\n                                               save_weights_only=False,\n                                               mode='max',)\n    wb_metr = wandb.keras.WandbMetricsLogger()\n    return [wb_ckpt, wb_metr]","metadata":{"execution":{"iopub.status.busy":"2023-03-25T21:57:27.513328Z","iopub.execute_input":"2023-03-25T21:57:27.513667Z","iopub.status.idle":"2023-03-25T21:57:27.51975Z","shell.execute_reply.started":"2023-03-25T21:57:27.513633Z","shell.execute_reply":"2023-03-25T21:57:27.518776Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"oof_pred = []; oof_tar = []; oof_val = []; oof_ids = []; oof_folds = []\npreds = np.zeros((test_df.shape[0],1))\n\nfor fold in np.arange(CFG.folds):\n    \n    # ignore not selected folds\n    if fold not in CFG.selected_folds:\n        continue\n        \n    # init wandb\n    if CFG.wandb:\n        run = wandb_init(fold)\n        wb_callbacks = get_wb_callbacks(fold)\n            \n    # train and valid dataframe\n    train_df = df.query(\"fold!=@fold\")\n    valid_df = df.query(\"fold==@fold\")\n    \n    # upsample cancer data\n    pos_df = train_df.query(\"cancer==1\").sample(frac=CFG.upsample, replace=True)\n    neg_df = train_df.query(\"cancer==0\")\n    train_df = pd.concat([pos_df, neg_df], axis=0, ignore_index=True)\n    \n    # get image_paths and labels\n    train_paths = train_df.image_path.values; train_labels = train_df[CFG.target_col].values.astype(np.float32)\n    valid_paths = valid_df.image_path.values; valid_labels = valid_df[CFG.target_col].values.astype(np.float32)\n    test_paths  = test_df.image_path.values\n    \n    # shuffle train data\n    index = np.arange(len(train_df))\n    np.random.shuffle(index)\n    train_paths  = train_paths[index]\n    train_labels = train_labels[index]\n    \n    # min samples in debug mode\n    min_samples = CFG.batch_size*REPLICAS*2\n    \n    # compute class weight (imbalance)\n    class_weight = compute_class_weight(class_weight='balanced',\n                                        classes=train_df.cancer.unique(),\n                                        y=train_df.cancer.values)\n    class_weight = dict(zip(df.cancer.unique(), class_weight))\n    \n    # for debug model run on small portion\n    if CFG.debug:\n        train_paths = train_paths[:min_samples]; train_labels = train_labels[:min_samples]\n        valid_paths = valid_paths[:min_samples]; valid_labels = valid_labels[:min_samples]\n    \n    # show message\n    print('#'*40); print('#### FOLD: ',fold)\n    print('#### IMAGE_SIZE: (%i, %i) | MODEL_NAME: %s | BATCH_SIZE: %i'%\n          (CFG.img_size[0],CFG.img_size[1],CFG.model_name,CFG.batch_size*REPLICAS))\n    \n    # data stat\n    num_train = len(train_paths)\n    num_valid = len(valid_paths)\n    if CFG.wandb:\n        wandb.log({'num_train':num_train,\n                   'num_valid':num_valid})\n    print('#### NUM_TRAIN: {:,} | NUM_VALID: {:,}'.format(num_train, num_valid))\n    \n    # build model\n    K.clear_session()\n    with strategy.scope():\n        model = build_model(CFG.model_name, dim=CFG.img_size, compile_model=True)\n\n    # build dataset\n    cache = 0\n    train_ds = build_dataset(train_paths, train_labels, cache=cache, batch_size=CFG.batch_size*REPLICAS,\n                   repeat=True, shuffle=True, augment=CFG.augment)\n    val_ds = build_dataset(valid_paths, valid_labels, cache=cache, batch_size=CFG.batch_size*REPLICAS,\n                   repeat=False, shuffle=False, augment=False)\n    print('#'*40)   \n    \n    # callbacks\n    callbacks = []\n    ## save best model after each fold\n    sv = tf.keras.callbacks.ModelCheckpoint(\n        'fold-%i.h5'%fold, monitor='val_pF1_thr', verbose=CFG.verbose, save_best_only=True,\n        save_weights_only=False, mode='max', save_freq='epoch')\n    callbacks +=[sv]\n    ## lr-scheduler\n    callbacks += [get_lr_callback(CFG.batch_size)]\n    ## wandb callbacks\n    if CFG.wandb:\n        callbacks += wb_callbacks\n        \n    # train\n    print('Training...')\n    history = model.fit(\n        train_ds, \n        epochs=CFG.epochs if not CFG.debug else 2, \n        callbacks = callbacks, \n        steps_per_epoch=len(train_paths)/CFG.batch_size//REPLICAS,\n        validation_data=val_ds, \n        class_weight = class_weight if CFG.use_cw else None,\n        verbose=CFG.verbose\n    )\n    \n    # load best model for inference\n    print('Loading best model...')\n    model.load_weights('fold-%i.h5'%fold)  \n    \n    # predict on valid data\n    print('Predicting OOF with TTA...')\n    ds_valid = build_dataset(valid_paths, labels=None, cache=False, batch_size=CFG.batch_size*REPLICAS*2,\n                   repeat=True, shuffle=False, augment=CFG.tta>1)\n    ct_valid = len(valid_paths); STEPS = CFG.tta * ct_valid/CFG.batch_size/2/REPLICAS\n    pred = model.predict(ds_valid,steps=STEPS,verbose=CFG.verbose)[:CFG.tta*ct_valid,] \n    oof_pred.append(np.mean(pred.reshape((CFG.tta, ct_valid,-1)),axis=0))                 \n    \n    # get id and target for valid data\n    oof_tar.append(valid_df[CFG.target_col].values[:(min_samples if CFG.debug else len(valid_df))])\n    oof_folds.append(np.ones_like(oof_tar[-1],dtype='int8')*fold)\n    oof_ids.append(valid_df.image_path.tolist()[:(min_samples if CFG.debug else len(valid_df))])\n    \n#     # predict on test data\n#     print('Predicting Test...')\n#     ds_test = build_dataset(test_paths, labels=None, cache=False, \n#                     batch_size=(CFG.batch_size*2 if len(test_df)>4 else 1)*REPLICAS,\n#                    repeat=True, shuffle=False, augment=CFG.tta>1)\n#     ct_test = len(test_paths); STEPS = 1 if len(test_df)<=4 else (CFG.tta * ct_test/CFG.batch_size/2/REPLICAS)\n#     pred = model.predict(ds_test,steps=STEPS,verbose=CFG.verbose)[:CFG.tta*ct_test,] \n#     preds[:ct_test, :] += np.mean(pred.reshape((CFG.tta, ct_test,-1)),axis=0) / CFG.folds # not meaningful for DIBUG = True\n    \n    # store best results\n    y_true = oof_tar[-1].astype(np.float32); y_pred = oof_pred[-1]\n    pF1 = pfbeta(y_true, y_pred)\n    pF1_thr = pfbeta_thr(y_true, y_pred).numpy() # tf metric\n    auc = roc_auc_score(y_true, y_pred)\n    oof_val.append(np.max(history.history['val_pF1'] ))\n    print('>>>> FOLD %i OOF pF1_batch = %.3f, pF1 = %.3f, pF1_thr = %.3f, auc = %.3f\\n'%(fold,oof_val[-1], \n                                                                                         pF1, \n                                                                                         pF1_thr,\n                                                                                         auc))  # pF1_batch => pF1 batchwise canculated then aggregated\n    \n    # log best result on wandb & plot\n    if CFG.wandb:\n        log_wandb(fold) # log\n        wandb.run.finish() # finish the run\n        display(ipd.IFrame(run.url, width=1080, height=720)) # show wandb dashboard","metadata":{"execution":{"iopub.status.busy":"2023-03-25T21:57:27.521077Z","iopub.execute_input":"2023-03-25T21:57:27.521542Z","iopub.status.idle":"2023-03-26T03:18:42.750614Z","shell.execute_reply.started":"2023-03-25T21:57:27.521514Z","shell.execute_reply":"2023-03-26T03:18:42.749566Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from mpl_toolkits.axes_grid1 import ImageGrid\n\nimgs = [cv2.imread(path) for path in glob('/kaggle/working/gradcam/*')[:8]]\nfig = plt.figure(figsize=(20., 15.))\ngrid = ImageGrid(fig, 111,  # similar to subplot(111)\n                 nrows_ncols=(2, 4),  # creates 2x2 grid of axes\n                 axes_pad=0.25,  # pad between axes in inch.\n                 )\n\nfor ax, im in zip(grid, imgs):\n    # Iterating over the grid returns the Axes.\n    ax.imshow(im)\n    ax.set_xticks([])\n    ax.set_yticks([])\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-03-26T03:18:42.756308Z","iopub.execute_input":"2023-03-26T03:18:42.756589Z","iopub.status.idle":"2023-03-26T03:18:45.012197Z","shell.execute_reply.started":"2023-03-26T03:18:42.756562Z","shell.execute_reply":"2023-03-26T03:18:45.010865Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# overall oof pF1\noof = np.concatenate(oof_pred); true = np.concatenate(oof_tar);\nids = np.concatenate(oof_ids); folds = np.concatenate(oof_folds)\npF1 = pfbeta(true.astype(np.float32),oof)\nprint('Overall OOF pF1 = %.3f'%pF1)","metadata":{"execution":{"iopub.status.busy":"2023-03-26T03:18:45.014047Z","iopub.execute_input":"2023-03-26T03:18:45.014355Z","iopub.status.idle":"2023-03-26T03:18:45.036683Z","shell.execute_reply.started":"2023-03-26T03:18:45.014328Z","shell.execute_reply":"2023-03-26T03:18:45.03547Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# save oof\ncolumns = ['image_path', 'true', 'pred']\ndf_oof = pd.DataFrame(np.concatenate([ids[:,None], true, oof], axis=1), columns=columns)\ndf_oof = df_oof.merge(df, on=['image_path'], how='left') # merge with train data\ndf_oof.to_csv('oof.csv',index=False)\ndf_oof.head(2)","metadata":{"execution":{"iopub.status.busy":"2023-03-26T03:18:45.038099Z","iopub.execute_input":"2023-03-26T03:18:45.038388Z","iopub.status.idle":"2023-03-26T03:18:45.531184Z","shell.execute_reply.started":"2023-03-26T03:18:45.038361Z","shell.execute_reply":"2023-03-26T03:18:45.529979Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# calculate pf1 for multiple thresholds\nthrs = np.arange(0,1,0.05)\nscores = []\nfor thr in tqdm(thrs):\n    scores+=[pfbeta(df_oof.true.astype('float32'), df_oof.pred.astype('float32')>thr)]\n    \n# get best thr for max pF1\nbest_score_idx = np.argmax(scores)\nbest_score = np.max(scores)\nbest_thr = thrs[best_score_idx]\nprint(f'\\n## MAX pF1 = {best_score: 0.3f} @ {best_thr:0.3f}\\n')\n\n# plot thr vs pF1 graph\nfig, ax = plt.subplots(figsize=(8,4))\nax.fill_between(thrs, scores,\n                color='red', alpha=0.3, )\nax.plot(thrs, scores, '-ok');\nax.axvline(x=best_thr, color='blue', ls='--')\nax.plot(best_thr, best_score, color='blue', marker='o', markersize=12)\nax.set_xlabel('Threshold');\nax.set_ylabel('pF1');\nax.set_title('Threshold Vs pF1');","metadata":{"execution":{"iopub.status.busy":"2023-03-26T03:18:45.532468Z","iopub.execute_input":"2023-03-26T03:18:45.532831Z","iopub.status.idle":"2023-03-26T03:18:45.993485Z","shell.execute_reply.started":"2023-03-26T03:18:45.532796Z","shell.execute_reply":"2023-03-26T03:18:45.992313Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import seaborn as sns\nsns.set(style='dark')\n\nplt.figure(figsize=(10*2,6))\n\nplt.subplot(1, 2, 1)\nsns.kdeplot(x=train_df[CFG.target_col[0]], color='b',fill=True);\nsns.kdeplot(x=df_oof.pred.values.astype('float32'), color='r',fill=True);\nplt.grid('ON')\nplt.xlabel(CFG.target_col[0]);plt.ylabel('freq');plt.title('KDE')\nplt.legend(['train', 'oof'])\n\nplt.subplot(1, 2, 2)\nsns.histplot(x=train_df[CFG.target_col[0]], color='b');\nsns.histplot(x=df_oof.pred.values.astype('float32'), color='r');\nplt.grid('ON')\nplt.xlabel(CFG.target_col[0]);plt.ylabel('freq');plt.title('Histogram')\nplt.legend(['train', 'oof'])\n\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-03-26T03:18:45.994837Z","iopub.execute_input":"2023-03-26T03:18:45.995691Z","iopub.status.idle":"2023-03-26T03:18:47.739775Z","shell.execute_reply.started":"2023-03-26T03:18:45.995657Z","shell.execute_reply":"2023-03-26T03:18:47.738516Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#!rm -r /kaggle/working/wandb","metadata":{"execution":{"iopub.status.busy":"2023-03-26T03:18:47.741102Z","iopub.execute_input":"2023-03-26T03:18:47.741424Z","iopub.status.idle":"2023-03-26T03:18:50.617172Z","shell.execute_reply.started":"2023-03-26T03:18:47.741394Z","shell.execute_reply":"2023-03-26T03:18:50.615661Z"},"trusted":true},"execution_count":null,"outputs":[]}]}