{"cells":[{"metadata":{},"cell_type":"markdown","source":"<h1 style=\"font-family:verdana;\"> <center>Human Protein Atlas - Single Cell Classification🎖 </center> </h1>\n\n<h3><center style=\"color:#159364; font-family:cursive;\">Training Notebook 🦾</center></h3>\n\n\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install git+https://github.com/keras-team/keras-applications.git -q","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import keras_applications as ka\ndef set_to_tf(ka):\n    from tensorflow.keras import backend, layers, models, utils\n    ka._KERAS_BACKEND = backend\n    ka._KERAS_LAYERS = layers\n    ka._KERAS_MODELS = models\n    ka._KERAS_UTILS = utils\n    \n    \nset_to_tf(ka)","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","execution":{"iopub.execute_input":"2020-12-23T08:32:23.84137Z","iopub.status.busy":"2020-12-23T08:32:23.840482Z","iopub.status.idle":"2020-12-23T08:32:30.91666Z","shell.execute_reply":"2020-12-23T08:32:30.915816Z"},"papermill":{"duration":7.10364,"end_time":"2020-12-23T08:32:30.916796","exception":false,"start_time":"2020-12-23T08:32:23.813156","status":"completed"},"tags":[],"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 import layers\nfrom keras.optimizers import Adam\nfrom tensorflow.keras import Model\n# import tensorflow.keras.applications.efficientnet as efn\nfrom tensorflow.keras.applications import Xception, ResNet50V2\nimport os, cv2\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":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","execution":{"iopub.execute_input":"2020-12-23T08:32:30.963865Z","iopub.status.busy":"2020-12-23T08:32:30.962979Z","iopub.status.idle":"2020-12-23T08:32:31.163747Z","shell.execute_reply":"2020-12-23T08:32:31.164513Z"},"papermill":{"duration":0.229339,"end_time":"2020-12-23T08:32:31.164679","exception":false,"start_time":"2020-12-23T08:32:30.93534","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"df = pd.read_csv('../input/hpa-csv-file/hpa_csv.csv')\ndisplay(df.head(5))\nprint(df.shape)","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":false,"trusted":true},"cell_type":"code","source":"def load(file):\n    img= cv2.imread(file)\n    img= cv2.resize(img, (600, 600))\n    return img\n\ndef show(df, sub_dir= 'train/'):\n    df= df.iloc[0:12, :]\n    f, ax= plt.subplots(2, 6, figsize=(18, 4))\n    for i, row in df.iterrows():\n        file= '../input/hpaimage512-data/TarName/' + sub_dir + row['ID'] + '.jpg'\n        img= load(file)\n        ax[i//6][i%6].imshow(img, aspect='auto')\n        try:\n            ax[i//6][i%6].set_title(row['Label'])\n        except:\n            pass\n        ax[i//6][i%6].set_xticks([]); ax[i//6][i%6].set_yticks([])\n    plt.suptitle(sub_dir[:-1].capitalize(), size= 20)\n    plt.show()\n        ","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"show(df)","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"show(pd.read_csv('../input/hpa-single-cell-image-classification/sample_submission.csv'), sub_dir='test/')","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2020-12-23T08:32:31.224427Z","iopub.status.busy":"2020-12-23T08:32:31.223477Z","iopub.status.idle":"2020-12-23T08:32:31.227074Z","shell.execute_reply":"2020-12-23T08:32:31.226359Z"},"papermill":{"duration":0.040807,"end_time":"2020-12-23T08:32:31.227247","exception":false,"start_time":"2020-12-23T08:32:31.18644","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"target_cols = df.drop(['ID','Label'], axis=1).columns.to_list()","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2020-12-23T08:32:31.274947Z","iopub.status.busy":"2020-12-23T08:32:31.274112Z","iopub.status.idle":"2020-12-23T08:32:31.277251Z","shell.execute_reply":"2020-12-23T08:32:31.276534Z"},"papermill":{"duration":0.029037,"end_time":"2020-12-23T08:32:31.277384","exception":false,"start_time":"2020-12-23T08:32:31.248347","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"############# CONFIG ##############\n\nn_classes = len(target_cols)\nimg_size = 300\nn_epochs = 30\nlr= 0.001\nseed= 35\nbatch_size=14","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","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2020-12-23T08:32:31.334511Z","iopub.status.busy":"2020-12-23T08:32:31.330432Z","iopub.status.idle":"2020-12-23T08:32:31.354745Z","shell.execute_reply":"2020-12-23T08:32:31.353906Z"},"papermill":{"duration":0.056227,"end_time":"2020-12-23T08:32:31.354916","exception":false,"start_time":"2020-12-23T08:32:31.298689","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"'''\nReference\nhttps://www.kaggle.com/xhlulu/ranzcr-efficientnet-tpu-training\n\n'''\n\ndef build_decoder(with_labels=True, target_size=(img_size, img_size), ext='jpg'):\n    def decode(path):\n        #print(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.1)\n        img = tf.image.random_contrast(img, 0.9, 1.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 = \"hpaimage512-data\"\nGCS_DS_PATH = KaggleDatasets().get_gcs_path(COMPETITION_NAME)\nGCS_DS_PATH","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2020-12-23T08:32:31.48825Z","iopub.status.busy":"2020-12-23T08:32:31.440461Z","iopub.status.idle":"2020-12-23T08:32:35.867696Z","shell.execute_reply":"2020-12-23T08:32:35.86687Z"},"papermill":{"duration":4.491378,"end_time":"2020-12-23T08:32:35.867827","exception":false,"start_time":"2020-12-23T08:32:31.376449","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"strategy = auto_select_accelerator()\nbatch_size = strategy.num_replicas_in_sync * batch_size\nprint('batch size', batch_size)","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2020-12-23T08:32:35.923117Z","iopub.status.busy":"2020-12-23T08:32:35.921791Z","iopub.status.idle":"2020-12-23T08:32:36.064857Z","shell.execute_reply":"2020-12-23T08:32:36.064039Z"},"papermill":{"duration":0.174953,"end_time":"2020-12-23T08:32:36.064988","exception":false,"start_time":"2020-12-23T08:32:35.890035","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"paths = GCS_DS_PATH + \"/TarName/train/\" + df['ID'] + '.jpg'\n\n# Get the multi-labels\nlabels = df.iloc[:, 2:].values\nlabels.shape","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=seed)\nprint(train_paths.shape, valid_paths.shape)\ntrain_labels.sum(axis=0), valid_labels.sum(axis=0)","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2020-12-23T08:32:36.218088Z","iopub.status.busy":"2020-12-23T08:32:36.216892Z","iopub.status.idle":"2020-12-23T08:32:36.819819Z","shell.execute_reply":"2020-12-23T08:32:36.818946Z"},"papermill":{"duration":0.669577,"end_time":"2020-12-23T08:32:36.819962","exception":false,"start_time":"2020-12-23T08:32:36.150385","status":"completed"},"tags":[],"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":{"trusted":true},"cell_type":"code","source":"def build_model():\n    inp = layers.Input(shape = (img_size, img_size, 3))\n    base = ka.efficientnet.EfficientNetB3(input_shape=(img_size, img_size, 3),weights='imagenet',\n                                                include_top=False)\n    \n    x= base(inp)\n    x= layers.GlobalAveragePooling2D()(layers.Dropout(0.1)(x))\n    x= layers.Dropout(0.3)(x)\n    x= layers.Dense(n_classes, 'sigmoid')(x)\n    \n    return Model(inp, x)\n    ","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2020-12-23T08:33:40.989998Z","iopub.status.busy":"2020-12-23T08:33:40.989103Z","iopub.status.idle":"2020-12-23T08:33:55.997386Z","shell.execute_reply":"2020-12-23T08:33:55.996567Z"},"papermill":{"duration":15.098172,"end_time":"2020-12-23T08:33:55.997516","exception":false,"start_time":"2020-12-23T08:33:40.899344","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    model= build_model()\n    loss= tf.keras.losses.BinaryCrossentropy(label_smoothing=0.0)\n    model.compile(optimizers.Adam(lr=lr),loss=loss,metrics=[tf.keras.metrics.AUC(multi_label=True)])","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2020-12-23T08:33:58.838101Z","iopub.status.busy":"2020-12-23T08:33:58.823687Z","iopub.status.idle":"2020-12-23T08:33:58.858954Z","shell.execute_reply":"2020-12-23T08:33:58.859837Z"},"papermill":{"duration":0.154312,"end_time":"2020-12-23T08:33:58.860071","exception":false,"start_time":"2020-12-23T08:33:58.705759","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"tf.keras.utils.plot_model(model, show_shapes=True)","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2020-12-23T08:33:59.092543Z","iopub.status.busy":"2020-12-23T08:33:59.091445Z","iopub.status.idle":"2020-12-23T08:33:59.095168Z","shell.execute_reply":"2020-12-23T08:33:59.094342Z"},"papermill":{"duration":0.114089,"end_time":"2020-12-23T08:33:59.095306","exception":false,"start_time":"2020-12-23T08:33:58.981217","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"rlr = ReduceLROnPlateau(monitor = 'val_loss', factor = 0.1, patience = 2, verbose = 1, \n                                min_delta = 1e-4, min_lr = 1e-6, mode = 'min', cooldown=1)\n        \nckp = ModelCheckpoint('hpa_effb3.h5',monitor = 'val_loss',\n                      verbose = 1, 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 = 1)","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2020-12-23T08:33:59.307416Z","iopub.status.busy":"2020-12-23T08:33:59.306624Z","iopub.status.idle":"2020-12-23T08:33:59.30985Z","shell.execute_reply":"2020-12-23T08:33:59.310406Z"},"papermill":{"duration":0.113307,"end_time":"2020-12-23T08:33:59.310581","exception":false,"start_time":"2020-12-23T08:33:59.197274","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"steps_per_epoch = train_paths.shape[0] // batch_size\nsteps_per_epoch","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.figure(figsize = (12, 6))\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Loss\")\nplt.plot( history.history[\"loss\"], label = \"Training Loss\", marker='o')\nplt.plot( history.history[\"val_loss\"], label = \"Validation Loss\", marker='+')\nplt.grid(True)\nplt.legend()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize = (12, 6))\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"AUC\")\nplt.plot( history.history[\"auc\"], label = \"Training AUC\" , marker='o')\nplt.plot( history.history[\"val_auc\"], label = \"Validation AUC\", marker='+')\nplt.grid(True)\nplt.legend()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"\n\n## 🌄 Thanks for Reading\n\n![](https://i.gifer.com/7ImI.gif)\n\n\n\n<div class=\"alert alert-block alert-info\" style=\"font-size:20px; font-family:verdana;\">\n <a target=\"_blank\" style=\"color:orange;\">Do UPVOTE for more Motivation🤞</a>\n</div>\n\n\n\n<hr><hr><hr>\n\n<hr>"}],"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}