{"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\n\nhttps://www.tensorflow.org/tutorials/images/data_augmentation\n\nhttps://github.com/tensorflow/tensorflow/pull/20753\n\nhttps://stackoverflow.com/questions/57329274/variable-was-not-created-in-the-distribution-strategy-scope-with-costum-layer"},{"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 tensorflow.keras import layers\nfrom tensorflow.keras.applications import DenseNet121\nfrom tensorflow.keras.callbacks import Callback, ModelCheckpoint\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.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":{"trusted":true},"cell_type":"code","source":"# from kaggle_datasets import KaggleDatasets","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":"AUTO = tf.data.experimental.AUTOTUNE\nBATCH_SIZE = 36 * strategy.num_replicas_in_sync\nEPOCHS = 20\n# Data access\n# GCS_DS_PATH = KaggleDatasets().get_gcs_path()","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) / 255\n    return im","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n\n# get the number of training images from the target\\id dataset\n# N = train_df.shape[0] # run on all data\nN = 5650 # run on sample\n# create an empty matrix for storing the images\nx_train = np.empty((N, 224, 224, 3), dtype=np.float32)\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    )\n    # if sampling\n    if i >= N-1:\n        break","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"if os.path.exists(f'../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.float32)\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        )","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.astype(np.int32)[0:N]\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)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n\n# 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=0.40, \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 convert(image, label):\n    image = tf.image.convert_image_dtype(image, tf.float32) # Cast and normalize the image to [0,1]\n    return image, label\n\ndef flip_aug(image,label):\n    image,label = convert(image, label)\n    image = tf.image.convert_image_dtype(image, tf.float32) # Cast and normalize the image to [0,1]\n    image = tf.image.flip_left_right(image)\n    return image,label\n\ndef rotate_aug(image,label):\n    image,label = convert(image, label)\n    image = tf.image.convert_image_dtype(image, tf.float32) # Cast and normalize the image to [0,1]\n    image = tf.image.rot90(image)\n    return image,label\n\ndef crop_aug(image,label):\n    image,label = convert(image, label)\n    image = tf.image.convert_image_dtype(image, tf.float32) # Cast and normalize the image to [0,1]\n    image = tf.image.central_crop(image, central_fraction=0.8)\n    return image,label\n\n\ndef pad_light_aug(image,label):\n    image,label = convert(image, label)\n    image = tf.image.convert_image_dtype(image, tf.float32) # Cast and normalize the image to [0,1]\n    image = tf.image.resize_with_crop_or_pad(image, 230, 230) # Add 6 pixels of padding\n    image = tf.image.random_crop(image, size=[224, 224, 3]) # Random crop back to 224x224x3\n    image = tf.image.random_brightness(image, max_delta=0.5) # Random brightness\n    return image,label","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_dataset = (\n    tf.data.Dataset\n    .from_tensor_slices((x_train, y_train))\n    .repeat()\n    .map(flip_aug, num_parallel_calls=AUTO)\n    .map(rotate_aug, num_parallel_calls=AUTO)\n    .map(crop_aug, num_parallel_calls=AUTO)\n    .map(pad_light_aug, num_parallel_calls=AUTO)\n    .batch(BATCH_SIZE)\n    .prefetch(AUTO)\n)\n\nvalid_dataset = (\n    tf.data.Dataset\n    .from_tensor_slices((x_val, y_val))\n    .batch(BATCH_SIZE)\n    .cache()\n    .prefetch(AUTO)\n)\n\nif os.path.exists('../input/prostate-cancer-grade-assessment/test_images'):\n    test_dataset = (\n        tf.data.Dataset\n        .from_tensor_slices(x_test)\n        .batch(BATCH_SIZE)\n    )","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Create Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"def build_model():\n    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    )\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    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    model = build_model()\n    model.compile(\n        loss='binary_crossentropy',\n        optimizer=Adam(lr=0.00010509613402110064),\n        metrics=['accuracy']\n    )\n\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Train Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"n_steps = x_train.shape[0] // BATCH_SIZE\n\ntrain_history = model.fit(\n    train_dataset,\n    steps_per_epoch=n_steps,\n    validation_data=valid_dataset,\n    epochs=EPOCHS\n)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Training Plots"},{"metadata":{"trusted":true},"cell_type":"code","source":"history_df = pd.DataFrame(train_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    y_test = model.predict(test_dataset)\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.to_csv('submission.csv',index=False)\nelse: # if test is not available, just submit some 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}