{"cells":[{"metadata":{},"cell_type":"markdown","source":"# PANDA: simple keras baseline","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 - just glue all tiles to one image and put in through keras based model with <a href=\"https://github.com/qubvel/efficientnet\">EfficientNet</a> as backbone.","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.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":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"DATA_PATH = '../input/prostate-cancer-grade-assessment'\nMODELS_PATH = '.'\nIMG_SIZE = 64\nSEQ_LEN = 25\nBATCH_SIZE = 16\nMDL_VERSION = 'v0'\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 image that made 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                 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.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        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)[-1]\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    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":{},"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([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":{},"cell_type":"markdown","source":"Let's look at result that data generator produces, 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=(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":"## Train model","execution_count":null},{"metadata":{"trusted":true},"cell_type":"markdown","source":"Our network based on EfficientNetB3:","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"bottleneck = efn.EfficientNetB3(\n    input_shape=(int(SEQ_LEN ** .5) * IMG_SIZE, int(SEQ_LEN ** .5) * IMG_SIZE, 3),\n    weights='../input/effnetweights/efficientnet-b3_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(bottleneck)\nmodel.add(GlobalAveragePooling2D())\nmodel.add(Flatten())\nmodel.add(BatchNormalization())\nmodel.add(Dropout(.25))\nmodel.add(Dense(512, activation='elu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(.25))\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)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np\nfrom sklearn.metrics import cohen_kappa_score\nfrom sklearn.metrics import confusion_matrix\n\nimport keras.backend as K\nimport tensorflow as tf\n\n\ndef kappa_keras(y_true, y_pred):\n\n    y_true = K.cast(K.argmax(y_true, axis=-1), dtype='int32')\n    y_pred = K.cast(K.argmax(y_pred, axis=-1), dtype='int32')\n    #print(y_true)\n    #print(y_pred)\n    # Figure out normalized expected values\n    min_rating = K.minimum(K.min(y_true), K.min(y_pred))\n    max_rating = K.maximum(K.max(y_true), K.max(y_pred))\n\n    # shift the values so that the lowest value is 0\n    # (to support scales that include negative values)\n    y_true = K.map_fn(lambda y: y - min_rating, y_true, dtype='int32')\n    y_pred = K.map_fn(lambda y: y - min_rating, y_pred, dtype='int32')\n\n    # Build the observed/confusion matrix\n    num_ratings = max_rating - min_rating + 1\n    observed = tf.math.confusion_matrix(y_true, y_pred,\n                                num_classes=num_ratings)\n    num_scored_items = K.shape(y_true)[0]\n\n    weights = K.expand_dims(K.arange(num_ratings), axis=-1) - K.expand_dims(K.arange(num_ratings), axis=0)\n    weights = K.cast(K.pow(weights, 2), dtype='float64')\n\n    hist_true = tf.math.bincount(y_true, minlength=num_ratings)\n    hist_true = hist_true[:num_ratings] / num_scored_items\n    hist_pred = tf.math.bincount(y_pred, minlength=num_ratings)\n    hist_pred = hist_pred[:num_ratings] / num_scored_items\n    expected = K.dot(K.expand_dims(hist_true, axis=-1), K.expand_dims(hist_pred, axis=0))\n\n    # Normalize observed array\n    observed = observed / num_scored_items\n\n    # If all weights are zero, that means no disagreements matter.\n    score = tf.where(K.any(K.not_equal(weights, 0)), \n                     K.sum(weights * observed) / K.sum(weights * expected), \n                     0)\n    \n    return 1. - score\n\nif __name__ == '__main__':\n    y_true = np.array([2, 0, 2, 2, 0, 1])\n    y_pred = np.array([0, 0, 2, 2, 0, 2])\n    # Testing Keras implementation of QWK\n    \n    # Calculating QWK score with scikit-learn\n   \n    skl_score = cohen_kappa_score(y_true, y_pred, weights='quadratic')\n    \n    # Keras implementation of QWK work with one hot encoding labels and predictions (also it works with softmax probabilities)\n    # Converting arrays to one hot encoded representation\n    shape = (y_true.shape[0], np.maximum(y_true.max(), y_pred.max()) + 1)\n\n    y_true_ohe = np.zeros(shape)\n    y_true_ohe[np.arange(shape[0]), y_true] = 1\n\n    y_pred_ohe = np.zeros(shape)\n    y_pred_ohe[np.arange(shape[0]), y_pred] = 1\n    \n    # Calculating QWK score with Keras\n    with tf.compat.v1.Session() as sess:\n        keras_score = kappa_keras(y_true_ohe, y_pred_ohe).eval()\n    \n    #print('Scikit-learn score: {:.03}, Keras score: {:.03}'.format(skl_score, keras_score))\n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(\n    loss='categorical_crossentropy',\n    optimizer=Adam(lr=1e-3),\n    metrics=['categorical_accuracy', kappa_keras]\n)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Train for only 20 epochs for demo:","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"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 = 20\nearlystopper = EarlyStopping(\n    monitor='val_loss', \n    patience=10, \n    verbose=1,\n    mode='min'\n)\nmodelsaver = ModelCheckpoint(\n    model_file, \n    monitor='val_loss', \n    verbose=1, \n    save_best_only=True,\n    mode='min'\n)\nlrreducer = ReduceLROnPlateau(\n    monitor='val_loss',\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. accuracy')\nplt.plot(history.history['val_categorical_accuracy'][:ep_max], label='val_accuracy')\nplt.plot(history.history['kappa_keras'][:ep_max], label='kappa_keras')\nplt.plot(history.history['val_kappa_keras'][:ep_max], label='val_kappa_keras')\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        seq_len=SEQ_LEN, \n        img_size=IMG_SIZE, \n        n_classes=6\n    )\n    preds = model.predict_generator(subm_datagen)\n    print('predictions done, total:', len(preds))\nelse:\n    print('submission not found')\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":"#Original Author: https://www.kaggle.com/vgarshin","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}