{"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\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 read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"\n\n#  Let the first 8000 be the train/val data, and the \n# 9000:10000 will be validation and last 1135 is the test set\n\nN_train = 8000    # \nN_val = 1000          \n\nFIRST = True;   # First run the weights shouldn't be loaded\n\nFIRST_HALF = True   #Every other run, the first half of the dataset is run\n\nRUN_NO = \"1\"\n#ROTATION = 1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# IMPORTS\nimport pandas as pd \nimport os\nimport tensorflow.keras\n# DATA visualization\nimport seaborn as sns\nfrom IPython.display import Image, display\n\n\nimport cv2\nfrom pathlib import Path\nfrom skimage.io import MultiImage\nfrom multiprocessing import Pool\nimport json\nimport math\nimport cv2\nimport PIL\nfrom PIL import Image\nimport numpy as np\nfrom tensorflow.keras import layers\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\nprint('TensorFlow version:', tf.__version__)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Load metadata\ndf = pd.read_csv('../input/prostate-cancer-grade-assessment/train.csv')\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!ls ../input/prostate-cancer-grade-assessment/","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Remove suspicous images\n\nlow_tiss_slides = [ '033e39459301e97e457232780a314ab7',\n                    '0b6e34bf65ee0810c1a4bf702b667c88',\n                    '3385a0f7f4f3e7e7b380325582b115c9',\n                    '3790f55cad63053e956fb73027179707',\n                    '5204134e82ce75b1109cc1913d81abc6',\n                    'a08e24cff451d628df797efc4343e13c']\n\nblank_slides = \"3790f55cad63053e956fb73027179707\"\n\ndf_marked = pd.read_csv('../input/marked-imgs/marked_images.csv')\nprint(df.shape)\ndf_marked.head()\nindex = df.index[df['image_id']=='033e39459301e97e457232780a314ab7'].astype(int)[0]\n#print(index)\nfor i, image_id in enumerate(df_marked['image_id']):\n  df.drop([df.index[df['image_id']==image_id].astype(int)[0]],inplace=True)\n  #print(\"i = \" + str(i))\n  #print(\"image_id = \" + image_id)\n  #print(df.index[df['image_id']==image_id].astype(int)[0])\nfor image_id in low_tiss_slides:\n  #image_id = low_tiss_slides[i]\n  df.drop([df.index[df['image_id']==image_id].astype(int)[0]],inplace=True)\n\nprint(df.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## Get images from pre-processed png files on disk\nif True:\n\n  x_train = np.empty((N_train, 224, 224, 3), dtype=np.uint16)\n  x_val = np.empty((N_val, 224, 224, 3), dtype=np.uint16)\n\n\n  if FIRST_HALF:\n    y_train_tmp = df[0:N_train]['isup_grade'] \n    for i, image_id in enumerate(df['image_id']):\n      if i >= 0 and i < N_train:\n        im = Image.open(\"../input/prostimg224/train_images/\" + image_id + \".png\")\n        x_train[i, :, :, :] = np.array(im)\n        im.close()\n      if i == N_train:\n        break\n      #if i < 20: \n      #  print(image_id)\n      #  print(i)\n      \n  else:\n    j = 0\n    y_train_tmp = df[3000:8000]['isup_grade'] \n    for i, image_id in enumerate(df['image_id']):\n      if i >= 3000 and i < 8000:   \n        im = Image.open(\"train_images/\" + image_id + \".png\")\n        x_train[j, :, :, :] = np.array(im)\n        im.close()\n        j += 1\n      if i == 8000:\n        print(i)\n        break\n  # validation data\n  k= 0\n  for i, image_id in enumerate(df['image_id']):\n    if i >=8000 and i < 9000:\n      im = Image.open(\"../input/prostimg224/train_images/\" + image_id + \".png\")\n      x_val[k, :, :, :] = np.array(im)\n      im.close()\n      k +=1\n    if i == 9000: \n      break\n\n  y_val_tmp = df[8000:9000]['isup_grade']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## double check shapes\nprint(x_train.shape)\nprint(x_val.shape)\nprint(y_train_tmp.shape)\nprint(y_val_tmp.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import gc\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#import tensorflow.keras\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, Flatten\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.applications import DenseNet121\nfrom tensorflow.keras import regularizers\nfrom tensorflow.keras.layers import BatchNormalization\n\ninput_shape = x_train[0].shape\nprint(x_train[0].shape)\nnum_classes = 6","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# make target categorical\ny_train = tensorflow.keras.utils.to_categorical(y_train_tmp, num_classes)\ny_val = tensorflow.keras.utils.to_categorical(y_val_tmp, num_classes)\nprint(y_train.shape)\nprint(y_val.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# normalize images\nx_train = x_train.astype('float16')\nx_val = x_val.astype('float16')\nx_train /= 255\nx_val /= 255","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# get histogram of isup grades in training/val set\n_ , isup_grade_train = np.nonzero(y_train)\n_ , isup_grade_val = np.nonzero(y_val)\nplt.figure()\nplt.hist(isup_grade_train)\nplt.figure()\nplt.hist(isup_grade_val)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Model definition\ndensenet = DenseNet121(\n    weights='../input/img-net-weights/densenet121_weights_tf_dim_ordering_tf_kernels_notop.h5',\n    include_top=False,\n    input_shape=(224,224,3)\n)\n\ndensenetNoweights = DenseNet121(\n    weights= None,\n    include_top=False,\n    input_shape=(224,224,3)\n)\n\ndef build_model_densenet():\n    model = Sequential()\n    model.add(densenet)\n    model.add(layers.GlobalAveragePooling2D())\n    model.add(layers.Dropout(0.75))\n    model.add(layers.Dense(6, activation='softmax'))\n    opt = tensorflow.keras.optimizers.Adam(learning_rate=0.000015)\n    model.compile(\n        loss='categorical_crossentropy',\n        optimizer=opt,\n        metrics=['accuracy']\n    )\n    model.summary()\n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = build_model_densenet()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Data generation\ndef create_datagen():\n    return ImageDataGenerator(\n        zoom_range=0.10,  # random zooming\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=32, seed=20)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## Train model \nif not FIRST:\n  model.load_weights('model_history_8kdensenetDrop08_aug_'+ RUN_NO +'_checkpoint')\n#history = model.fit(x_train, y_train,\n#          batch_size=32,\n#          epochs=15,\n#          verbose=2,\n#          validation_data=(x_val, y_val))\n\n########## AUGMENTATION FIT\nbatch_size = 32\nhistory = model.fit_generator(\n    data_generator,\n    steps_per_epoch= N_train / batch_size,\n    epochs=35,\n    validation_data=(x_val, y_val)\n)\nmodel.save_weights('model_history_8kdensenetDrop08_aug'+ RUN_NO +'_checkpoint')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# plot history\nhistory_df = pd.DataFrame(history.history)\nhistory_df[['loss', 'val_loss']].plot()\nhistory_df[['accuracy', 'val_accuracy']].plot()\nhist_csv_file = \"history_8kdensenetDrop08_aug\" + RUN_NO + \".csv\"\nwith open(hist_csv_file, mode='w') as f:\n    history_df.to_csv(f)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## TESTING dataset\nN_test = 1135\nx_test = np.empty((N_test, 224, 224, 3), dtype=np.uint16)\ny_test_tmp = df[9000:]['isup_grade']\n#  # testing data\nk= 0\nfor i, image_id in enumerate(tqdm(df['image_id'])):\n  if i >=9000:\n    im = Image.open(\"../input/prostimg224/train_images/\" + image_id + \".png\")\n    x_test[k, :, :, :] = np.array(im)\n    im.close()\n    k += 1\n\n\nx_test = x_test.astype('float16')\nx_test /= 255\ny_test = tensorflow.keras.utils.to_categorical(y_test_tmp, num_classes)\nprint(x_test.shape)\nprint(y_test.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Predict on test data\npred = model.predict(x_test,verbose=1)\neval = model.evaluate(x_test,y_test,verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"diff = np.zeros(1135)\nprediction = np.zeros(1135)\ntest_val = np.zeros(1135)\nfor i in range(1135):\n    diff[i] = np.argmax(y_test[i]) - np.argmax(pred[i])\n    prediction[i] = np.argmax(pred[i])\n    test_val[i] = np.argmax(y_test[i])\n\nplt.figure()\nplt.title(\"Difference between prediction and target\")\nplt.hist(diff,bins=21)\nplt.figure()\nplt.title(\"Predicted value histogram\")\nplt.hist(prediction, bins=11)\nplt.figure()\nplt.title(\"Target value histogram\")\nplt.hist(test_val, bins=11)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Test evaluation metrics\n\npred_numbers = np.argmax(pred, axis=-1)\ny_test_numbers = np.argmax(y_test,axis = -1)\n\nunique_test, counts_test = np.unique(y_test_numbers, return_counts=True)\n#print(unique_test)\n#print(counts_test)\n\nN_correct_0 = 0\nN_correct_1 = 0\nN_correct_2 = 0\nN_correct_3 = 0\nN_correct_4 = 0\nN_correct_5 = 0\nfor i in range(N_test):\n  if y_test_numbers[i] == 0:\n      if pred_numbers[i] == 0:\n        N_correct_0 += 1\n  if y_test_numbers[i] == 1:\n      if pred_numbers[i] == 1:\n        N_correct_1 += 1\n  if y_test_numbers[i] == 2:\n      if pred_numbers[i] == 2:\n        N_correct_2 += 1\n  if y_test_numbers[i] == 3:\n      if pred_numbers[i] == 3:\n        N_correct_3 += 1\n  if y_test_numbers[i] == 4:\n      if pred_numbers[i] == 4:\n        N_correct_4 += 1\n  if y_test_numbers[i] == 5:\n    if pred_numbers[i] == 5:\n        N_correct_5 += 1\n\nprint(\"Percentage of correct guess for ISUP grade 0: {:.2f}%\".format((N_correct_0/counts_test[0])*100))\nprint(\"Percentage of correct guess for ISUP grade 1: {:.2f}%\".format((N_correct_1/counts_test[1])*100))\nprint(\"Percentage of correct guess for ISUP grade 2: {:.2f}%\".format((N_correct_2/counts_test[2])*100))\nprint(\"Percentage of correct guess for ISUP grade 3: {:.2f}%\".format((N_correct_3/counts_test[3])*100))\nprint(\"Percentage of correct guess for ISUP grade 4: {:.2f}%\".format((N_correct_4/counts_test[4])*100))\nprint(\"Percentage of correct guess for ISUP grade 5: {:.2f}%\".format((N_correct_5/counts_test[5])*100))\n\n\nprint(\"Standard deviation: {:.3f}\".format(np.std(y_test_numbers-pred_numbers)))\nprint(\"Average error: {:.3f}\".format(np.mean(y_test_numbers-pred_numbers)))","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}