{"cells":[{"metadata":{},"cell_type":"markdown","source":"# PANDA: keras with timedistributed layer","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"The idea to use tiles of original image was taken from <a href=\"https://www.kaggle.com/iafoss/panda-16x128x128-tiles\">this great notebook</a>. \n\nThe rest of current notebook is rather simple - put sequence of tiles to CNN (<a href=\"https://github.com/qubvel/efficientnet\">EfficientNet</a> as backbone) with wrapper layer (timedistributed) and classify result.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n!pip install ../input/efficientnet/efficientnet-1.1.0/ -f ./ --no-index","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import 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.metrics import cohen_kappa_score\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 as efn\nimport albumentations as albu\nprint('tensorflow version:', tf.__version__)\ngpus = tf.config.experimental.list_physical_devices('GPU')\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":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.utils import get_custom_objects\nclass Mish(Activation):\n    '''\n    Mish Activation Function.\n    .. math::\n        mish(x) = x * tanh(softplus(x)) = x * tanh(ln(1 + e^{x}))\n    Shape:\n        - Input: Arbitrary. Use the keyword argument `input_shape`\n        (tuple of integers, does not include the samples axis)\n        when using this layer as the first layer in a model.\n        - Output: Same shape as the input.\n    Examples:\n        >>> X = Activation('Mish', name=\"conv1_act\")(X_input)\n    '''\n    def __init__(self, activation, **kwargs):\n        super(Mish, self).__init__(activation, **kwargs)\n        self.__name__ = 'Mish'\ndef mish(inputs):\n    return inputs * tf.math.tanh(tf.math.softplus(inputs))\nget_custom_objects().update({'Mish': Mish(mish)})","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"DATA_PATH = '../input/prostate-cancer-grade-assessment'\nMODELS_PATH = '.'\n# Use half-sized images for EfficientNet input\n# Inputs for EfficientNet:\n# B0: 224x224x3 \n# B1: 240x240x3\n# B2: 260x260x3\n# B3: 300x300x3\n# B4: 380x380x3\n# B5: 456x456x3\nIMG_SIZE = 120 # half-sized B1\nSEQ_LEN = 10\nBATCH_SIZE = 20\nMDL_VERSION = 'v2'\nTIFF = -1\nRESIZE = None\nSEED = 80","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Data prepare","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"Data generator to feed neural network takes image, cut it to tiles and produces sequence of tiles:","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def 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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class DataGenPanda(Sequence):\n    def __init__(self, imgs_path, df, batch_size=32, \n                 mode='fit', shuffle=False, aug=None,\n                 tiff=-1, resize=None,\n                 seq_len=12, img_size=128, 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.tiff = tiff\n        self.resize = resize\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.seq_len, self.img_size, 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, ] = img_patches\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)[self.tiff]\n        if self.resize:\n            img = cv2.resize(img, (int(img.shape[1] / self.resize), int(img.shape[0] / self.resize)))\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])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Load train metadata, train-test split with classes balance:","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"train = 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":"aug = albu.Compose(\n    [\n        albu.OneOf(\n            [\n                albu.RandomBrightness(limit=.15), \n                albu.RandomContrast(limit=.3), \n                albu.RandomGamma()\n            ], \n            p=.3\n        ),\n        albu.HorizontalFlip(p=.3),\n        albu.VerticalFlip(p=.3),\n        albu.ShiftScaleRotate(shift_limit=.1, scale_limit=.1, rotate_limit=20, p=.3)\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    tiff=TIFF,\n    resize=RESIZE,\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    tiff=TIFF,\n    resize=RESIZE,\n    seq_len=SEQ_LEN, \n    img_size=IMG_SIZE, \n    n_classes=6\n)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Let's look at result that data generator producers, just to see it is normal as train data:","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"Xt, yt = train_datagen.__getitem__(0)\nprint('test X: ', Xt.shape)\nprint('test y: ', yt.shape)\nfig, axes = plt.subplots(figsize=(SEQ_LEN, BATCH_SIZE), nrows=BATCH_SIZE, ncols=SEQ_LEN)\nfor j in range(BATCH_SIZE):\n    for i in range(SEQ_LEN):\n        axes[j, i].imshow(Xt[j][i])\n        axes[j, i].axis('off')\n        axes[j, i].set_title(np.argmax(yt[j, ]))\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Train model","execution_count":null},{"metadata":{"trusted":true},"cell_type":"markdown","source":"Our network based on EfficientNet:","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"bottleneck = efn.EfficientNetB1(\n    weights='../input/effnetweights/efficientnet-b1_weights_tf_dim_ordering_tf_kernels_autoaugment_notop.h5', \n    include_top=False, \n    pooling='avg'\n)\nbottleneck = Model(inputs=bottleneck.inputs, outputs=bottleneck.layers[-2].output)\nmodel = Sequential()\nmodel.add(TimeDistributed(bottleneck, input_shape=(SEQ_LEN, IMG_SIZE, IMG_SIZE, 3)))\nmodel.add(TimeDistributed(BatchNormalization()))\nmodel.add(GlobalMaxPooling3D())\nmodel.add(BatchNormalization())\nmodel.add(Dropout(.4))\nmodel.add(Dense(512, activation='Mish'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(.4))\nmodel.add(Dense(128, activation='Mish'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(.4))\nmodel.add(Dense(6, activation='softmax'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def qw_kappa_score(y_true, y_pred):\n    y_true=tf.math.argmax(y_true, axis=1)\n    y_pred=tf.math.argmax(y_pred, axis=1)\n    def sklearn_qwk(y_true, y_pred) -> np.float64:\n        return cohen_kappa_score(y_true, y_pred, weights='quadratic')\n    return tf.compat.v1.py_func(sklearn_qwk, (y_true, y_pred), tf.double)\nmodel.compile(\n    loss='categorical_crossentropy',\n    optimizer=Adam(lr=1e-3),\n    metrics=['categorical_accuracy', qw_kappa_score]\n)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Train for only 15 epochs for demo:","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nmodel_file = '{}/model_{}.h5'.format(MODELS_PATH, MDL_VERSION)\nif False:\n    model = load_model(model_file)\n    print('model loaded')\nelse:\n    print('train from scratch')\nEPOCHS = 15\nearlystopper = EarlyStopping(\n    monitor='val_qw_kappa_score', \n    patience=10, \n    verbose=1,\n    mode='max'\n)\nmodelsaver = ModelCheckpoint(\n    model_file, \n    monitor='val_qw_kappa_score', \n    verbose=1, \n    save_best_only=True,\n    mode='max'\n)\nlrreducer = ReduceLROnPlateau(\n    monitor='val_qw_kappa_score',\n    factor=.1,\n    patience=5,\n    verbose=1,\n    min_lr=1e-7\n)\nhistory = model.fit_generator(\n    train_datagen,\n    validation_data=val_datagen,\n    class_weight=class_weights,\n    callbacks=[earlystopper, modelsaver, lrreducer],\n    epochs=EPOCHS,\n    verbose=1\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history_file = '{}/history_{}.txt'.format(MODELS_PATH, MDL_VERSION)\ndict_to_save = {}\nfor k, v in history.history.items():\n    dict_to_save.update({k: [np.format_float_positional(x) for x in history.history[k]]})\nwith open(history_file, 'w') as file:\n    json.dump(dict_to_save, file)\nep_max = EPOCHS\nplt.plot(history.history['loss'][:ep_max], label='loss')\nplt.plot(history.history['val_loss'][:ep_max], label='val_loss')\nplt.legend()\nplt.show()\nplt.plot(history.history['categorical_accuracy'][:ep_max], label='cat acc')\nplt.plot(history.history['val_categorical_accuracy'][:ep_max], label='val cat acc')\nplt.legend()\nplt.show()\nplt.plot(history.history['qw_kappa_score'][:ep_max], label='qwk')\nplt.plot(history.history['val_qw_kappa_score'][:ep_max], label='val qwk')\nplt.legend()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Inference","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"test = pd.read_csv('{}/test.csv'.format(DATA_PATH))\npreds = [[0] * 6] * len(test)\nif os.path.exists('../input/prostate-cancer-grade-assessment/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        tiff=TIFF,\n        resize=RESIZE,\n        seq_len=SEQ_LEN, \n        img_size=IMG_SIZE, \n        n_classes=6\n    )\n    preds = model.predict_generator(subm_datagen)\n    print('preds done, total:', len(preds))\nelse:\n    print('preds are zeros')\ntest['isup_grade'] = np.argmax(preds, axis=1)\ntest.drop('data_provider', axis=1, inplace=True)\ntest.to_csv('submission.csv', index=False)\nprint('submission saved')","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}