{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install efficientnet -q","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import os\nimport numpy as np\nimport pandas as pd\nfrom kaggle_datasets import KaggleDatasets\nfrom sklearn.model_selection import train_test_split\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import KFold\nimport efficientnet.tfkeras as efn","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Helper functions"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"def auto_select_accelerator():\n    try:\n        tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n        tf.config.experimental_connect_to_cluster(tpu)\n        tf.tpu.experimental.initialize_tpu_system(tpu)\n        strategy = tf.distribute.experimental.TPUStrategy(tpu)\n        print(\"Running on TPU:\", tpu.master())\n    except ValueError:\n        strategy = tf.distribute.get_strategy()\n    print(f\"Running on {strategy.num_replicas_in_sync} replicas\")\n    \n    return strategy\n\n\ndef build_decoder(with_labels=True, target_size=(256, 256), ext='jpg'):\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.cast(img, tf.float32) / 255.0\n        img = tf.image.resize(img, target_size)\n\n        return img\n    \n    def decode_with_labels(path, label):\n        return decode(path), label\n    \n    return decode_with_labels if with_labels else decode\n\n\ndef build_augmenter(with_labels=True):\n    def augment(img):\n        img = tf.image.random_flip_left_right(img)\n        img = tf.image.random_flip_up_down(img)\n        img = tf.image.random_saturation(img, 0.7, 1.3)\n        img = tf.image.random_contrast(img, 0.8, 1.2)\n        img = tf.image.random_brightness(img, 0.1)\n        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, bsize=32, cache=True,\n                  decode_fn=None, augment_fn=None,\n                  augment=True, repeat=True, shuffle=1024, \n                  cache_dir=\"\"):\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    dset = tf.data.Dataset.from_tensor_slices(slices)\n    dset = dset.map(decode_fn, num_parallel_calls=AUTO)\n    dset = dset.cache(cache_dir) if cache else dset\n    dset = dset.map(augment_fn, num_parallel_calls=AUTO) if augment else dset\n    dset = dset.repeat() if repeat else dset\n    dset = dset.shuffle(shuffle) if shuffle else dset\n    dset = dset.batch(bsize).prefetch(AUTO)\n    \n    return dset","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Variables and configurations"},{"metadata":{"trusted":true},"cell_type":"code","source":"COMPETITION_NAME = \"ranzcr-clip-catheter-line-classification\"\nGCS_DS_PATH = KaggleDatasets().get_gcs_path(COMPETITION_NAME)\nprint(GCS_DS_PATH)\nstrategy = auto_select_accelerator()\nBATCH_SIZE = strategy.num_replicas_in_sync * 16","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Preparing dataset"},{"metadata":{},"cell_type":"markdown","source":"### Loading and preprocess CSVs"},{"metadata":{"trusted":true},"cell_type":"code","source":"load_dir = f\"/kaggle/input/{COMPETITION_NAME}/\"\ndf = pd.read_csv(load_dir + 'train.csv')\n\n# paths = load_dir + \"train/\" + df['StudyInstanceUID'] + '.jpg'\npaths = GCS_DS_PATH + \"/train/\" + df['StudyInstanceUID'] + '.jpg'\n\nsub_df = pd.read_csv(load_dir + 'sample_submission.csv')\n\n# test_paths = load_dir + \"test/\" + sub_df['StudyInstanceUID'] + '.jpg'\ntest_paths = GCS_DS_PATH + \"/test/\" + sub_df['StudyInstanceUID'] + '.jpg'\n\n# Get the multi-labels\nlabel_cols = sub_df.columns[1:]\nlabels = df[label_cols].values","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Train test split\nrandom_state = 2020\nfold_nums = 0\nskf = KFold(n_splits=5, random_state=random_state, shuffle=True)\nfor fold, (train_id, test_id) in enumerate(skf.split(paths , labels)):\n    if fold == fold_nums:\n        train_paths = paths[train_id]\n        valid_paths = paths[test_id]\n        train_labels = labels[train_id]\n        valid_labels = labels[test_id]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Build the tensorflow datasets\nIMSIZE = (224, 240, 260, 300, 380, 456, 528, 600)\nimg_size = IMSIZE[7]\ndecoder = build_decoder(with_labels=True, target_size=(img_size, img_size))\ntest_decoder = build_decoder(with_labels=False, target_size=(img_size, img_size))\n\ntrain_dataset = build_dataset(\n    train_paths, train_labels, bsize=BATCH_SIZE, decode_fn=decoder\n)\n\nvalid_dataset = build_dataset(\n    valid_paths, valid_labels, bsize=BATCH_SIZE, decode_fn=decoder,\n    repeat=False, shuffle=False, augment=False\n)\n\ntest_dataset = build_dataset(\n    test_paths, cache=False, bsize=BATCH_SIZE, decode_fn=test_decoder,\n    repeat=False, shuffle=False, augment=False\n)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Modeling"},{"metadata":{"trusted":true},"cell_type":"code","source":"\ncfg = dict(\n    net_count         =  range(6,8),\n    epochs            =  18,\n    label_smooth_fac  =   0.005,   \n    LR_START          =   0.000005,\n    LR_MAX            =   0.000200,\n    LR_MIN            =   0.00001,\n    LR_RAMPUP_EPOCHS  =   5,\n    LR_SUSTAIN_EPOCHS =   0,\n    LR_EXP_DECAY      =   0.8,\n    tta_steps         =   25,\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_lr_callback(cfg):\n    lr_start   = cfg['LR_START']\n    lr_max     = cfg['LR_MAX'] * strategy.num_replicas_in_sync\n    lr_min     = cfg['LR_MIN']\n    lr_ramp_ep = cfg['LR_RAMPUP_EPOCHS']\n    lr_sus_ep  = cfg['LR_SUSTAIN_EPOCHS']\n    lr_decay   = cfg['LR_EXP_DECAY']\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        else:\n            lr = (lr_max - lr_min) * lr_decay**(epoch - lr_ramp_ep - lr_sus_ep) + lr_min\n            \n        return lr\n\n    lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=False)\n    return lr_callback","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nlr_start   = cfg['LR_START']\nlr_max     = cfg['LR_MAX'] * 16\nlr_min     = cfg['LR_MIN']\nlr_ramp_ep = cfg['LR_RAMPUP_EPOCHS']\nlr_sus_ep  = cfg['LR_SUSTAIN_EPOCHS']\nlr_decay   = cfg['LR_EXP_DECAY']\n\ndef 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    else:\n        lr = (lr_max - lr_min) * lr_decay**(epoch - lr_ramp_ep - lr_sus_ep) + lr_min\n\n    return lr\n\nlr_epochs = [lrfn(ep) for ep in range(cfg['epochs'])]\nplt.plot(lr_epochs)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\ndef get_model(cfg):\n    model_input = tf.keras.Input(shape=(img_size, img_size, 3), name='imgIn')\n\n    dummy = tf.keras.layers.Lambda(lambda x:x)(model_input)\n    \n    outputs = []    \n    for i in cfg['net_count']:\n        constructor = getattr(efn, f'EfficientNetB{i}')\n        \n        x = constructor(include_top=False, weights='noisy-student', \n                        input_shape=(img_size, img_size, 3),  pooling='avg')(dummy)\n        x = tf.keras.layers.Dense(n_labels, activation='sigmoid')(x)\n        outputs.append(x)\n        \n    model = tf.keras.Model(model_input, outputs, name='aNetwork')\n    model.summary()\n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"n_labels = labels.shape[1]\nwith strategy.scope():\n    model = get_model(cfg)\n\n    losses = [tf.keras.losses.BinaryCrossentropy(label_smoothing = cfg['label_smooth_fac'])\n              for i in cfg['net_count']]\n\n    model.compile(\n        optimizer='adam',\n        loss='binary_crossentropy',\n        metrics=[tf.keras.metrics.AUC(multi_label=True)])\n\n    model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"steps_per_epoch = train_paths.shape[0] // BATCH_SIZE\ncheckpoint = tf.keras.callbacks.ModelCheckpoint( 'model.h5', save_best_only=True,monitor='val_auc', mode='max')\nlr_reducer = tf.keras.callbacks.ReduceLROnPlateau(monitor=\"val_auc\", patience=3, min_lr=1e-6, mode='max')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_dataset     = train_dataset.map(lambda img, label: (img, tuple([label] * len(cfg['net_count']))))\nhistory = model.fit(\n    train_dataset, \n    epochs=20,\n    verbose=2,\n    callbacks=[checkpoint, get_lr_callback(cfg)],\n    steps_per_epoch=steps_per_epoch,\n    validation_data=valid_dataset)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Save history"},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save_weights('easy_checkpoint.h5')\nprint(\"success save checkpoint!\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"hist_df = pd.DataFrame(history.history)\nhist_df.to_csv('history.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cfg['batch_size'] = 256\n\ncnt_test   = count_data_items(files_test)\nsteps      = cnt_test / (cfg['batch_size'] * REPLICAS) * cfg['tta_steps']\nds_testAug = get_dataset(files_test, CFG, augment=True, repeat=True, \n                         labeled=False, return_image_names=False)\n\nprobs = model.predict(ds_testAug, verbose=1, steps=steps)\n\nprobs = np.stack(probs)\nprobs = probs[:,:cnt_test * cfg['tta_steps']]\nprobs = np.stack(np.split(probs, cfg['tta_steps'], axis=1), axis=1)\nprobs = np.mean(probs, axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ds = get_dataset(files_test, CFG, augment=False, repeat=False, \n                 labeled=False, return_image_names=True)\n\nimage_names = np.array([img_name.numpy().decode(\"utf-8\") \n                        for img, img_name in iter(ds.unbatch())])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for i in range(cfg[\"net_count\"]):\n    submission = pd.DataFrame(dict(\n        image_name = image_names,\n        target     = probs[i,:,0]))\n\n    submission = submission.sort_values('image_name') \n    submission.to_csv(f'submission_model_{i}.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.DataFrame(dict(\n    image_name = image_names,\n    target     = np.mean(probs[:,:,0], axis=0)))\n\nsubmission = submission.sort_values('image_name') \nsubmission.to_csv('submission_models_blended.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!ls -l .","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}