{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install ../input/installation/Keras_Applications-1.0.8-py3-none-any.whl -f ./ --no-index --no-deps\n!pip install ../input/install-2/efficientnet-1.1.0-py3-none-any.whl -f ./ --no-index --no-deps","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import os\nimport PIL\nimport time\nimport math\nimport warnings\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.preprocessing.image import load_img\nfrom plotly import graph_objs as go\nimport plotly.express as px\nimport plotly.figure_factory as ff\nimport seaborn as sns\nimport openslide\n\nimport warnings\nwarnings.filterwarnings('ignore')\nimport os\nimport cv2\nimport numpy as np\nimport pandas as pd \nimport json\nimport skimage.io\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras import Model, Sequential\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.utils import Sequence\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau\nimport efficientnet.tfkeras\nimport albumentations as albu\nprint('tensorflow version:', tf.__version__)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"gpus = tf.config.experimental.list_physical_devices('GPU')\n\nif gpus:\n    try:\n        for gpu in gpus:\n            tf.config.experimental.set_memory_growth(gpu, True)\n        logical_gpus = tf.config.experimental.list_logical_devices('GPU')\n        print(len(gpus), \"Physical GPUs,\", len(logical_gpus), \"Logical GPUs\")\n    except RuntimeError as e:\n        print(e)\nelse:\n    print('no gpus')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Model Building","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# Parameters\nDATA_PATH = '../input/prostate-cancer-grade-assessment'\nMODELS_PATH = '.'\nIMG_SIZE = 128\nSEQ_LEN = 36\nTARGET_SIZE = [528, 528]\nBATCH_SIZE = 16\nMDL_VERSION = 'v0'\nSEED = 80\nLEVEL = 1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"\nData generator to feed neural network takes image, cut it to tiles and produces image that made of tiles:\n\"\"\"\n\n# Helpers\ndef get_axis_max_min(array, axis=0):\n    one_axis = list((array != 255).sum(axis=tuple([x for x in (0, 1, 2) if x != axis])))\n    axis_min = next((i for i, x in enumerate(one_axis) if x), 0)\n    axis_max = len(one_axis) - next((i for i, x in enumerate(one_axis[::-1]) if x), 0)\n    return axis_min, axis_max\n\nclass DataGenPanda(Sequence):\n    def __init__(self, imgs_path, df, batch_size=32, \n                 mode='fit', shuffle=False, aug=None, \n                 seq_len=SEQ_LEN, img_size=IMG_SIZE, n_classes=6):\n        self.imgs_path = imgs_path\n        self.df = df\n        self.shuffle = shuffle\n        self.mode = mode\n        self.aug = aug\n        self.batch_size = batch_size\n        self.img_size = img_size\n        self.seq_len = seq_len\n        self.n_classes = n_classes\n        self.side = int(seq_len ** .5)\n        self.on_epoch_end()\n    def __len__(self):\n        return int(np.floor(len(self.df) / self.batch_size))\n    def on_epoch_end(self):\n        self.indexes = np.arange(len(self.df))\n        if self.shuffle:\n            np.random.shuffle(self.indexes)\n    def __getitem__(self, index):\n        X = np.zeros((self.batch_size, self.side * self.img_size, self.side * self.img_size, 3), dtype=np.float32)\n        imgs_batch = self.df[index * self.batch_size : (index + 1) * self.batch_size]['image_id'].values\n        for i, img_name in enumerate(imgs_batch):\n            img_path = '{}/{}.tiff'.format(self.imgs_path, img_name)\n            img_patches = self.get_patches(img_path)\n            X[i, ] = self.glue_to_one(img_patches)\n        \n        # Resize image \n        X = tf.image.convert_image_dtype(X, tf.float32) # Cast and normalize the image to [0,1]    \n        X = tf.image.resize(X, size = TARGET_SIZE) # standardize image size\n\n        if self.mode == 'fit':\n            y = np.zeros((self.batch_size, self.n_classes), dtype=np.float32)\n            lbls_batch = self.df[index * self.batch_size : (index + 1) * self.batch_size]['isup_grade'].values\n            for i in range(self.batch_size):\n                y[i, lbls_batch[i]] = 1\n            return X, y\n        elif self.mode == 'predict':\n            return X\n        else:\n            raise AttributeError('mode parameter error')\n    def get_patches(self, img_path):\n        num_patches = self.seq_len\n        p_size = self.img_size\n        img = skimage.io.MultiImage(img_path)[LEVEL]\n        a0min, a0max = get_axis_max_min(img, axis=0)\n        a1min, a1max = get_axis_max_min(img, axis=1)\n        img = img[a0min:a0max, a1min:a1max, :].astype(np.float32) / 255\n        if self.aug:\n            img = self.aug(image=img)['image']\n        pad0, pad1 = (p_size - img.shape[0] % p_size) % p_size, (p_size - img.shape[1] % p_size) % p_size\n        img = np.pad(\n            img,\n            [\n                [pad0 // 2, pad0 - pad0 // 2], \n                [pad1 // 2, pad1 - pad1 // 2], \n                [0, 0]\n            ],\n            constant_values=1\n        )\n        img = img.reshape(img.shape[0] // p_size, p_size, img.shape[1] // p_size, p_size, 3)\n        img = img.transpose(0, 2, 1, 3, 4).reshape(-1, p_size, p_size, 3)\n        if len(img) < num_patches:\n            img = np.pad(\n                img, \n                [\n                    [0, num_patches - len(img)],\n                    [0, 0],\n                    [0, 0],\n                    [0, 0]\n                ],\n                constant_values=1\n            )\n        idxs = np.argsort(img.reshape(img.shape[0], -1).sum(-1))[:num_patches]\n        return np.array(img[idxs])\n    \n    def glue_to_one(self, imgs_seq):\n        img_glue = np.zeros((self.img_size * self.side, self.img_size * self.side, 3), dtype=np.float32)\n        for i, ptch in enumerate(imgs_seq):\n            x = i // self.side\n            y = i % self.side\n            img_glue[x * self.img_size : (x + 1) * self.img_size, \n                     y * self.img_size : (y + 1) * self.img_size, :] = ptch            \n        return img_glue","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Train test split\ntrain = pd.read_csv('{}/train.csv'.format(DATA_PATH))\nprint('train: ', train.shape, '| unique ids:', sum(train['isup_grade'].value_counts()))\nX_train, X_val = train_test_split(train, test_size=.2, stratify=train['isup_grade'], random_state=SEED)\nlbl_value_counts = X_train['isup_grade'].value_counts()\nclass_weights = {i: max(lbl_value_counts) / v for i, v in lbl_value_counts.items()}\nprint('classes weigths:', class_weights)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Data generators\naug = albu.Compose(\n    [\n        albu.OneOf([albu.RandomBrightness(limit=.15), albu.RandomContrast(limit=.3), albu.RandomGamma()], p=.25),\n        albu.HorizontalFlip(p=.25),\n        albu.VerticalFlip(p=.25),\n        albu.ShiftScaleRotate(shift_limit=.1, scale_limit=.1, rotate_limit=20, p=.25)\n    ]\n)\ntrain_datagen = DataGenPanda(\n    imgs_path='{}/train_images'.format(DATA_PATH), \n    df=X_train, \n    batch_size=BATCH_SIZE,\n    mode='fit', \n    shuffle=True, \n    aug=aug, \n    seq_len=SEQ_LEN, \n    img_size=IMG_SIZE, \n    n_classes=6\n)\nval_datagen = DataGenPanda(\n    imgs_path='{}/train_images'.format(DATA_PATH), \n    df=X_val, \n    batch_size=BATCH_SIZE,\n    mode='fit', \n    shuffle=False, \n    aug=None, \n    seq_len=SEQ_LEN, \n    img_size=IMG_SIZE, \n    n_classes=6\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Checking data generator results\nXt, yt = train_datagen.__getitem__(0)\nprint('test X: ', Xt.shape)\nprint('test y: ', yt.shape)\nfig, axes = plt.subplots(figsize=(18, 6), ncols=BATCH_SIZE)\nfor j in range(BATCH_SIZE):\n    axes[j].imshow(Xt[j])\n    axes[j].axis('off')\n    axes[j].set_title('label {}'.format(np.argmax(yt[j, ])))\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Model Loading","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# Load trained model\nMODEL_DIR = '../input/pandamodels/'\nmodels = {'B0': 'EfficientNetB0.h5', \n          'B2':'EfficientNetB2.h5', \n          'B4':'EfficientNetB4.h5', \n          'B6':'EfficientNetB6.h5', \n          'Xception':'Xception.h5'}\nmodel = tf.keras.models.load_model(MODEL_DIR + models['B6'], compile=False)\nprint('Model loaded:', model)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Make prediction\ntest = pd.read_csv('{}/test.csv'.format(DATA_PATH))\npreds = [[0] * 6] * len(test)\n\nif os.path.exists('../input/prostate-cancer-grade-assessment/test_images'):\n    print('Inference on test images...')\n    subm_datagen = DataGenPanda(\n        imgs_path='{}/test_images'.format(DATA_PATH), \n        df=test,\n        batch_size=1,\n        mode='predict', \n        shuffle=False, \n        aug=None, \n        seq_len=SEQ_LEN, \n        img_size=IMG_SIZE, \n        n_classes=6\n    )\n    preds = model.predict_generator(subm_datagen)\n    print('Total preds test:', len(preds))\nelse:\n    print('Inference on validation images...')\n    preds = model.predict_generator(val_datagen.__getitem__(1))[:len(preds)]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Save submission file\ntest['isup_grade'] = np.argmax(preds, axis=1)\ntest.drop('data_provider',inplace= True, axis=1)\ntest.to_csv('submission.csv', index=False)\ntest.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}