{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\n# import os\n# for dirname, _, filenames in os.walk('/kaggle/input'):\n#     for filename in filenames:\n#         print(os.path.join(dirname, filename))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Resources: \n\nhttps://www.kaggle.com/xhlulu/aptos-2019-densenet-keras-starter\n\nhttps://www.kaggle.com/wouterbulten/getting-started-with-the-panda-dataset\n\nhttps://www.kaggle.com/yeayates21/densenet-keras-starter-fork-v2\n\nhttps://www.kaggle.com/xhlulu/jigsaw-tpu-xlm-roberta"},{"metadata":{},"cell_type":"markdown","source":"# Imports"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import json\nimport math\nimport cv2\nimport PIL\nfrom PIL import Image\nimport numpy as np\nfrom keras import layers\nfrom keras.applications import DenseNet121\nfrom keras.callbacks import Callback, ModelCheckpoint\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.optimizers import Adam\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import cohen_kappa_score, accuracy_score\nimport scipy\nimport tensorflow as tf\nfrom tqdm import tqdm\n%matplotlib inline","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import os\n# There are two ways to load the data from the PANDA dataset:\n# Option 1: Load images using openslide\nimport openslide\n# Option 2: Load images using skimage (requires that tifffile is installed)\nimport skimage.io\n# General packages\nfrom IPython.display import display\n# Plotly for the interactive viewer (see last section)\nimport plotly.graph_objs as go\n# read images\nimport rasterio","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import gc\nfrom random import randint","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Config Settings"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Detect hardware, return appropriate distribution strategy\ntry:\n    # TPU detection. No parameters necessary if TPU_NAME environment variable is\n    # set: this is always the case on Kaggle.\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    print('Running on TPU ', tpu.master())\nexcept ValueError:\n    tpu = None\n\nif tpu:\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nelse:\n    # Default distribution strategy in Tensorflow. Works on CPU and single GPU.\n    strategy = tf.distribute.get_strategy()\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Variable Constants"},{"metadata":{"trusted":true},"cell_type":"code","source":"BATCH_SIZE = 15\nTRAIN_VAL_RATIO = 0.27\nEPOCHS = 11\nLR = 0.00010409613402110064","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Target & ID Loading"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df = pd.read_csv('../input/prostate-cancer-grade-assessment/train.csv')\ntest_df = pd.read_csv('../input/prostate-cancer-grade-assessment/test.csv')\nprint(train_df.shape)\nprint(test_df.shape)\ntrain_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"gc.collect()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Image Loading & Pre-processing"},{"metadata":{"trusted":true},"cell_type":"code","source":"def preprocess_image(image_path, desired_size=224):\n    biopsy = openslide.OpenSlide(image_path)\n    im = np.array(biopsy.get_thumbnail(size=(desired_size,desired_size)))\n    im = Image.fromarray(im)\n    im = im.resize((desired_size,desired_size)) \n    im = np.array(im)\n    return im","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# get the number of training images from the target\\id dataset\nN = train_df.shape[0]\n# create an empty matrix for storing the images\nx_train = np.empty((N, 224, 224, 3), dtype=np.uint8)\n# loop through the images from the images ids from the target\\id dataset\n# then grab the cooresponding image from disk, pre-process, and store in matrix in memory\nfor i, image_id in enumerate(tqdm(train_df['image_id'])):\n    x_train[i, :, :, :] = preprocess_image(\n        f'../input/prostate-cancer-grade-assessment/train_images/{image_id}.tiff'\n    )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"if os.path.exists('../input/prostate-cancer-grade-assessment/test_images'):\n    # do the same thing as the last cell but on the test\\holdout set\n    N = test_df.shape[0]\n    x_test = np.empty((N, 224, 224, 3), dtype=np.uint8)\n    for i, image_id in enumerate(tqdm(test_df['image_id'])):\n        x_test[i, :, :, :] = preprocess_image(\n            f'../input/prostate-cancer-grade-assessment/test_images/{image_id}.tiff'\n        )\nelse:\n    print(\"test images not found\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# pre-processing the target (i.e. one-hot encoding the target)\ny_train = pd.get_dummies(train_df['isup_grade']).values\n\nprint(x_train.shape)\nprint(y_train.shape)\nif os.path.exists('../input/prostate-cancer-grade-assessment/test_images'):\n    print(x_test.shape)\nelse:\n    print(\"test images not found\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Further target pre-processing\n\n# Instead of predicting a single label, we will change our target to be a multilabel problem; \n# i.e., if the target is a certain class, then it encompasses all the classes before it. \n# E.g. encoding a class 4 retinopathy would usually be [0, 0, 0, 1], \n# but in our case we will predict [1, 1, 1, 1]. For more details, \n# please check out Lex's kernel.\n\ny_train_multi = np.empty(y_train.shape, dtype=y_train.dtype)\ny_train_multi[:, 5] = y_train[:, 5]\n\nfor i in range(4, -1, -1):\n    y_train_multi[:, i] = np.logical_or(y_train[:, i], y_train_multi[:, i+1])\n\nprint(\"Original y_train:\", y_train.sum(axis=0))\nprint(\"Multilabel version:\", y_train_multi.sum(axis=0))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Train & Validation Split"},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train, x_val, y_train, y_val = train_test_split(\n    x_train, y_train_multi, \n    test_size=TRAIN_VAL_RATIO, \n    random_state=2020\n)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Create Image Augmentation Generator"},{"metadata":{"trusted":true},"cell_type":"code","source":"def create_datagen():\n    return ImageDataGenerator(\n        zoom_range=0.15,  # set range for random zoom\n        # set mode for filling points outside the input boundaries\n        fill_mode='constant',\n        cval=0.,  # value used for fill_mode = \"constant\"\n        horizontal_flip=True,  # randomly flip images\n        vertical_flip=True,  # randomly flip images\n    )\n\n# Using original generator\ndata_generator = create_datagen().flow(x_train, y_train, batch_size=BATCH_SIZE, seed=2019)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Create Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"densenet = DenseNet121(\n    weights='../input/densenet-keras/DenseNet-BC-121-32-no-top.h5',\n    include_top=False,\n    input_shape=(224,224,3)\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def build_model(LR=LR):\n    model = Sequential()\n    model.add(densenet)\n    model.add(layers.GlobalAveragePooling2D())\n    model.add(layers.Dropout(0.80))\n    model.add(layers.Dense(6, activation='sigmoid'))\n    \n    model.compile(\n        loss='binary_crossentropy',\n        optimizer=Adam(lr=LR),\n        metrics=['accuracy']\n    )\n    \n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = build_model()\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Train Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit_generator(\n    data_generator,\n    steps_per_epoch=x_train.shape[0] / BATCH_SIZE,\n    epochs=EPOCHS,\n    validation_data=(x_val, y_val)\n)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Training Plots"},{"metadata":{"trusted":true},"cell_type":"code","source":"history_df = pd.DataFrame(history.history)\nhistory_df[['loss', 'val_loss']].plot()\nhistory_df[['accuracy', 'val_accuracy']].plot()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Submission"},{"metadata":{"trusted":true},"cell_type":"code","source":"if os.path.exists('../input/prostate-cancer-grade-assessment/test_images'):\n    print(\"test images found.\")\n    y_test = model.predict(x_test)\n    y_test = y_test > 0.37757874193797547\n    y_test = y_test.astype(int).sum(axis=1) - 1\n    test_df['isup_grade'] = y_test\n    test_df = test_df[[\"image_id\",\"isup_grade\"]]\n    test_df.to_csv('submission.csv',index=False)\nelse: # if test is not available, just submit some random values\n    print(\"test images not found, submitting random values.\")\n    rand_preds = []\n    for i in range(len(test_df)):\n        rand_preds.append(randint(0,5))\n    test_df['isup_grade'] = rand_preds\n    test_df = test_df[[\"image_id\",\"isup_grade\"]]\n    test_df.to_csv('submission.csv',index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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}