{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n# ML tools \nimport tensorflow as tf\nfrom kaggle_datasets import KaggleDatasets\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Flatten, Activation, Conv2D, MaxPooling2D, Dropout, Conv2D,MaxPooling2D,GlobalAveragePooling2D\nfrom keras.optimizers import Adam\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.applications import InceptionResNetV2\nimport os\nfrom keras import optimizers\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.callbacks import ReduceLROnPlateau, ModelCheckpoint, EarlyStopping","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"df_target = pd.read_csv('../input/ranzcr-clip-catheter-line-classification/train.csv')\ndisplay(df_target.head(3))\nprint(df_target.shape)\ndf_sample = pd.read_csv('../input/ranzcr-clip-catheter-line-classification/sample_submission.csv')\ndisplay(df_sample.head(3))\nprint(df_sample.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"target_cols = df_target.drop(['StudyInstanceUID','PatientID'], axis=1).columns.to_list()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"n_classes = len(target_cols)\nimg_size = 900\nn_epochs = 30","execution_count":null,"outputs":[]},{"metadata":{"trusted":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\ndef build_decoder(with_labels=True, target_size=(img_size, img_size), ext='jpg'):\n    def decode(path):\n        file_bytes = tf.io.read_file(path) # Reads and outputs the entire contents of the input filename.\n\n        if ext == 'png':\n            img = tf.image.decode_png(file_bytes, channels=3) # Decode a PNG-encoded image to a uint8 or uint16 tensor\n        elif ext in ['jpg', 'jpeg']:\n            img = tf.image.decode_jpeg(file_bytes, channels=3) # Decode a JPEG-encoded image to a uint8 tensor\n        else:\n            raise ValueError(\"Image extension not supported\")\n\n        img = tf.cast(img, tf.float32) / 255.0 # Casts a tensor to the type float32 and divides by 255.\n        img = tf.image.resize(img, target_size) # Resizing to target size\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.8, 1.2)\n        img = tf.image.random_brightness(img, 0.2)\n        img = tf.image.random_contrast(img, 0.8, 1.2)\n        img = tf.image.random_hue(img, 0.2)\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\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) # overlaps data preprocessing and model execution while training\n    return dset\n","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\nprint('batch size', batch_size)\nGCS_DS_PATH = KaggleDatasets().get_gcs_path(COMPETITION_NAME)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"load_dir = '/kaggle/input/ranzcr-clip-catheter-line-classification/'\ndf_train = pd.read_csv(load_dir + 'train.csv')\npaths = GCS_DS_PATH + \"/train/\" + df_train['StudyInstanceUID'] + '.jpg'\n\ndf_sub = pd.read_csv(load_dir + 'sample_submission.csv')\ntest_paths = GCS_DS_PATH + \"/test/\" + df_sub['StudyInstanceUID'] + '.jpg'\n\n# Get the multi-labels\nlabel_cols = df_sub.columns[1:]\nlabels = df_train[label_cols].values","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Train test split\ntrain_paths, valid_paths, train_labels, valid_labels = train_test_split(paths, labels, test_size=0.12, random_state=42)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Build the tensorflow datasets\n\ndecoder = build_decoder(with_labels=True, target_size=(img_size, img_size))\n\n# Build the tensorflow datasets\ndtrain = build_dataset(\n    train_paths, train_labels, bsize=batch_size, decode_fn=decoder\n)\n\ndvalid = build_dataset(\n    valid_paths, valid_labels, bsize=batch_size, \n    repeat=False, shuffle=False, augment=False, decode_fn=decoder\n)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Visualizing some images in a batch"},{"metadata":{"trusted":true},"cell_type":"code","source":"data, _ = dtrain.take(2)\nimages = data[0].numpy()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, axes = plt.subplots(4, 4, figsize=(24,24))\naxes = axes.flatten()\nfor img, ax in zip(images, axes):\n    ax.imshow(img)\n    ax.axis('off')\nplt.tight_layout()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    net = tf.keras.applications.ResNet50(include_top=False,input_shape=(img_size, img_size, 3), weights='imagenet')\n    x = net.output\n    x = GlobalAveragePooling2D()(x)\n    x = Dropout(0.5)(x)\n    output = Dense(n_classes, activation='sigmoid')(x)\n    model = Model(inputs=net.input, outputs=output)\n    model.compile(optimizer = 'adam',loss='binary_crossentropy',metrics=[tf.keras.metrics.AUC(multi_label=True)])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"rlr = ReduceLROnPlateau(monitor = 'val_loss', factor = 0.1, patience = 2, verbose = 0, \n                                min_delta = 1e-4, min_lr = 1e-6, mode = 'min')\n        \nckp = ModelCheckpoint('model.h5',monitor = 'val_loss',\n                      verbose = 0, save_best_only = True, mode = 'min')\n        \nes = EarlyStopping(monitor = 'val_loss', min_delta = 1e-4, patience = 5, mode = 'min', \n                    restore_best_weights = True, verbose = 0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"steps_per_epoch = train_paths.shape[0] // batch_size","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit(dtrain,                      \n                    validation_data=dvalid,                                       \n                    epochs=n_epochs,\n                    callbacks=[rlr,es,ckp],\n                    steps_per_epoch=steps_per_epoch,\n                    verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.rcParams.update({'font.size': 16})\nhist = pd.DataFrame(history.history)\nfig, (ax1, ax2) = plt.subplots(figsize=(12,12),nrows=2, ncols=1)\nhist['loss'].plot(ax=ax1,c='k',label='training loss')\nhist['val_loss'].plot(ax=ax1,c='r',linestyle='--', label='validation loss')\nax1.legend()\nhist['auc'].plot(ax=ax2,c='k',label='training AUC')\nhist['val_auc'].plot(ax=ax2,c='r',linestyle='--',label='validation AUC')\nax2.legend()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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}