{"cells":[{"metadata":{},"cell_type":"markdown","source":"<h2> Catheter and Line Position Prediction </h2>\n<hr>\n\n- [1. Overview](#1)\n- [2. Exploratory Data Analysis](#2)\n    * [2.1. Distributions](#3)   \n        * [CVC - Normal](#4)\n        * [CVC - Borderline](#5)\n        * [CVC - Abnormal](#6)\n        * [ETT - Normal](#7)\n        * [ETT - Borderline](#8)\n        * [ETT - Abnormal](#9)\n        * [NGT - Normal](#10)\n        * [NGT - Borderline](#11)\n        * [NGT - Abnormal](#12)\n        * [NGT - Incompletely Imaged](#13)\n        * [Swan Ganz Catheter Present](#14)\n- [3. Model](#15)"},{"metadata":{},"cell_type":"markdown","source":"## <span id=\"1\"></span> **1. Overview**"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport plotly.express as px\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\n\nimport os\nimport ast\nimport cv2\nimport random","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"BASE_DIR = \"../input/ranzcr-clip-catheter-line-classification/\"\nprint(os.listdir(BASE_DIR))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Files\n- **train.csv** - contains image IDs, binary labels, and patient IDs.\n- **sample_submission.csv** - a sample submission file in the correct format\n- **test** - test images\n- **train** - training images\n"},{"metadata":{},"cell_type":"markdown","source":"## <span id=\"2\"></span> **2. Exploratory Data Analysis**\nMostly utilized from <a href=\"https://www.kaggle.com/ihelon/catheter-position-exploratory-data-analysis\">Yaroslav</a>'s EDA notebook: https://www.kaggle.com/ihelon/catheter-position-exploratory-data-analysis"},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train = pd.read_csv(os.path.join(BASE_DIR, \"train.csv\"), index_col=0)\ndf_train.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### <span id=\"3\"></span> Distributions"},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"df_tmp = df_train.iloc[:, :-1].sum()\ndf_tmp = df_tmp.sort_values(ascending=True)\n\nfig = px.bar(x=df_tmp.values, y=df_tmp.index)\n\nfig.update_layout(\n        title = {\"text\": \"Distribution of Labels\", \"font_size\" :18, \"x\": 0.5},\n        xaxis_title=\"Count\",\n        yaxis_title=\"Label\",\n    )\n    \nfig.update_traces(\n    marker_color=px.colors.qualitative.Prism\n)\n\n\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"def show_values_on_bars(axs):\n    def _show_on_single_plot(ax):        \n        for p in ax.patches:\n            _x = p.get_x() + p.get_width() / 2\n            _y = p.get_y() + p.get_height()\n            value = '{:.0f}'.format(p.get_height())\n            ax.text(_x, _y, value, ha=\"center\") \n\n    if isinstance(axs, np.ndarray):\n        for idx, ax in np.ndenumerate(axs):\n            _show_on_single_plot(ax)\n    else:\n        _show_on_single_plot(axs)","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"f, axes = plt.subplots(3,3,figsize=(14,14))\n\n_palette = \"tab10\"\n\n# CVC\n\nsns.countplot(df_train['CVC - Normal'], ax = axes[0,0], palette=_palette)\naxes[0,0].set_xlabel('CVC - Normal', fontsize=14)\naxes[0,0].set_ylabel('Count', fontsize=14)\naxes[0,0].yaxis.tick_left()\n\nsns.countplot(df_train['CVC - Borderline'], ax = axes[0,1], palette=_palette)\naxes[0,1].set_xlabel('CVC - Borderline', fontsize=14)\naxes[0,1].set_ylabel('', fontsize=14)\naxes[0,1].yaxis.set_label_position(\"right\")\naxes[0,1].yaxis.tick_left()\n\nsns.countplot(df_train['CVC - Abnormal'], ax = axes[0,2], palette=_palette)\naxes[0,2].set_xlabel('CVC - Abnormal', fontsize=14)\naxes[0,2].set_ylabel('', fontsize=14)\naxes[0,2].yaxis.set_label_position(\"right\")\naxes[0,2].yaxis.tick_left()\n\n# ETT\n\nsns.countplot(df_train['ETT - Normal'], ax = axes[1,0], palette=_palette)\naxes[1,0].set_xlabel('ETT - Normal', fontsize=14)\naxes[1,0].set_ylabel('Count', fontsize=14)\naxes[1,0].yaxis.tick_left()\n\nsns.countplot(df_train['ETT - Borderline'], ax = axes[1,1], palette=_palette)\naxes[1,1].set_xlabel('ETT - Borderline', fontsize=14)\naxes[1,1].set_ylabel('', fontsize=14)\naxes[1,1].yaxis.set_label_position(\"right\")\naxes[1,1].yaxis.tick_left()\n\nsns.countplot(df_train['ETT - Abnormal'], ax = axes[1,2], palette=_palette)\naxes[1,2].set_xlabel('ETT - Abnormal', fontsize=14)\naxes[1,2].set_ylabel('', fontsize=14)\naxes[1,2].yaxis.set_label_position(\"right\")\naxes[1,2].yaxis.tick_left()\n\nshow_values_on_bars(axes)\n\n# NGT\n\nsns.countplot(df_train['NGT - Normal'], ax = axes[2,0], palette=_palette)\naxes[2,0].set_xlabel('NGT - Normal', fontsize=14)\naxes[2,0].set_ylabel('Count', fontsize=14)\naxes[2,0].yaxis.tick_left()\n\nsns.countplot(df_train['NGT - Borderline'], ax = axes[2,1], palette=_palette)\naxes[2,1].set_xlabel('NGT - Borderline', fontsize=14)\naxes[2,1].set_ylabel('', fontsize=14)\naxes[2,1].yaxis.set_label_position(\"right\")\naxes[2,1].yaxis.tick_left()\n\nsns.countplot(df_train['NGT - Abnormal'], ax = axes[2,2], palette=_palette)\naxes[2,2].set_xlabel('NGT - Abnormal', fontsize=14)\naxes[2,2].set_ylabel('', fontsize=14)\naxes[2,2].yaxis.set_label_position(\"right\")\naxes[2,2].yaxis.tick_left()\n\nshow_values_on_bars(axes)\n\nplt.show()\n","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"f, axes = plt.subplots(1,2,figsize=(14,4))\n\n_palette = \"tab10\"\n\n# \n\nsns.countplot(df_train['NGT - Incompletely Imaged'], ax = axes[0], palette=_palette)\naxes[0].set_xlabel('NGT - Incompletely Imaged', fontsize=14)\naxes[0].set_ylabel('Count', fontsize=14)\naxes[0].yaxis.tick_left()\n\nsns.countplot(df_train['Swan Ganz Catheter Present'], ax = axes[1], palette=_palette)\naxes[1].set_xlabel('Swan Ganz Catheter Present', fontsize=14)\naxes[1].set_ylabel('', fontsize=14)\naxes[1].yaxis.set_label_position(\"right\")\naxes[1].yaxis.tick_left()\n\nshow_values_on_bars(axes)\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"There are {0} unique patients.\".format(df_train[\"PatientID\"].nunique()))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"plt.figure(figsize=(16, 6))\ndf_tmp = df_train[\"PatientID\"].value_counts()\nsns.countplot(x=df_tmp.values)\nplt.xticks(fontsize=12, rotation=90)\nplt.yticks(fontsize=14)\nplt.xlabel(\"Number of observations\", fontsize=15)\nplt.ylabel(\"Number of patients\", fontsize=15)\nplt.title(\"Distribution of observations by PatientID\", fontsize=16);","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_annot = pd.read_csv(os.path.join(BASE_DIR, \"train_annotations.csv\"))\ndf_annot.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def plot_image_with_annotations(row_ind):\n    row = df_annot.iloc[row_ind]\n    image_path = os.path.join(BASE_DIR, \"train\", row[\"StudyInstanceUID\"] + \".jpg\")\n    label = row[\"label\"]\n    data = np.array(ast.literal_eval(row[\"data\"]))\n    \n    plt.figure(figsize=(16, 5))\n    image = cv2.imread(image_path)\n    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n    plt.subplot(1, 2, 1)\n    plt.imshow(image)\n    plt.subplot(1, 2, 2)\n    plt.imshow(image)\n    plt.scatter(data[:, 0], data[:, 1])\n    \n    plt.suptitle(label, fontsize=15)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_image_with_annotations(8)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"# Helpfer functions\n\ndef visualize_batch(image_ids):\n    plt.figure(figsize=(16, 10))\n    \n    for ind, image_id in enumerate(image_ids):\n        plt.subplot(2, 3, ind + 1)\n        image = cv2.imread(os.path.join(BASE_DIR, \"train\", f\"{image_id}.jpg\"))\n        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n        plt.imshow(image)\n        plt.axis(\"off\")\n    \n    plt.show()\n\n    \ndef plot_statistics(df, col):\n    plt.figure(figsize=(16, 2))\n    sns.countplot(y=df[col])\n    \n    plt.xticks(fontsize=12)\n    plt.yticks(fontsize=12)\n    plt.xlabel(\"Number of observations\", fontsize=15)\n    plt.ylabel(col, fontsize=15)\n    plt.title(f\"Distribution of {col}\", fontsize=16);\n    \n    plt.show()    \n\ndef process_class(col_name):\n    plot_statistics(df_train, col_name)\n    tmp_df = df_train[df_train[col_name] == 1]\n    visualize_batch(random.sample(tmp_df.index.tolist(), 6))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### <span id=\"4\"></span> CVC - Normal"},{"metadata":{"trusted":true},"cell_type":"code","source":"process_class(\"CVC - Normal\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### <span id=\"5\"></span> CVC - Borderline"},{"metadata":{"trusted":true},"cell_type":"code","source":"process_class(\"CVC - Borderline\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### <span id=\"6\"></span> CVC - Abnormal"},{"metadata":{"trusted":true},"cell_type":"code","source":"process_class(\"CVC - Abnormal\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### <span id=\"7\"></span> ETT - Normal"},{"metadata":{"trusted":true},"cell_type":"code","source":"process_class(\"ETT - Normal\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### <span id=\"8\"></span> ETT - Borderline"},{"metadata":{"trusted":true},"cell_type":"code","source":"process_class(\"ETT - Borderline\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### <span id=\"9\"></span> ETT - Abnormal"},{"metadata":{"trusted":true},"cell_type":"code","source":"process_class(\"ETT - Abnormal\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### <span id=\"10\"></span> NGT - Normal"},{"metadata":{"trusted":true},"cell_type":"code","source":"process_class(\"NGT - Normal\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### <span id=\"11\"></span> NGT - Borderline"},{"metadata":{"trusted":true},"cell_type":"code","source":"process_class(\"NGT - Borderline\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### <span id=\"12\"></span> NGT - Abnormal"},{"metadata":{"trusted":true},"cell_type":"code","source":"process_class(\"NGT - Abnormal\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### <span id=\"13\"></span> NGT - Incompletely Imaged"},{"metadata":{"trusted":true},"cell_type":"code","source":"process_class(\"NGT - Incompletely Imaged\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### <span id=\"14\"></span> Swang Ganz Catheter Present"},{"metadata":{"trusted":true},"cell_type":"code","source":"process_class(\"Swan Ganz Catheter Present\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## <span id=\"15\"></span> **3. Model**\nCompletely utilized from <a href=\"https://www.kaggle.com/xhlulu\">Xing Han</a>'s GPU starter notebook: https://www.kaggle.com/xhlulu/ranzcr-efficientnet-gpu-starter-train-submit"},{"metadata":{"trusted":true},"cell_type":"code","source":"# import efficientnet.tfkeras as efn\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 tensorflow.keras.applications.efficientnet as efn","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"def auto_select_accelerator():\n    \"\"\"\n    Reference: \n        * https://www.kaggle.com/mgornergoogle/getting-started-with-100-flowers-on-tpu\n        * https://www.kaggle.com/xhlulu/ranzcr-efficientnet-tpu-training\n    \"\"\"\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        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":{"trusted":true},"cell_type":"code","source":"COMPETITION_NAME = \"ranzcr-clip-catheter-line-classification\"\nstrategy = auto_select_accelerator()\nBATCH_SIZE = strategy.num_replicas_in_sync * 16\n# GCS_DS_PATH = KaggleDatasets().get_gcs_path(COMPETITION_NAME)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"load_dir = f\"/kaggle/input/{COMPETITION_NAME}/\"\ndf = pd.read_csv(load_dir + 'train.csv')\npaths = load_dir + \"train/\" + df['StudyInstanceUID'] + '.jpg'\n\nsub_df = pd.read_csv(load_dir + 'sample_submission.csv')\ntest_paths = load_dir + \"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\n(\n    train_paths, valid_paths, \n    train_labels, valid_labels\n) = train_test_split(paths, labels, test_size=0.2, random_state=42)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Build the tensorflow datasets\nIMSIZES = (224, 240, 260, 300, 380, 456, 528, 600)\n# index i corresponds to b-i\nsize = IMSIZES[2]\n\ndecoder = build_decoder(with_labels=True, target_size=(size, size))\ntest_decoder = build_decoder(with_labels=False, target_size=(size, size))\n\n# Build the tensorflow datasets\ndtrain = build_dataset(\n    train_paths, train_labels, bsize=BATCH_SIZE, \n    cache_dir='/kaggle/tf_cache', decode_fn=decoder\n)\n\ndvalid = build_dataset(\n    valid_paths, valid_labels, bsize=BATCH_SIZE, \n    repeat=False, shuffle=False, augment=False, \n    cache_dir='/kaggle/tf_cache', decode_fn=decoder\n)\n\ndtest = build_dataset(\n    test_paths, bsize=BATCH_SIZE, repeat=False, \n    shuffle=False, augment=False, cache=False, \n    decode_fn=test_decoder\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model_path = '../input/tfkeras-efficientnet-weights/efficientnetb2_notop.h5'  # imagenet\nn_labels = labels.shape[1]\n\nwith strategy.scope():\n    model = tf.keras.Sequential([\n        efn.EfficientNetB2(\n            input_shape=(size, size, 3),\n            weights=model_path,\n            include_top=False,\n            drop_connect_rate=0.5),\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(n_labels, activation='sigmoid')\n    ])\n    model.compile(\n        optimizer='adam',\n        loss='binary_crossentropy',\n        metrics=[tf.keras.metrics.AUC(multi_label=True)])\n    model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# ############### Train the model ###############\nsteps_per_epoch = train_paths.shape[0] // BATCH_SIZE\ncheckpoint = tf.keras.callbacks.ModelCheckpoint(\n    'model.h5', save_best_only=True, monitor='val_auc', mode='max')\nlr_reducer = tf.keras.callbacks.ReduceLROnPlateau(\n    monitor=\"val_auc\", patience=3, min_lr=1e-6, mode='max')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit(\n    dtrain, \n    epochs=20,\n    verbose=1,\n    callbacks=[checkpoint, lr_reducer],\n    steps_per_epoch=steps_per_epoch,\n    validation_data=dvalid)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.load_weights('model.h5')","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":"sub_df[label_cols] = model.predict(dtest, verbose=1)\nsub_df.to_csv('submission.csv', index=False)\n\nsub_df.head()","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}