{"cells":[{"metadata":{"papermill":{"duration":0.033736,"end_time":"2021-01-22T13:32:38.670033","exception":false,"start_time":"2021-01-22T13:32:38.636297","status":"completed"},"tags":[]},"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;\">Inference Notebook 🦾</center></h3>\n\n\n### Do check-out for [Traning NOTEBOOK](https://www.kaggle.com/akhileshdkapse/hpa-cell-classification-efficientnets-tpu-training) :-)"},{"metadata":{"execution":{"iopub.execute_input":"2021-01-22T13:32:38.906092Z","iopub.status.busy":"2021-01-22T13:32:38.905163Z","iopub.status.idle":"2021-01-22T13:32:38.907534Z","shell.execute_reply":"2021-01-22T13:32:38.906849Z"},"papermill":{"duration":0.045294,"end_time":"2021-01-22T13:32:38.90766","exception":false,"start_time":"2021-01-22T13:32:38.862366","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"########## Hyperparameters ##############\nimg_size= (300,300)\nclasses= 19\nseed= 32\nbatch_size= 14\nval_split= 0.12\nlr= 0.001","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2021-01-22T13:32:38.985162Z","iopub.status.busy":"2021-01-22T13:32:38.984246Z","iopub.status.idle":"2021-01-22T13:32:43.934726Z","shell.execute_reply":"2021-01-22T13:32:43.933949Z"},"papermill":{"duration":4.992729,"end_time":"2021-01-22T13:32:43.934874","exception":false,"start_time":"2021-01-22T13:32:38.942145","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"import pandas as pd \nimport numpy as np\nimport os\n\nimport tensorflow as tf","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2021-01-22T13:32:44.000935Z","iopub.status.busy":"2021-01-22T13:32:43.998988Z","iopub.status.idle":"2021-01-22T13:32:44.001619Z","shell.execute_reply":"2021-01-22T13:32:44.002127Z"},"papermill":{"duration":0.042473,"end_time":"2021-01-22T13:32:44.002258","exception":false,"start_time":"2021-01-22T13:32:43.959785","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"# Reading images\ndef build_decoder(with_labels=True, target_size=img_size, 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\n# Augmenting images\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_crop(img, size, seed=None, name=None)\n        img= tf.image.random_brightness(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","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2021-01-22T13:32:44.070307Z","iopub.status.busy":"2021-01-22T13:32:44.068877Z","iopub.status.idle":"2021-01-22T13:32:44.071038Z","shell.execute_reply":"2021-01-22T13:32:44.071553Z"},"papermill":{"duration":0.044422,"end_time":"2021-01-22T13:32:44.071692","exception":false,"start_time":"2021-01-22T13:32:44.02727","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"# TPU or GPU detection\ndef 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:  # detect TPUs\n        tpu = tf.distribute.cluster_resolver.TPUClusterResolver()  ## detect TPUs\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.MirroredStrategy() # for GPU or multi-GPU machines\n        #strategy = tf.distribute.get_strategy() # default strategy that works on CPU and single GPU\n        #strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy() # for clusters of multi-GPU machines\n        \n    print(f\"Running on {strategy.num_replicas_in_sync} replicas\")\n    return strategy\n\n","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2021-01-22T13:32:44.12876Z","iopub.status.busy":"2021-01-22T13:32:44.126953Z","iopub.status.idle":"2021-01-22T13:32:44.129422Z","shell.execute_reply":"2021-01-22T13:32:44.129884Z"},"papermill":{"duration":0.032581,"end_time":"2021-01-22T13:32:44.130007","exception":false,"start_time":"2021-01-22T13:32:44.097426","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"test_decoder = build_decoder(with_labels=False, target_size= img_size)","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2021-01-22T13:32:44.229952Z","iopub.status.busy":"2021-01-22T13:32:44.229174Z","iopub.status.idle":"2021-01-22T13:32:44.233269Z","shell.execute_reply":"2021-01-22T13:32:44.232659Z"},"papermill":{"duration":0.037884,"end_time":"2021-01-22T13:32:44.233367","exception":false,"start_time":"2021-01-22T13:32:44.195483","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"def Build_dataset(paths, labels= None, batch= batch_size,\n                  decode_fn=test_decoder, augment_fn=None,\n                  augment= False, repeat= True, shuffle= seed):\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.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(batch).prefetch(AUTO)\n    \n    return dset","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2021-01-22T13:32:46.718157Z","iopub.status.busy":"2021-01-22T13:32:45.120456Z","iopub.status.idle":"2021-01-22T13:32:46.723069Z","shell.execute_reply":"2021-01-22T13:32:46.72355Z"},"papermill":{"duration":2.464834,"end_time":"2021-01-22T13:32:46.72369","exception":false,"start_time":"2021-01-22T13:32:44.258856","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"Base_dir = \"hpa-single-cell-image-classification\"\nstrategy = auto_select_accelerator()\nBATCH_SIZE = strategy.num_replicas_in_sync * batch_size","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2021-01-22T13:32:46.782794Z","iopub.status.busy":"2021-01-22T13:32:46.781974Z","iopub.status.idle":"2021-01-22T13:32:46.785911Z","shell.execute_reply":"2021-01-22T13:32:46.786377Z"},"papermill":{"duration":0.036685,"end_time":"2021-01-22T13:32:46.786515","exception":false,"start_time":"2021-01-22T13:32:46.74983","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"tpu_bsize= batch_size * strategy.num_replicas_in_sync\ntpu_bsize","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2021-01-22T13:32:46.84569Z","iopub.status.busy":"2021-01-22T13:32:46.844962Z","iopub.status.idle":"2021-01-22T13:32:46.887685Z","shell.execute_reply":"2021-01-22T13:32:46.886508Z"},"papermill":{"duration":0.07531,"end_time":"2021-01-22T13:32:46.88781","exception":false,"start_time":"2021-01-22T13:32:46.8125","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"sub_df = pd.read_csv('/kaggle/input/hpa-single-cell-image-classification/sample_submission.csv')\ntest_paths = '../input/hpaimage512-data/TarName/test/' + sub_df['ID'] + '.jpg'","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2021-01-22T13:32:46.952043Z","iopub.status.busy":"2021-01-22T13:32:46.951274Z","iopub.status.idle":"2021-01-22T13:32:47.14231Z","shell.execute_reply":"2021-01-22T13:32:47.143166Z"},"papermill":{"duration":0.229236,"end_time":"2021-01-22T13:32:47.143328","exception":false,"start_time":"2021-01-22T13:32:46.914092","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"# Get the multi-labels\nlabel_cols = sub_df.columns[1:]\n\n#dtest = Build_dataset(paths= test_paths, labels= None, augment= False, repeat=False, shuffle=False)\ndtest = Build_dataset(paths= test_paths, labels= None, augment= False, repeat=False, shuffle=False)","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2021-01-22T13:32:47.204481Z","iopub.status.busy":"2021-01-22T13:32:47.202569Z","iopub.status.idle":"2021-01-22T13:32:47.205159Z","shell.execute_reply":"2021-01-22T13:32:47.205685Z"},"papermill":{"duration":0.035714,"end_time":"2021-01-22T13:32:47.205815","exception":false,"start_time":"2021-01-22T13:32:47.170101","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"img_size = img_size[0]\nseed= 35\n#from tensorflow.keras import layers","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2021-01-22T13:32:47.268507Z","iopub.status.busy":"2021-01-22T13:32:47.267835Z","iopub.status.idle":"2021-01-22T13:32:48.075256Z","shell.execute_reply":"2021-01-22T13:32:48.074631Z"},"papermill":{"duration":0.842367,"end_time":"2021-01-22T13:32:48.075377","exception":false,"start_time":"2021-01-22T13:32:47.23301","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.layers import Input, Dense, Flatten, Activation, Conv2D, Lambda, \\\n                            Dropout, Conv2D, MaxPooling2D, GlobalAveragePooling2D, BatchNormalization, multiply\nfrom keras.optimizers import Adam\nfrom tensorflow.keras import Model\n# import tensorflow.keras.applications.efficientnet as efn\nfrom tensorflow.keras.applications import Xception\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":{"execution":{"iopub.execute_input":"2021-01-22T13:32:48.134536Z","iopub.status.busy":"2021-01-22T13:32:48.13371Z","iopub.status.idle":"2021-01-22T13:33:24.57484Z","shell.execute_reply":"2021-01-22T13:33:24.573754Z"},"papermill":{"duration":36.472673,"end_time":"2021-01-22T13:33:24.574968","exception":false,"start_time":"2021-01-22T13:32:48.102295","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    model= tf.keras.models.load_model('../input/hpa-cell-classification-efficientnets-tpu-training/hpa_effb3.h5')","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2021-01-22T13:33:24.669961Z","iopub.status.busy":"2021-01-22T13:33:24.659598Z","iopub.status.idle":"2021-01-22T13:33:24.727621Z","shell.execute_reply":"2021-01-22T13:33:24.726822Z"},"papermill":{"duration":0.125381,"end_time":"2021-01-22T13:33:24.727778","exception":false,"start_time":"2021-01-22T13:33:24.602397","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2021-01-22T13:33:24.788893Z","iopub.status.busy":"2021-01-22T13:33:24.788239Z","iopub.status.idle":"2021-01-22T13:38:32.628018Z","shell.execute_reply":"2021-01-22T13:38:32.627051Z"},"papermill":{"duration":307.872366,"end_time":"2021-01-22T13:38:32.628137","exception":false,"start_time":"2021-01-22T13:33:24.755771","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"preds = model.predict(dtest, verbose=1)\npreds.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub_df['INDEX']= list(range(0, sub_df.shape[0]))\nsub_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"encoded_df= pd.read_csv('../input/generated-mask/encoded_csv.csv')\nencoded_df.drop(['PredictionString'], 1, inplace=True)\nencoded_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df=pd.merge(sub_df, encoded_df, on='ID', how='left')\ndf.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def thresh(i, thr=0.5):\n    p= preds[i]\n    string=''\n#     for ind, confi in enumerate(p):\n#         if confi >thr:\n#             x= '{} {:.6} '.format(ind, confi) + df.encode[i][2:-1] +' '\n#             string+= x\n    string+= '0 1 ' + df.encode[i][2:-1] +' '\n    return string","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub_df.PredictionString= sub_df.INDEX.apply(thresh)\nsub_df.drop(['INDEX'], 1, inplace=True)\nsub_df.head(5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub_df.PredictionString[0].split(' ')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#sub_df = pd.read_csv('../input/hpa-single-cell-image-classification/sample_submission.csv')","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2021-01-22T13:38:33.580205Z","iopub.status.busy":"2021-01-22T13:38:33.579616Z","iopub.status.idle":"2021-01-22T13:38:33.917957Z","shell.execute_reply":"2021-01-22T13:38:33.91731Z"},"papermill":{"duration":0.456527,"end_time":"2021-01-22T13:38:33.918113","exception":false,"start_time":"2021-01-22T13:38:33.461586","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"sub_df.to_csv('submission.csv', index=False)\nsub_df.head()","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}