{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Predict prostate cancer grade for a Keras model trained separately","execution_count":null},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import os\nimport shutil\n\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\n# General packages\nimport pandas as pd\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport PIL\nfrom IPython.display import Image, display\nfrom collections import Counter\n\nimport cv2\nimport skimage.io\nfrom tqdm.notebook import tqdm\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import MultiLabelBinarizer\n\nfrom keras.optimizers import Adam\nfrom keras.preprocessing.image import ImageDataGenerator","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf\ntf.test.is_gpu_available()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Load images: test set if actual submission, train set otherwise\ndataTestDir = '/kaggle/input/prostate-cancer-grade-assessment/test_images'\n\nif os.path.exists(dataTestDir):\n    # Test set is available\n    dataDir = dataTestDir\n    labels = pd.read_csv('/kaggle/input/prostate-cancer-grade-assessment/test.csv').set_index('image_id')\n    cropDir = '/kaggle/working/cropped_test_images/'\n    # Create this folder\n    if not os.path.exists(cropDir):\n        os.mkdir(cropDir)\nelse:\n    dataDir = '/kaggle/input/prostate-cancer-grade-assessment/train_images'\n    labels = pd.read_csv('/kaggle/input/prostate-cancer-grade-assessment/train.csv').set_index('image_id')\n    cropDir = '/kaggle/input/crop-images/cropped_train_images/'","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Get cropped images\nTrain images are pre-cropped but test images need to be processed.  \nhttps://www.kaggle.com/lvulliard/crop-images","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def tile(img):\n    result = []\n    shape = img.shape\n    pad0,pad1 = (cropPx - shape[0]%cropPx)%cropPx, (cropPx - shape[1]%cropPx)%cropPx\n    img = np.pad(img,[[pad0//2,pad0-pad0//2],[pad1//2,pad1-pad1//2],[0,0]],\n                constant_values=255)\n    \n    img = img.reshape(img.shape[0]//cropPx,cropPx,img.shape[1]//cropPx,cropPx,3)\n    img = img.transpose(0,2,1,3,4).reshape(-1,cropPx,cropPx,3)\n    \n    if len(img) < cropN:\n        img = np.pad(img,[[0,cropN-len(img)],[0,0],[0,0],[0,0]],constant_values=255)\n    idxs = np.argsort(img.reshape(img.shape[0],-1).sum(-1))[:cropN]\n    img = img[idxs]\n    for i in range(len(img)):\n        result.append({'img':img[i], 'idx':i})\n    return result","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"if os.path.exists(dataTestDir):\n    # Test set is available\n\n    # Parameters for cropping images\n    cropPx= 56\n    cropN = 16\n    assert np.sqrt(cropN) == round(np.sqrt(cropN))\n\n    nbCol = int(np.sqrt(cropN))\n    names = [x.split('.')[0] for x in os.listdir(dataDir)]\n    for name in tqdm(names):\n        img = skimage.io.MultiImage(os.path.join(dataDir+'/',name+'.tiff'))[-1]\n        tiles = tile(img)\n        stackImg = np.vstack([np.hstack([tiles[nbCol*col + row]['img'] for row in range(nbCol)])\n                   for col in range(nbCol)])\n        cv2.imwrite(cropDir+name+'.png', stackImg)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Model inference\nSee here for model training: https://www.kaggle.com/lvulliard/tune-pre-trained-efficient-b1  \nThe model is then further trained (all weights) for several rounds.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install -qq /kaggle/input/sequencedata/efficientnet-1.1.0-py3-none-any.whl","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import efficientnet.tfkeras\nfrom tensorflow.keras.models import load_model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"inputShape = (224, 224, 3)\n\nmodelFile = \"/kaggle/input/fine-tune-efficient-b1-2nd-step/B1_100_r100.model\"\nmyModel = load_model(modelFile)\nmyModel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"testDF = pd.DataFrame(list(zip(labels.index + \".png\")), columns =['x_col']) \n# Uncomment the following to fasten local test (otherwise prediction takes about one minute)\n# if not os.path.exists(dataTestDir):\n#     testDF = testDF[:2050]\n\nnbSteps = testDF.shape[0]\n\ntestDatagen = ImageDataGenerator() \ntestGenerator = testDatagen.flow_from_dataframe(testDF, x_col=\"x_col\", y_col=None, directory=cropDir, # this is the target directory \n                                                batch_size=256, class_mode=None, shuffle=False,\n                                                target_size=(inputShape[0], inputShape[1]), \n                                                color_mode='rgb')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds = myModel.predict_generator(testGenerator,steps=nbSteps/256)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Export results\n\n","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"outputDF = pd.DataFrame([np.argmax(preds[i,:]) for i in range(nbSteps)], \n                        index = labels.index[:nbSteps], columns = [\"isup_grade\"])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"outputDF.to_csv(\"../working/submission.csv\")","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}