{"cells":[{"metadata":{},"cell_type":"markdown","source":"Let's try using a transfer learning model that was specifically **trained on chest x-ray images! **\n\n#### CheXNet - Keras\n\n* CheXNet is based on Densenet 121, which was pretrained on imagenet, before being finetuned on ChestX-ray14, which contained 112,120 frontal view greyscale X-rays from 30,805 patients. \n    * For more about CheXnet, check out the original article or github with the trained model: https://github.com/brucechou1983/CheXNet-Keras\n* Loading the model naively won't work, but I provide a workaround here.\n* Keras - for ease of use! :) \n    \n* Data loading code copied from the kernel [Baseline: Transfer Learning+RandomForest](https://www.kaggle.com/titericz/baseline-transfer-learning-randomforest-gpu/) \n* Transfer learning best practices are* **not** yet applied here* - a frozen base model and tuning of the output layer, followed by unfreezing all layers and gentler finetuning.\n    * Removing the added dense layer at the end may improve things (just be sure to handle the logits)\n* Note that this is just a starter kernel - there's lots more that could be done to improve the model, the transfer learning, etc' \n* In this simple notebook we'll finetune chexnet, and see how it does vs imagenet pretrained models \n* For static feature extraction, see: [danofer: ranzcr-chexnet-x-ray-transfer-learning-extractor](https://www.kaggle.com/danofer/ranzcr-chexnet-x-ray-transfer-learning-extractor)\n\n\n   "},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import os\n\n# 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\n# import tensorflow.keras.applications.efficientnet as efn\n\n\nimport tensorflow as tf\nfrom tensorflow.keras import Sequential\nfrom keras.models import Model\nfrom tensorflow.keras.utils import plot_model\nfrom tensorflow.keras.applications import densenet\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.layers import GlobalAveragePooling2D, GlobalMaxPooling2D, AveragePooling2D","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## size of the pooled output layer from the model\nPOOLED_OUTPUT_SIZE = 1024 # 1024 for densenet 121, 2048 for mobilenet? \n\nchexnet_weights_path = \"../input/chexnet-keras-weights/brucechou1983_CheXNet_Keras_0.3.0_weights.h5\"\n\n# FAST_RUN = False # use only a few rows, for fast debugging","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"### enable mixed precision - may affect results, but should speed things up\n#### https://www.tensorflow.org/guide/mixed_precision\nimport tensorflow as tf\n\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.mixed_precision import experimental as mixed_precision\n\npolicy = mixed_precision.Policy('mixed_float16')\nmixed_precision.set_policy(policy)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Helper functions"},{"metadata":{},"cell_type":"markdown","source":"The following functions are hidden:\n```python\nauto_select_accelerator()\n\nbuild_decoder(with_labels=True, target_size=(256, 256), ext='jpg')\n\nbuild_augmenter(with_labels=True)\n\nbuild_dataset(paths, labels=None, bsize=64, cache=True,\n              decode_fn=None, augment_fn=None,\n              augment=True, repeat=True, shuffle=1024, \n              cache_dir=\"\")\n```\n\nUnhide below to see:"},{"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=(300, 300), 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## todo: more augmentations, e.g. rotation, albumention - https://www.kaggle.com/bjoernholzhauer/inference-for-trained-fastai-efficientnet-b4\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":{},"cell_type":"markdown","source":"## Variables and configurations"},{"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 * 32 #16 was 16 - in kernels env, without mixed precision\n# GCS_DS_PATH = KaggleDatasets().get_gcs_path(COMPETITION_NAME)","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')\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.1, random_state=42)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Results are notably better with larger image sizes, but this means slower training and will run into the GPU/kernel time limit! "},{"metadata":{"trusted":true},"cell_type":"code","source":"# Build the tensorflow datasets\nIMSIZES = (224, 240, 260, 300, 380, 456, 528, 600) # (224, 240, 260, 300, 380, 456, 528, 600)\n# index i corresponds to b-i\nsize = IMSIZES[3] # [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 - we don't need to define batch size when using this\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":{},"cell_type":"markdown","source":"## Modeling"},{"metadata":{"trusted":true},"cell_type":"code","source":"n_labels = labels.shape[1]\n\n\nwith strategy.scope():\n    # # Instantiate cheXnet model with pretrained weights. Pop last layers, add average pooling\n    base = densenet.DenseNet121(weights=None,\n                                include_top=False,\n                                input_shape=(size,size,3)\n                               )\n    ## workaround - add dummy layer then load weights then pop dummy layer, in order to match expected shape for pretrained weights\n    predictions = tf.keras.layers.Dense(14, activation='sigmoid', name='predictions')(base.output)\n    base = tf.keras.Model(inputs=base.input, outputs=predictions) \n\n    base.load_weights(chexnet_weights_path)\n    print(\"CheXNet loaded\")\n    # base.trainable=False # freeze most layers - for better finetuning procedure - TODO\n    # base.training=False\n    \n### https://stackoverflow.com/questions/41668813/how-to-add-and-remove-new-layers-in-keras-after-loading-weights\n#     base._layers.pop() ## _labels instead of labels  \n\n    new_model = tf.keras.layers.GlobalAveragePooling2D()(base.layers[-3].output) \n    ### OPT: add use flatten instead of global pooling. Opt: add dropout, fully connected layers after\n    new_model = tf.keras.layers.Dense(n_labels, activation='sigmoid')(new_model) \n\n    model = tf.keras.Model(base.input, new_model)\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":"# model.layers[-4:]\nbase.layers[-5:-1]","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')\nearly_stop = tf.keras.callbacks.EarlyStopping(\n    monitor='val_auc', min_delta=0.0001, patience=6, mode='max')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit(\n    dtrain, \n    epochs=36, # training for longer results in a better model - but timed out on kernels\n    verbose=1,\n    callbacks=[checkpoint, lr_reducer,early_stop],\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":{},"cell_type":"markdown","source":"## Save history"},{"metadata":{"trusted":true},"cell_type":"code","source":"hist_df = pd.DataFrame(history.history)\nhist_df.to_csv('history.csv')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Submission"},{"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}