{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"_kg_hide-input":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\nimport openslide\nimport os\nimport cv2\nimport PIL\nfrom PIL import Image\nfrom IPython.display import Image, display\nfrom keras.applications.vgg16 import VGG16,preprocess_input\n# Plotly for the interactive viewer (see last section)\nimport plotly.graph_objs as go\nfrom sklearn.metrics import cohen_kappa_score\nfrom sklearn.model_selection import train_test_split\nfrom keras.models import Sequential, Model,load_model\nfrom keras.applications.vgg16 import VGG16,preprocess_input\nfrom keras.applications.resnet50 import ResNet50\nfrom keras.preprocessing.image import ImageDataGenerator,load_img, img_to_array\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Dense, Dropout, Input, Flatten,BatchNormalization,Activation\nfrom keras.layers import GlobalMaxPooling2D\nfrom keras.models import Model\nfrom keras.optimizers import Adam, SGD, RMSprop\nfrom keras.callbacks import ModelCheckpoint, Callback, EarlyStopping, ReduceLROnPlateau\nfrom keras.utils import to_categorical\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom keras.layers.normalization import BatchNormalization\nimport gc\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport skimage.io\nfrom sklearn.model_selection import KFold\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.\nimport tensorflow as tf\nfrom tensorflow.python.keras import backend as K\nsess = K.get_session()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.callbacks.callbacks import ReduceLROnPlateau, EarlyStopping\nimport tensorflow as tf\nfrom sklearn.preprocessing import LabelEncoder\nfrom keras.models import load_model\nfrom keras.applications.xception import Xception\nimport time\nimport seaborn as sns\nfrom sklearn.metrics import roc_curve\nfrom sklearn.metrics import auc","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nfrom numpy.random import seed\nseed(1)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train=pd.read_csv('/kaggle/input/prostate-cancer-grade-assessment/train.csv')\ntrain.head()\ntrain_copy = train.copy()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img=openslide.OpenSlide('/kaggle/input/prostate-cancer-grade-assessment/train_images/2fd1c7dc4a0f3a546a59717d8e9d28c3.tiff')\ndisplay(img.get_thumbnail(size=(512,512)))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img.dimensions","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"patch = img.read_region((18500,4100), 0, (256, 256))\n\n# Display the image\ndisplay(patch)\n# Close the opened slide after use\nimg.close()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train['isup_grade'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"The classes are imbalanced, more severe cases are underrepresented.\n\nLet's start preparing the images for training."},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"labels=[]\ndata=[]\ndata_dir='../input/panda-resized-train-data-512x512/train_images/train_images/'\nfor i in range(train.shape[0]):\n    data.append(data_dir + train['image_id'].iloc[i]+'.png')\n    labels.append(train['isup_grade'].iloc[i])\ndf=pd.DataFrame(data)\ndf.columns=['images']\ndf['isup_grade']=labels","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train, X_val, y_train, y_val = train_test_split(df['images'],df['isup_grade'], test_size=0.20, random_state=42)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train=pd.DataFrame(X_train)\ntrain.columns=['images']\ntrain['isup_grade']=y_train\n\nvalidation=pd.DataFrame(X_val)\nvalidation.columns=['images']\nvalidation['isup_grade']=y_val\n\ntrain['isup_grade']=train['isup_grade'].astype(str)\nvalidation['isup_grade']=validation['isup_grade'].astype(str)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"So the basic preprocessing I've done is:-\n* Normalizing the images.\n* Reshape the images to be of shape 224,224,3\n* Basic image augmentation like rotation, flipping etc."},{"metadata":{"trusted":true},"cell_type":"code","source":"#Image data generator generates varied images with the input data for better prediction for the models\n#shear is avoided since the cancerous cells look like sheared normal cells","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_datagen = ImageDataGenerator(rescale=1./255,rotation_range=40,\n    featurewise_center=True,\n    featurewise_std_normalization=True,\n    #zoom_range=[0.8, 1.2],        \n    horizontal_flip=True, vertical_flip = True,\n    brightness_range=[0.9, 1.1],\n    width_shift_range=1.0,\n    height_shift_range=1.0)#,\n    #validation_split=0.1)\n\n\nval_datagen=train_datagen = ImageDataGenerator(rescale=1./255)\ntrain_generator = train_datagen.flow_from_dataframe(\n    train,\n    x_col='images',\n    y_col='isup_grade',\n    target_size=(224, 224),\n    batch_size=32,\n    shuffle = True,\n    class_mode='categorical')\n\nvalidation_generator = val_datagen.flow_from_dataframe(\n    validation,\n    x_col='images',\n    y_col='isup_grade',\n    target_size=(224, 224),\n    batch_size=32,\n    class_mode='categorical')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"filenames = validation_generator.filenames\nnb_samples = len(filenames)\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#y_true = validation_generator.classes\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#y_true","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#VGG16 model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def vgg16_model( num_classes=None):\n\n    model = VGG16(weights='/kaggle/input/keras-pretrained-models/vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5', include_top=False, input_shape=(224, 224, 3))\n    #x=Dropout(0.2)(model.output)\n    x=Flatten()(model.output)\n    #x =Dense(32, activation = 'relu')(x)\n    output=Dense(num_classes,activation='softmax')(x)\n    model=Model(model.input,output)\n    return model\n\nvgg_conv=vgg16_model(6)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#VGG19 model-- Uncomment last line to run the model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.applications.vgg19 import VGG19\ndef vgg19_model(num_classes = None):\n    vgg19_weights = '../input/vgg19/vgg19_weights_tf_dim_ordering_tf_kernels_notop.h5'\n    #model = VGG19(weights='imagenet',include_top=False, input_shape=(224, 224, 3))\n    model = VGG19(weights= vgg19_weights , include_top=False, input_shape=(224, 224, 3))\n    x=Dropout(0.3)(model.output)\n    x=Flatten()(x)\n    x =Dense(32, activation = 'relu')(x)\n    x =Dropout(0.2)(x)\n    output=Dense(num_classes,activation='softmax')(x)\n    model=Model(model.input,output)\n    return model\nvgg19_conv = vgg19_model(6)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#InceptionV3 model- Uncomment last line to run the model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.applications.inception_v3 import InceptionV3\ndef InceptionV3_model(num_classes = None):\n    InceptionV3_weights = '../input/inceptionv3/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5'\n    #model = ResNet50(weights='imagenet', include_top = False, input_shape = (224,224,3))\n    model = InceptionV3(weights= InceptionV3_weights, include_top=False, input_shape=(224, 224, 3))\n    #model = InceptionV3(weights='imagenet', include_top = False, input_shape = (224,224,3))\n    x=Dropout(0.3)(model.output)\n    #x=Flatten()(model.output)\n    #x =Dense(64, activation = 'relu')(model.output)\n    #x = tf.compat.v1.keras.layers.GlobalAveragePooling2D()(model.output)\n    x=Flatten()(x)\n    #x =Dropout(0.2)(x)\n    x =Dense(32, activation = 'relu')(x)\n    x =Dropout(0.2)(x)\n    output=Dense(num_classes,activation='softmax')(x)\n    model=Model(model.input,output)\n    return model\nInceptionV3_conv = InceptionV3_model(6)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Resnet50 model- Uncomment last line to run the model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install tensorflow==2.1.0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.applications.resnet50 import ResNet50\ndef ResNet50_model(num_classes = None):\n    ResNet_weights = '../input/keras-pretrained-models/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5'\n    #model = ResNet50(weights='imagenet', include_top = False, input_shape = (224,224,3))\n    model = ResNet50(weights= ResNet_weights, include_top=False, input_shape=(224, 224, 3))\n    #x=Dropout(0.2)(model.output)\n    #x = GlobalAveragePooling2D()(model.output)\n    x=Flatten()(model.output)\n    #x =Dropout(0.2)(x)\n    x =Dense(16, activation = 'relu')(x)\n    x =Dropout(0.2)(x)\n    output=Dense(num_classes,activation='softmax')(x)\n    model=Model(model.input,output)\n    return model\nResNet50_conv = ResNet50_model(6)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#InceptionV3_conv,ResNet50_conv","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.applications import InceptionResNetV2\ndef InceptionResnet_model(num_classes = None):\n    InceptionResnet_weights = '../input/keras-pretrained-models/inception_resnet_v2_weights_tf_dim_ordering_tf_kernels_notop.h5'\n    #model = inception_resnet_v2(weights='imagenet', include_top = False, input_shape = (224,224,3))\n    model = InceptionResNetV2(weights= InceptionResnet_weights, include_top=False, input_shape=(224, 224, 3))\n    #x=Dropout(0.2)(model.output)\n    #x = GlobalAveragePooling2D()(model.output)\n    x=Flatten()(model.output)\n    #x =Dropout(0.2)(x)\n    x =Dense(16, activation = 'relu')(x)\n    x =Dropout(0.2)(x)\n    output=Dense(num_classes,activation='softmax')(x)\n    model=Model(model.input,output)\n    return model\nInceptionResnet_conv = InceptionResnet_model(6)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Let's take a look at the architecture."},{"metadata":{"trusted":true},"cell_type":"code","source":"#Uncomment any one to run the corresponding summary","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#vgg_conv.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#vgg19_conv.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n#InceptionV3_conv.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#ResNet50_conv.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#InceptionResnet_conv.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Including batch Normalization","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def freeze(model):\n    # freeze layers before 99\n    for layer in model.layers[:99]:\n        layer.trainable = False\n        if layer.name.startswith('batch_normalization'):\n            layer.trainable = True\n        if layer.name.endswith('bn'):\n            layer.trainable = True\n\n    # unfreeze layers after 99\n    for layer in model.layers[99:]:\n        layer.trainable = True\n        \n\n        \n        \n        ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"freeze(vgg_conv)\nfreeze(vgg19_conv)\nfreeze(InceptionV3_conv)\nfreeze(ResNet50_conv)\nfreeze(InceptionResnet_conv)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#y_pred = np.argmax(InceptionV3_conv.predict_generator(validation_generator, steps= len(validation_generator)), axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#kappa score is the metric we use since two types of evaluation is done on the data set \n\n#The kappa statistic.\n#According to Cohen's original article, \n#values ≤ 0 as indicating no agreement and 0.01–0.20 as none to slight,\n#0.21–0.40 as fair, 0.41– 0.60 as moderate,\n#0.61–0.80 as substantial, \n#0.81–1.00 as almost perfect agreement.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#def kappa_score(y_true, y_pred):\n    \n    #y_true=tf.math.argmax(y_true)\n    #y_pred=tf.math.argmax(y_pred)\n    #return tf.compat.v1.py_func(cohen_kappa_score,(y_true, y_pred),tf.double)\n    #return tf.compat.v1.py_func(cohen_kappa_score,(y_true,y_pred),tf.double)\n    #return (y_true,y_pred)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n    ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Hyperparameter Tuning "},{"metadata":{"trusted":true},"cell_type":"code","source":"opt = Adam(lr= 0.0001)\nvgg_conv.compile(loss='binary_crossentropy',optimizer=opt,metrics=['accuracy'])\nvgg19_conv.compile(loss='binary_crossentropy',optimizer=opt,metrics=['accuracy'])\nInceptionV3_conv.compile(loss='binary_crossentropy',optimizer=opt,metrics=['accuracy'])\nResNet50_conv.compile(loss='binary_crossentropy',optimizer=opt,metrics=['accuracy'])\nInceptionResnet_conv.compile(loss='binary_crossentropy',optimizer=opt,metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"nb_epochs = 30\nbatch_size=16\n#nb_train_steps = train.shape[0]//batch_size\n#nb_val_steps=validation.shape[0]//batch_size\nnb_train_steps = 128\nnb_val_steps = 64\nprint(\"Number of training and validation steps: {} and {}\".format(nb_train_steps,nb_val_steps))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"vgg_conv.fit_generator( train_generator,steps_per_epoch=nb_train_steps,epochs=30,validation_data=validation_generator,\nvalidation_steps=128)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#generator to activate the augmentation.\n#callbacks = [ReduceLROnPlateau(monitor='val_loss', patience=1, verbose=1, factor=0.5),\n             #EarlyStopping(monitor='val_loss', patience=3),\n             #ModelCheckpoint(filepath='best_model.h5', monitor='val_loss', save_best_only=True)]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=\"./logs\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"vgg19_conv.fit_generator( train_generator,steps_per_epoch=nb_train_steps,epochs=nb_epochs,validation_data=validation_generator,validation_steps=nb_val_steps)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history =InceptionV3_conv.fit_generator( train_generator,steps_per_epoch=nb_train_steps,epochs=nb_epochs,validation_data=validation_generator,\nvalidation_steps=nb_val_steps)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nResNet50_conv.fit_generator( train_generator,steps_per_epoch=nb_train_steps,epochs=30,validation_data=validation_generator,\nvalidation_steps=nb_val_steps)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = InceptionResnet_conv.fit_generator( train_generator,steps_per_epoch=nb_train_steps,epochs=30,validation_data=validation_generator,\nvalidation_steps=nb_val_steps)","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":{"trusted":true},"cell_type":"code","source":"","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":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np \nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.applications import InceptionV3, VGG19, ResNet50\nfrom tensorflow.keras.applications.inception_v3 import preprocess_input as process_inception_v3\nfrom tensorflow.keras.applications.vgg19 import preprocess_input as process_vgg19\nfrom tensorflow.keras.applications.resnet50 import preprocess_input as process_resnet\nfrom tensorflow.keras.models import *\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.callbacks import *\nfrom tensorflow.keras.optimizers import *\n\nimport cv2\nimport random\nimport itertools\nimport os\n\nfrom sklearn.metrics import classification_report, confusion_matrix","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"### UTILITY FUNCTION TO LOAD BASE MODELS ###\n\ndef import_base_model(SHAPE):\n    #InceptionV3_weights = '../input/inceptionv3/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5'\n    inception_v3 =InceptionV3(weights= '../input/inceptionv3/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5',include_top = False, input_shape = SHAPE)\n    #vgg19_weights = '../input/vgg19/vgg19_weights_tf_dim_ordering_tf_kernels_notop.h5'\n    vgg19 = VGG19(weights = '../input/vgg19/vgg19_weights_tf_dim_ordering_tf_kernels_notop.h5', include_top = False, input_shape = SHAPE)\n    #ResNet_weights = '../input/keras-pretrained-models/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5'\n    resnet = ResNet50(weights = '../input/keras-pretrained-models/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5' , include_top = False, input_shape = SHAPE)\n\n    #for layer in inception_v3.layers[:-4]:\n        #layer.trainable = False\n\n    #for layer in vgg19.layers[:-5]:\n     #   layer.trainable = False\n\n    #for layer in resnet.layers[:-10]:\n     #   layer.trainable = False\n        \n    return inception_v3, vgg19, resnet","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"### LOAD BASE MODELS ###\nSHAPE=(224, 224, 3)\ninception_v3, vgg19, resnet = import_base_model(SHAPE)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n\n\ninp = Input((224,224,3))\n\ninception_v3_process = Lambda(process_inception_v3)(inp)\ninception_v3 = inception_v3(inception_v3_process)\nx_inception_v3 = GlobalMaxPool2D()(inception_v3)\nx_inception_v3 = Dense(128, activation='relu')(x_inception_v3)\n\nresnet_process = Lambda(process_resnet)(inp)\nres_net = resnet(resnet_process)\nx_resnet = GlobalMaxPool2D()(res_net)\nx_resnet = Dense(128, activation='relu')(x_resnet)\n\nvgg_19_process = Lambda(process_vgg19)(inp)\nvgg_19 = vgg19(vgg_19_process)\nx_vgg_19 = GlobalMaxPool2D()(vgg_19)\nx_vgg_19 = Dense(128, activation='relu')(x_vgg_19)\n\nx = Concatenate()([x_inception_v3, x_resnet, x_vgg_19])\nout = Dense(6, activation='softmax')(x)\n\nmodel = Model(inp, out)\nmodel.compile(loss='categorical_crossentropy', optimizer=Nadam(lr=1e-4), metrics='accuracy')\n\nes = EarlyStopping(monitor='val_accuracy', mode='auto', restore_best_weights=True, verbose=1, patience=7)\nmodel.fit(train_generator, steps_per_epoch = train_generator.samples/train_generator.batch_size,\n          epochs=50, validation_data=validation_generator, validation_steps = validation_generator.samples/validation_generator.batch_size, \n          callbacks=[es], verbose = 1)","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":{"trusted":true},"cell_type":"code","source":"","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":{"trusted":true},"cell_type":"code","source":"","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":{"trusted":true},"cell_type":"code","source":"","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":{"trusted":true},"cell_type":"code","source":"","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":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#history = InceptionResnet_conv.fit_generator( train_generator,steps_per_epoch=nb_train_steps,epochs=2,validation_data=validation_generator,\n#validation_steps=nb_val_steps, callbacks = callbacks)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def show_history(history):\n    fig, ax = plt.subplots(1, 3, figsize=(15,5))\n    ax[0].set_title('loss')\n    ax[0].plot(history.epoch, history.history[\"loss\"], label=\"Train loss\")\n    ax[0].plot(history.epoch, history.history[\"val_loss\"], label=\"Validation loss\")\n    ax[1].set_title('kappa_keras')\n    ax[1].plot(history.epoch, history.history[\"kappa_keras\"], label=\"Train Quadratic Kappa score\")\n    ax[1].plot(history.epoch, history.history[\"val_kappa_keras\"], label=\"Validation Quadratic Kappa score\")\n    ax[2].set_title('accuracy')\n    ax[2].plot(history.epoch, history.history[\"accuracy\"], label=\"Train acc\")\n    ax[2].plot(history.epoch, history.history[\"val_accuracy\"], label=\"Validation accuracy\")\n    ax[0].legend()\n    ax[1].legend()\n    ax[2].legend()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"show_history(history)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#vgg_baseline = Model.save('VGG16_Baseline.h5')  # creates a HDF5 file 'my_model.h5'\n#InceptionV3_baseline =InceptionV3_conv.save('InceptionV3_Baseline.h5')  # creates a HDF5 file 'my_model.h5'\n#Resnet50_baseline =ResNet50_conv.save('ResNet50_Baseline.h5')  # creates a HDF5 file 'my_model.h5'\n#InceptionResnet_baseline =InceptionResnet_conv.save('InceptionResnet_Baseline.h5')  # creates a HDF5 file 'my_model.h5'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#vgg_baseline_weights = Model.save_weights('vgg_baseline_weights.h5')\n#InceptionV3_weights =InceptionV3_conv.save_weights('InceptionV3_weights.h5')  # creates a HDF5 file 'my_model.h5'\n#Resnet50_weights =ResNet50_conv.save_weights('Resnet50_weights.h5')  # creates a HDF5 file 'my_model.h5'\n#InceptionResnet_weights =InceptionResnet_conv.save_weights('InceptionResnet_weights.h5')  # creates a HDF5 file 'my_model.h5'","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Inference\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"os.listdir('.')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#InceptionV3_conv.load_weights(\"best_model.h5\")\n#InceptionResnet_conv.load_weights(\"best_model.h5\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def predict_submission(df, path, passes=1):\n    \n    df[\"image_path\"] = [path+image_id+\".tiff\" for image_id in df[\"image_id\"]]\n    df[\"isup_grade\"] = 0\n    \n    for idx, row in df.iterrows():\n        prediction_per_pass = []\n        for i in range(passes):\n            model_input = np.array([get_random_samples(row.image_path)/255.])\n            input_image1 = model_input[:,0,:,:]\n            input_image2 = model_input[:,1,:,:]\n            input_image3 = model_input[:,2,:,:]\n\n            prediction = InceptionResnet_conv.predict([input_image1,input_image2,input_image3])\n            prediction_per_pass.append(np.argmax(prediction))\n            \n        df.at[idx,\"isup_grade\"] = np.mean(prediction_per_pass)\n    df = df.drop('image_path', 1)\n    return df[[\"image_id\",\"isup_grade\"]]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# submission code from https://www.kaggle.com/frlemarchand/high-res-samples-into-multi-input-cnn-keras\ndef predict_submission(df, path):\n    \n    df[\"image_path\"] = [path+image_id+\".tiff\" for image_id in df[\"image_id\"]]\n    df[\"isup_grade\"] = 0\n    predictions = []\n    for idx, row in df.iterrows():\n        print(row.image_path)\n        img=skimage.io.imread(str(row.image_path))\n        img = cv2.resize(img, (224,224))\n        img = cv2.resize(img, (224,224))\n        img = img.astype(np.float32)/255.\n        img=np.reshape(img,(1,224,224,3))\n       \n    \n        prediction=InceptionResnet_conv.predict(img)\n        predictions.append(np.argmax(prediction))\n            \n    df[\"isup_grade\"] = predictions\n    df = df.drop('image_path', 1)\n    return df[[\"image_id\",\"isup_grade\"]]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_path = \"../input/prostate-cancer-grade-assessment/test_images/\"\nsubmission_df = pd.read_csv(\"../input/prostate-cancer-grade-assessment/sample_submission.csv\")\n\nif os.path.exists(test_path):\n    test_df = pd.read_csv(\"../input/prostate-cancer-grade-assessment/test.csv\")\n    submission_df = predict_submission(test_df, test_path)\nelse:\n    print('submission csv not found')\n\n    \ndel vgg16\nsubmission_df.to_csv('submission.csv', index=False)\nsubmission_df.head()","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}