{"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 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)))\nimg.dimensions\npatch = 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_test, y_train, y_test = train_test_split(df['images'],df['isup_grade'], test_size=0.2, 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\ntest=pd.DataFrame(X_test)\ntest.columns=['images']\ntest['isup_grade']=y_test\n\ntrain['isup_grade']=train['isup_grade'].astype(str)\ntest['isup_grade']=test['isup_grade'].astype(str)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train, X_val, y_train, y_val = train_test_split(train['images'],train['isup_grade'], test_size=0.1, random_state=42)","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":"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=test_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=16,\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=16,\n    class_mode='categorical')\ntest_generator = test_datagen.flow_from_dataframe(\n    test,\n    x_col='images',\n    y_col='isup_grade',\n    target_size=(224, 224),\n    batch_size=16,\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","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\n#vgg_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\nimport keras \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    model =keras.applications.VGG19(include_top=False, weights='imagenet', \n                                       input_tensor=None,  input_shape=(224, 224, 3), \n                                       pooling=None, classes=1000)\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(512, 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\n#InceptionV3_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(512, 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\n#ResNet50_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/inceptionresnetv2/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(512, 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\n#InceptionResnet_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":"#Including batch Normalization","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def freeze(model,at):\n    # freeze layers before 99\n    for layer in model.layers[:at]:\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[at:]:\n        layer.trainable = True\n \n       \n        ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#freeze(vgg16_conv)\nfreeze(vgg19_conv,20)\n#freeze(InceptionV3_conv,150)\n#freeze(ResNet50_conv,140)","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":{},"cell_type":"markdown","source":"Hyperparameter Tuning "},{"metadata":{"trusted":true},"cell_type":"code","source":"opt = Adam(lr= 0.0001)\n#vgg_conv.compile(loss='binary_crossentropy',optimizer=opt,metrics=[kappa_keras, 'accuracy'])\nvgg19_conv.compile(loss='categorical_crossentropy',optimizer=opt,metrics=['accuracy'])\n#InceptionV3_conv.compile(loss='binary_crossentropy',optimizer=opt,metrics=['accuracy'])\n#ResNet50_conv.compile(loss='binary_crossentropy',optimizer=opt,metrics=['accuracy'])\n#InceptionResnet_conv.compile(loss='binary_crossentropy',optimizer=opt,metrics=[kappa_score,kappa_keras, '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))\n#train_generator, test_generator, validation_generator = dataGen(batch_size)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#generator to activate the augmentation.\nReduceLROnPlateau(monitor='val_loss', patience=1, verbose=1, factor=0.5)\ncallbacks = [EarlyStopping(monitor='val_loss', patience=5),\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=10,\n                         validation_data=validation_generator, validation_steps=nb_val_steps,\n                         callbacks = callbacks)\n\nvgg19_conv.save('vgg19_conv.h5')\n_, test_acc = vgg19_conv.evaluate(test_generator, verbose=0)\nprint('Test by vgg_model-1: %.3f' % (test_acc))","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,\n                                        validation_data=validation_generator,validation_steps=nb_val_steps, \n                                        callbacks = callbacks)\n\nInceptionV3_conv.save('InceptionV3_conv.h5')\n_, test_acc = InceptionV3_conv.evaluate(test_generator, verbose=0)\nprint('Test by vgg_model-1: %.3f' % (test_acc))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ResNet50_conv.fit_generator( train_generator,steps_per_epoch=nb_train_steps,epochs=25,\n                            validation_data=validation_generator,validation_steps=nb_val_steps, \n                            callbacks = callbacks)\n\nResNet50_conv.save('ResNet50_conv.h5')\n_, test_acc = ResNet50_conv.evaluate(test_generator, verbose=0)\nprint('Test by vgg_model-1: %.3f' % (test_acc))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_generator, test_generator, validation_generator = dataGen(612) \ntest_generator.reset()\ntest_Images, test_labels = test_generator.next()\ntrain_generator, test_generator, valid_generator = dataGen(305)\nvalidation_Images, validation_labels = valid_generator.next() ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.metrics import confusion_matrix\nfrom imblearn.metrics import sensitivity_specificity_support\nfrom sklearn.metrics import classification_report\nfrom imblearn.metrics import geometric_mean_score\n#from keras.models import load_model\nfrom tensorflow.keras.models import load_model\n# load models from file\n#path='../input/stack-cnn-submodels/fold4/fold2/'\ndef load_all_models():\n    all_models = list() \n    model = load_model('./ResNet50_conv.h5')\n    all_models.append(model)\n    model = load_model('./vgg19_conv.h5')\n    all_models.append(model)\n    model = load_model('./InceptionV3_conv.h5')\n    all_models.append(model) \n    return all_models\n\nmembers = load_all_models()\nprint('Loaded %d models' % len(members))\ntestX, testy = test_Images, test_labels\n# evaluate standalone models on test dataset\ntesty1 = np.argmax(testy,axis=1)\nfor model in members:\n\ttesty_enc = to_categorical(testy)\n\t_, acc = model.evaluate(testX, testy, verbose=0)\n\t#print('Model Accuracy: %.3f' % acc)\n\tyhat=pred = model.predict(testX, steps=None, callbacks=None, max_queue_size=10, workers=1, use_multiprocessing=False, verbose=0)\n\tyhat1=np.argmax(yhat,axis=1)\n\tGmean = geometric_mean_score(testy1, yhat1, average='multiclass')\n\tresult = sensitivity_specificity_support(testy1, yhat1, average='macro')\n\tresult = sensitivity_specificity_support(testy1, yhat1, average='macro')\n\tprint(\"Sensitivity: {:5.2f}%\".format(100*result[0]), \"specificity {:5.2f}%\".format(100*result[1]), \n      \"Accuracy: {:5.2f}%\".format(100*acc),\"Gmean: {:5.2f}%\".format(100*Gmean))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# stacked generalization with linear meta model on blobs dataset\nfrom sklearn.datasets import make_blobs\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.linear_model import LogisticRegression\nfrom keras.models import load_model\nfrom keras.utils import to_categorical\nfrom numpy import dstack\n# create stacked model input dataset as outputs from the ensemble\ndef stacked_dataset(members, inputX):\n\tstackX = None\n\tfor model in members:\n\t\t# make prediction\n\t\tyhat = model.predict(inputX, verbose=0)\n\t\t# stack predictions into [rows, members, probabilities]\n\t\tif stackX is None:\n\t\t\tstackX = yhat\n\t\telse:\n\t\t\tstackX = dstack((stackX, yhat))\n\t# flatten predictions to [rows, members x probabilities]\n\tstackX = stackX.reshape((stackX.shape[0], stackX.shape[1]*stackX.shape[2]))\n\treturn stackX\n# fit a model based on the outputs from the ensemble members\ndef fit_stacked_model(members, inputX, inputy):\n\t# create dataset using ensemble\n\tstackedX = stacked_dataset(members, inputX)\n\t# fit standalone model\n\tmodel = LogisticRegression(max_iter=200)\n\tmodel.fit(stackedX, inputy)\n\treturn model\nvalidation_labels1 = np.argmax(validation_labels,axis=1)\n# fit stacked model using the ensemble\nmodel = fit_stacked_model(members, validation_Images, validation_labels1)\n\n# make a prediction with the stacked model\ndef stacked_prediction(members, model, inputX):\n\t# create dataset using ensemble\n\tstackedX = stacked_dataset(members, inputX)\n\t# make a prediction\n\tyhat = model.predict(stackedX)\n\tyscore = model.predict_proba(stackedX)\n\treturn yhat, yscore\n\n# evaluate model on test set\nyhat, yscore = stacked_prediction(members, model, testX)\ntesty1 = np.argmax(testy,axis=1)\nGmean = geometric_mean_score(testy1, yhat, average='multiclass')\nacc = accuracy_score(testy1, yhat)\nresult = sensitivity_specificity_support(testy1, yhat, average='macro')\nprint(\"Sensitivity: {:5.2f}%\".format(100*result[0]), \"specificity {:5.2f}%\".format(100*result[1]), \n      \"Accuracy: {:5.2f}%\".format(100*acc),\"Gmean: {:5.2f}%\".format(100*Gmean))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.metrics import confusion_matrix\nfrom imblearn.metrics import sensitivity_specificity_support\nfrom sklearn.metrics import classification_report\nfrom imblearn.metrics import geometric_mean_score\nimport seaborn as sn\nimport pandas as pd\n\n#test_generator.reset()\n#pred = model2.predict(trainImages, batch_size=None, verbose=0, steps=None, max_queue_size=10, workers=1, use_multiprocessing=False)\ntestX, testy = test_Images, test_labels\n# evaluate standalone models on test dataset\n\n#esty_enc = to_categorical(testy)\n#_, acc = model.predict(testX, testy, verbose=0)\n#print('Model Accuracy: %.3f' % acc)\n\npred_label=yhat\ntrue_label = testy1\n\ntarget_names = ['a',  'b','c','d','e','f']\nresult = sensitivity_specificity_support(true_label, pred_label, average='macro')\n\nprint(\"Sensitivity: {:5.2f}%\".format(100*result[0]), \"specificity {:5.2f}%\".format(100*result[1]), \n      \"Accuracy: {:5.2f}%\".format(100*acc),'\\n')\n\nreport=classification_report(true_label, pred_label, target_names=target_names, digits=4)\nprint(report)\n\nf = open( 'report.txt', 'w' )\nf.write(report)\nf.close()\n\n\ndisp = confusion_matrix(true_label, pred_label)\ndisp.astype('int')\npd.options.display.float_format = '{:.5f}'.format\ndf_cm = pd.DataFrame(disp, target_names, target_names)\n\nfig, ax = plt.subplots(figsize=(4,3))\nsn.set(font_scale=1.2) # for label size\nsn.heatmap(df_cm, annot=True, annot_kws={\"size\": 13},ax=ax, cmap=\"YlGnBu\" , fmt='g',cbar=False)#, fontsize =12)\nplt.ylabel('Actual',fontsize=16,fontweight='bold')\nplt.xlabel('Predicted',fontsize=16,fontweight='bold')\nplt.ioff()\nimport pylab\npylab.savefig('fold_conf_mat.eps', format = 'eps',bbox_inches='tight')\n\n##### Sensivity and PPV ------------------------------------------------------------------------------------\nmatrix = confusion_matrix(true_label, pred_label)\nmatrix = matrix.astype('float')\n#cm_norm = matrix / matrix.sum(axis=1)[:, np.newaxis]\n#print(matrix)\n#class_acc = np.array(cm_norm.diagonal())\n\nGmean = geometric_mean_score(true_label, pred_label, average='multiclass')\nprint('Gmean: {:.4f}'.format(Gmean))\n\nclass_acc = [matrix[i,i]/np.sum(matrix[i,:]) if np.sum(matrix[i,:]) else 0 for i in range(len(matrix))]\nprint('Sens COVID-19: {0:.3f}, Normal: {1:.3f}, Pneumonia: {2:.3f}'.format(class_acc[0], class_acc[1], class_acc[2]))\n                                                                             \nppvs = [matrix[i,i]/np.sum(matrix[:,i]) if np.sum(matrix[:,i]) else 0 for i in range(len(matrix))]\nprint('PPV COVID-19: {0:.3f}, Normal: {1:.3f}, Pneumonia: {2:.3f}'.format(ppvs[0],  ppvs[1], ppvs[2]))","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":"### 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 =tf.keras.applications.InceptionV3(include_top=False, weights='imagenet', input_tensor=None, \n                                                    input_shape=SHAPE, pooling=None, classes=3)\n    #vgg19_weights = '../input/vgg19/vgg19_weights_tf_dim_ordering_tf_kernels_notop.h5'\n    vgg19 = tf.compat.v2.keras.applications.VGG19(include_top=False, weights='imagenet', input_tensor=None, \n                                                  input_shape=SHAPE, pooling=None, classes=1000)\n    #ResNet_weights = '../input/keras-pretrained-models/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5'\n    resnet = tf.keras.applications.resnet50.ResNet50(include_top=False, weights='imagenet', input_tensor=None, \n                                                     input_shape=SHAPE, pooling=None, classes=1000)\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":"inp = 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=5, 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}