{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"markdown","source":"**Diabetic RetinopathyDetection**\n\nThis Notebook aims to provide a prediction kernel using Transfer learning - Fine Tuned VGG-16 architecture.\n"},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"#All Necessary Imports\nimport numpy as np\nimport os\nimport time\nfrom keras.applications.vgg16 import VGG16\nfrom keras.preprocessing import image\nfrom keras.applications.vgg16 import preprocess_input\nfrom keras.layers import Dense, Activation, Flatten\nfrom keras.layers import merge, Input\nfrom keras.models import Model\nfrom keras.utils import np_utils\nfrom sklearn.utils import shuffle\nfrom sklearn.model_selection import train_test_split\n","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"f837a829c9e7259b7ca0f90df9e386bc2d31c14d"},"cell_type":"markdown","source":"**Model Selection**\n\nWe load the base model, which is a VGG-16 model pretrained on imagenet weights.\nWe then move on to freeze all the layers except the last three."},{"metadata":{"trusted":true,"_uuid":"8d56ae07b9763a4f88268c40010ab39122269f94"},"cell_type":"code","source":"#loading base model\nbase_model = VGG16(weights='imagenet', include_top=True, input_shape=(224, 224, 3))\n#freeze_layers(base_model)\nbase_model.summary()\n#model = Model(input=base_model.input, output=base_model.get_layer('fc1').output)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"24c422b317327eb7249423ac1390e75d4d4d3faf"},"cell_type":"code","source":"# Freeze the layers except the last 4 layers\nfor layer in base_model.layers[:-3]:\n    layer.trainable = False\n# Check the trainable status of the individual layers\nfor layer in base_model.layers:\n    print(layer, layer.trainable)\nbase_model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"47639d9f4fa6b80db2b910dd6b013b43b678b101"},"cell_type":"code","source":"from keras.utils.vis_utils import plot_model\nplot_model(base_model, to_file='base_model_plot.png', show_shapes=True, show_layer_names=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a42faec3474658cf69dcb6ada7d2acfbb2f153de"},"cell_type":"code","source":"from IPython.display import SVG\nfrom keras.utils.vis_utils import model_to_dot\n\nSVG(model_to_dot(base_model).create(prog='dot', format='svg'))","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"af26cb090ff973cc094397446370cdbf1ed56283"},"cell_type":"markdown","source":"Before we go about pre processing data and training our loaded model, we fix the following\n* Batch Size of the data required for training\n* nb_classes -> indicates the number of output classes\n* nb_epoch -> induicates the number of iterations during training "},{"metadata":{"trusted":true,"_uuid":"4030c44b8ad57afb0886a6533b5678087a40e6c9"},"cell_type":"code","source":"#batch_size to train\nbatch_size = 32\n# number of output classes\nnb_classes = 5\n# number of epochs to train\nnb_epoch = 10","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"fc84351c44f6c733e8631f64e84b666e96876ee0"},"cell_type":"markdown","source":"**Fine Tune : VGG-16**\n\nWe move on to add customised layers on top of our pre-loaded model for purpose of fine-tuning.\nThe following layers were added :\n* Dense Relu\n* Dropout\n* Dense Softmax"},{"metadata":{"trusted":true,"_uuid":"7673e1a0abe534fde8994df62af6950a820fbe1b"},"cell_type":"code","source":"from keras import models\nfrom keras import layers\nfrom keras import optimizers\n \n# Create the model\nmodel = models.Sequential()\n \n# Add the vgg convolutional base model\nmodel.add(base_model)\n \n# Add new layers\nmodel.add(layers.Dense(1024, activation='relu'))\nmodel.add(layers.Dropout(0.5))\nmodel.add(layers.Dense(nb_classes, activation='softmax', name ='output'))\n \n# Show a summary of the model. Check the number of trainable parameters\nmodel.summary()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"95ac78abba21a8d5347302e1a915fd7ecdfd3978"},"cell_type":"code","source":"from keras.utils.vis_utils import plot_model\nplot_model(model, to_file='finetune_model_plot.png', show_shapes=True, show_layer_names=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"61255aa57405a8f62314509b65020a7bd4879318"},"cell_type":"code","source":"from IPython.display import SVG\nfrom keras.utils.vis_utils import model_to_dot\n\nSVG(model_to_dot(model).create(prog='dot', format='svg'))","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"3a8765f628e9c6de3f80aa6ee83ffdb356211e71"},"cell_type":"markdown","source":"Loading the dataset"},{"metadata":{"trusted":true,"_uuid":"3bcee53a7b21398bd6709ecddbdcc12e75b1696f"},"cell_type":"code","source":"import pandas as pd\ntrainLabels = pd.read_csv(\"../input/trainLabels.csv\")\ntrainLabels.head()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"5df3e41a74a51ba3dd562d6c720cb2b7571015fe"},"cell_type":"markdown","source":"**Finding class distribution**"},{"metadata":{"trusted":true,"_uuid":"089e008813aaa24cf8c8a5eaa6ff7414400612f8"},"cell_type":"code","source":"import seaborn as sns\nsns.countplot(\"level\",data= trainLabels)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"e9719df37b7ed86cfa3babb9c0f55811375361e4"},"cell_type":"markdown","source":"The dataset is highly imbalanced with maximum data having severity 0, i.e., no Diabetic Retinopathy"},{"metadata":{"trusted":true,"_uuid":"804fc97a50d5b9722c3365ff614a06cbe7e2622d"},"cell_type":"code","source":"#from imblearn.over_sampling import SMOTE\n\n#print(\"Before OverSampling, counts of severity '0': {}\".format(sum(trainLabels.level==0)))\n#print(\"Before OverSampling, counts of severity '1': {} \".format(sum(trainLabels.level==1)))\n#print(\"Before OverSampling, counts of severity '2': {}\".format(sum(trainLabels.level==2)))\n#print(\"Before OverSampling, counts of severity '3': {} \".format(sum(trainLabels.level==3)))\n#print(\"Before OverSampling, counts of severity '4': {} \".format(sum(trainLabels.level==4)))\n\n#sm = SMOTE(random_state=2)\n#trainLables.image, trainLabels.level = sm.fit_sample(trainLabels.image, trainLabels.level.ravel())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"7dbf379333217bfd444521ce2aeac37f21cd9fe8"},"cell_type":"code","source":"import os\n\nlisting = os.listdir(\"../input\") \nlisting.remove(\"trainLabels.csv\")\nnp.size(listing)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"7e116a90ccb86412fa6f0a29030151f594851fec"},"cell_type":"markdown","source":"**Image to Numpy Array**"},{"metadata":{"trusted":true,"_uuid":"5bc7b700d54150a06643ed138f9ae5caaae3517c"},"cell_type":"code","source":"from PIL import Image\n\n# input image dimensions\nimg_rows, img_cols = 224, 224\n\nimmatrix = []\nimlabel = []\n\nfor file in listing:\n    base = os.path.basename(\"../input/\" + file)\n    fileName = os.path.splitext(base)[0]\n    imlabel.append(trainLabels.loc[trainLabels.image==fileName, 'level'].values[0])\n    im = Image.open(\"../input/\" + file)   \n    img = im.resize((img_rows,img_cols))\n    rgb = img.convert('RGB')\n    immatrix.append(np.array(rgb).flatten())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f59d2779594bdb4776b407c1237dc34f644124e7"},"cell_type":"code","source":"\nfrom sklearn.utils import shuffle\n\n#converting images & labels to numpy arrays\nimmatrix = np.asarray(immatrix)\nimlabel = np.asarray(imlabel)\n\n\ndata,Label = shuffle(immatrix,imlabel, random_state=2)\ntrain_data = [data,Label]\ntype(train_data)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"7b95e0f0ada75a660da9e3e450b2f78891f56a5e"},"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport matplotlib\nfor i in range (10):\n    img=immatrix[i].reshape(img_rows,img_cols,3)\n    print('severity',imlabel[i])\n    if(imlabel[i]>0):\n        plt.imshow(img)\n    ","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"1060415f9d521e181b599f0b34f7ebb48296a2ca"},"cell_type":"markdown","source":"Splitting Dataset to training and test samples"},{"metadata":{"trusted":true,"_uuid":"222cc4e13c159543d069f15f72f8e72ba73c1c51"},"cell_type":"code","source":"(X, y) = (train_data[0],train_data[1])\nfrom sklearn.cross_validation import train_test_split\n\n# STEP 1: split X and y into training and testing sets\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=4)\n\nX_train = X_train.reshape(X_train.shape[0], img_cols, img_rows, 3)\nX_test = X_test.reshape(X_test.shape[0], img_cols, img_rows, 3)\n\n\nprint(X_train.shape)\nprint(y_train.shape)\nprint(X_test.shape)\nprint(y_test.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"daf6d77753c0afa518ae65607f5b773de0400969"},"cell_type":"code","source":"# X_train = X_train.reshape(X_train.shape[0], img_cols, img_rows, 3)\n# X_test = X_test.reshape(X_test.shape[0], img_cols, img_rows, 3)\n\nX_train = X_train.astype('float32')\nX_test = X_test.astype('float32')\n\nX_train /= 255\nX_test /= 255\n\nprint('X_train shape:', X_train.shape)\nprint(X_train.shape[0], 'train samples')\nprint(X_test.shape[0], 'test samples')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"ff03f69142342b658c2a54c38b74639f91c5abcb"},"cell_type":"code","source":"from keras.utils import np_utils\n\n# convert class vectors to binary class matrices\nY_train = np_utils.to_categorical(y_train, nb_classes)\nY_test = np_utils.to_categorical(y_test, nb_classes)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"15fbe038329a213ca226014719817439f3db0ce3"},"cell_type":"markdown","source":"**Performing Image augmentation**"},{"metadata":{"trusted":true,"_uuid":"7a90aabe61bb4a587953ce6563a6b1f37fcb5a76"},"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\n\n# create generators  - training data will be augmented images\nvalidationdatagenerator = ImageDataGenerator()\ntraindatagenerator = ImageDataGenerator(width_shift_range=0.1,height_shift_range=0.1,rotation_range=15,zoom_range=0.1 )\n\nbatchsize=8\ntrain_generator=traindatagenerator.flow(X_train, Y_train, batch_size=batchsize) \nvalidation_generator=validationdatagenerator.flow(X_test, Y_test,batch_size=batchsize)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f6f0b91bed8c737378199ad5b856edb3733a9caa"},"cell_type":"code","source":"model.compile(loss='categorical_crossentropy',\n              optimizer='adam',\n              metrics=['acc'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"88db458f4387d3309fbaa79c3f3fd9793b792f6c","scrolled":true},"cell_type":"code","source":"history= model.fit_generator(train_generator, steps_per_epoch=int(len(X_train)/batchsize), \n                    epochs=10, validation_data=validation_generator, \n                    validation_steps=int(len(X_test)/batchsize))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"dc613ad29cbd3b6367796f74252bd26e3c0ec420"},"cell_type":"code","source":"# summarize history for accuracy\nplt.plot(history.history['acc'])\nplt.plot(history.history['val_acc'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()\nplt.savefig('model_accuracy.png')\n# summarize history for loss\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()\nplt.savefig('model_loss.png')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"dc28517eee262e2bc468d9474a2ab68aaf356339"},"cell_type":"code","source":"score = model.evaluate(X_test, Y_test, verbose=0)\nprint(score)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"74f26e64b86baa85d6d4ef67fa260963a1a2bbcf"},"cell_type":"code","source":"from keras.models import load_model\nmodel.save('retinopathy_predict.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"607078bb11b9469d6130977cca2b2a826ff07bc7"},"cell_type":"code","source":"print(X_train.shape)\nprint(X_test[0].shape)\ny_pred = []\np = 100\nfor i in range (200):\n    image = X_train[i]\n    imagematrix =  np.asarray(image)\n    #img1=imagematrix.reshape(img_rows,img_cols,3)\n    #plt.imshow(img1)\n    #print(imagematrix.shape)\n    imagepredict = np.expand_dims(imagematrix, axis=0)\n    #print(imagepredict.shape)\n    y_pred1 = model.predict(imagepredict)\n    y_pred2 = [x * p for x in y_pred1]\n    y_pred3 = np.max(y_pred2)\n    y_pred.append(y_pred3)\n    print(y_pred3)\ny_pred = np.asarray(y_pred)\n    \n    \n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"c16306afd796d701f2241fdff9859044fe75e1f5"},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"af73b805d2eeb8b466dec8503f658ead75198279"},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}