{"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_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\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\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n!pip install git+https://github.com/keras-team/keras-applications.git -q","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import keras_applications as ka\nfrom tensorflow.keras import backend, layers, models, utils\nka._KERAS_BACKEND = backend\nka._KERAS_LAYERS = layers\nka._KERAS_MODELS = models\nka._KERAS_UTILS = utils","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.read_csv('../input/hpa-single-cell-image-classification/train.csv')\n\nlabels = [str(i) for i in range(19)]\nfor x in labels: df[x] = df['Label'].apply(lambda r: int(x in r.split('|')))\n    \ndisplay(df.head(5))\nprint(df.shape)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"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()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"show(df)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"show(pd.read_csv('../input/hpa-single-cell-image-classification/sample_submission.csv'), sub_dir='test/')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"target_cols = df.drop(['ID','Label'], axis=1).columns.to_list()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"n_classes = len(target_cols)\nimg_size = 300\nn_epochs = 20\nlr= 0.001\nseed= 42\nbatch_size=128\nstrategy = tf.distribute.get_strategy()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def 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","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"COMPETITION_NAME = \"hpaimage512-data\"\nGCS_DS_PATH = KaggleDatasets().get_gcs_path(COMPETITION_NAME)\nGCS_DS_PATH","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"strategy = auto_select_accelerator()\nbatch_size = strategy.num_replicas_in_sync * batch_size\nprint('batch size', batch_size)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"paths = '../input/hpaimage512-data' + \"/TarName/train/\" + df['ID'] + '.jpg'\n\n# Get the multi-labels\nlabels = df.iloc[:, 2:].values\nlabels.shape","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"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)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"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(train_paths, train_labels, bsize=batch_size, decode_fn=decoder)\n\ndvalid = build_dataset(valid_paths, valid_labels, bsize=batch_size, \n    repeat=False, shuffle=False, augment=False, decode_fn=decoder)\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_paths = '../input/hpaimage512-data' + \"/TarName/test/\" + df['ID'] + '.jpg'\ntest_paths","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_decoder = build_decoder(with_labels=False, target_size=(img_size, img_size))\ndtest = build_dataset(test_paths, bsize=batch_size, \n    repeat=False, shuffle=False, augment=False, decode_fn=test_decoder)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"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',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    ","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"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)])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tf.keras.utils.plot_model(model, show_shapes=True)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"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)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"steps_per_epoch = train_paths.shape[0] // batch_size\nsteps_per_epoch","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"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)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"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()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"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()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}