{"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\nprint(os.listdir(\"../input\"))\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":{},"cell_type":"markdown","source":"### IMPORT LIBRARY","execution_count":null},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import os, sys\nimport matplotlib.pyplot as plt\nimport cv2\nfrom sklearn.model_selection import train_test_split\nfrom PIL import Image\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nIMG_SIZE = 512","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# INTRODUCTION\n\n![](https://tansuerakgun.com/tr/wp-content/uploads/2017/08/diabetik-retina-tedavisi-1.jpg)\n[Picture Source:](https://tansuerakgun.com/tr/wp-content/uploads/2017/08/diabetik-retina-tedavisi-1.jpg)\n\n The most common cause of blindness due to diabetes is “Diabetic Retinopathy”. Diabetes affects the nerve layer (retina or net layer) of the eye and the capillaries in this layer, disrupting its work and causing vision loss. Retinal disorders due to diabetes are called diabetic retinopathy.\n\n","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"# Basic Data Analysis","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train=pd.read_csv(\"../input/aptos2019-blindness-detection/train.csv\")\ndf_test=pd.read_csv(\"../input/aptos2019-blindness-detection/test.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x=df_train[\"id_code\"]\ny=df_train[\"diagnosis\"]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"labels=[\"Train\",\"Test\"]\nsizes=[len(df_train),len(df_test)]\n\nplt.pie(sizes,labels=labels,autopct='%1.1f%%')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"* Separation of pictures in the data","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.15,random_state=42)\nprint(\"x_train shape: \", x_train.shape)\nprint(\"x_test shape: \", x_test.shape)\nprint(\"y_train shape: \", y_train.shape)\nprint(\"y_test shape: \", y_test.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"* Train, test data distinction and shows shape","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.hist(y_train,label=\"y_train\")\nplt.hist(y_test,label=\"y_test\")\nplt.title(\"Retinopathy Type and number\")\nplt.xlabel(\"0:No DR, 1:Mild, 2:Moderate, 3:Severe, 4:Proliferative DR\")\nplt.ylabel(\"Number\")\nplt.legend()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"* Retinopathy levels of patients","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"# IMAGE PROCESSING","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"### 1- Default and Sorted Image","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":" %%time\nfig = plt.figure(figsize=(25, 16))\n# display 10 images from each class\nfor i in sorted(y_train.unique()):\n    for j, (idx, row) in enumerate(df_train.loc[df_train['diagnosis'] == i].sample(5, random_state=42).iterrows()):\n        ax = fig.add_subplot(5, 5, i * 5 + j + 1, xticks=[], yticks=[])\n        path=f\"../input/aptos2019-blindness-detection/train_images/{row['id_code']}.png\"\n        image = cv2.imread(path)\n        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n        image = cv2.resize(image, (IMG_SIZE, IMG_SIZE))\n        plt.imshow(image)\n        ax.set_title('Label: %d-%d-%s' % (i, idx, row['id_code']) )\n        \n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### 2- Different Colored Pictures and Sorted Image","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nfig=plt.figure(figsize=(25,16))\nfor i in sorted(y_train.unique()):\n    for j ,(idx,row) in enumerate(df_train.loc[df_train[\"diagnosis\"]==i].sample(5,random_state=42).iterrows()):\n        ax = fig.add_subplot(5, 5, i*5+j+1, xticks=[], yticks=[])\n        path=f\"../input/aptos2019-blindness-detection/train_images/{row['id_code']}.png\"\n        image = cv2.imread(path)\n        image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n        image = cv2.resize(image, (IMG_SIZE, IMG_SIZE))\n\n        plt.imshow(image)\n        ax.set_title('Label: %d-%d-%s' % (i, idx, row['id_code']) )","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### 3- Gray Pictures and Sorted Image ","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nfig=plt.figure(figsize=(25,16))\nfor i in sorted(y_train.unique()):\n    for j ,(idx,row) in enumerate(df_train.loc[df_train[\"diagnosis\"]==i].sample(5,random_state=42).iterrows()):\n        ax = fig.add_subplot(5, 5, i*5+j+1, xticks=[], yticks=[])\n        path=f\"../input/aptos2019-blindness-detection/train_images/{row['id_code']}.png\"\n        image = cv2.imread(path)\n        image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n        image = cv2.resize(image, (IMG_SIZE, IMG_SIZE))\n\n        plt.imshow(image,cmap=\"gray\")\n        ax.set_title('Label: %d-%d-%s' % (i, idx, row['id_code']) )","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### A picture with 4.level retinopathy","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"dpi=80\n\npath=f\"../input/aptos2019-blindness-detection/train_images/838c87c63422.png\"\nimage = cv2.imread(path)\nimage=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)\nheight,width=image.shape\nprint(height,width)\nSCALE=2\nfigsize=(width/float(dpi))/SCALE,(height/float(dpi))/SCALE\nimage = cv2.resize(image, (IMG_SIZE, IMG_SIZE))\nfig=plt.figure(figsize=figsize)\nplt.imshow(image,cmap=\"gray\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# BEN GRAHAM'S LIGTHING METHOD","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"fig=plt.figure(figsize=(25,16))\nfor i in sorted(y_train.unique()):\n    for j,(idx,row) in enumerate(df_train.loc[df_train[\"diagnosis\"]==i].sample(5,random_state=42).iterrows()):\n        \n        ax = fig.add_subplot(5, 5, i*5+j+1, xticks=[], yticks=[])\n        path=f\"../input/aptos2019-blindness-detection/train_images/{row['id_code']}.png\"\n        image = cv2.imread(path)\n        image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n        image = cv2.resize(image, (IMG_SIZE, IMG_SIZE))\n        image=cv2.addWeighted ( image,4, cv2.GaussianBlur( image , (0,0) , IMG_SIZE/10) ,-4 ,128) \n\n        plt.imshow(image, cmap='gray')\n        ax.set_title('Label: %d-%d-%s' % (i, idx, row['id_code']) )","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Image Resized (512,512)","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def crop_image_from_gray(img,tol=7):\n    if img.ndim ==2:\n        mask = img>tol\n        return img[np.ix_(mask.any(1),mask.any(0))]\n    elif img.ndim==3:\n        gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n        mask = gray_img>tol\n        \n        check_shape = img[:,:,0][np.ix_(mask.any(1),mask.any(0))].shape[0]\n        if (check_shape == 0): # image is too dark so that we crop out everything,\n            return img # return original image\n        else:\n            img1=img[:,:,0][np.ix_(mask.any(1),mask.any(0))]\n            img2=img[:,:,1][np.ix_(mask.any(1),mask.any(0))]\n            img3=img[:,:,2][np.ix_(mask.any(1),mask.any(0))]\n    #         print(img1.shape,img2.shape,img3.shape)\n            img = np.stack([img1,img2,img3],axis=-1)\n    #         print(img.shape)\n        return img","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def load_ben_color(path, sigmaX=10):\n    image = cv2.imread(path)\n    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n    image = crop_image_from_gray(image)\n    image = cv2.resize(image, (IMG_SIZE, IMG_SIZE))\n    image=cv2.addWeighted ( image,4, cv2.GaussianBlur( image , (0,0) , sigmaX) ,-4 ,128)\n        \n    return image","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Lighting","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"NUM_SAMP=7\nfig = plt.figure(figsize=(25, 16))\nfor i in sorted(y_train.unique()):\n    for j, (idx, row) in enumerate(df_train.loc[df_train['diagnosis'] == i].sample(NUM_SAMP, random_state=42).iterrows()):\n        ax = fig.add_subplot(5, NUM_SAMP, i* NUM_SAMP + j + 1, xticks=[], yticks=[])\n        path=f\"../input/aptos2019-blindness-detection/train_images/{row['id_code']}.png\"\n        image = load_ben_color(path,sigmaX=30)\n\n        plt.imshow(image)\n        ax.set_title('%d-%d-%s' % (i, idx, row['id_code']) )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def load_ben_color2(path, sigmaX=10):\n    image = cv2.imread(path)\n    image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n    image = crop_image_from_gray(image)\n    image = cv2.resize(image, (IMG_SIZE, IMG_SIZE))\n  \n        \n    return image","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Level 4 Retinopathy Image After Image Processing ","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"dpi = 80 #inch\n\npath=f\"../input/aptos2019-blindness-detection/train_images/838c87c63422.png\" \nimage = load_ben_color(path,sigmaX=10)\n\nheight, width = IMG_SIZE, IMG_SIZE\nprint(height, width)\n\nSCALE=1\nfigsize = (width / float(dpi))/SCALE, (height / float(dpi))/SCALE\n\nfig = plt.figure(figsize=figsize)\nplt.imshow(image, cmap='gray')\n\ndpi = 80 #inch\n\npath=f\"../input/aptos2019-blindness-detection/train_images/838c87c63422.png\" \nimage = load_ben_color2(path,sigmaX=10)\n\nheight, width = IMG_SIZE, IMG_SIZE\nprint(height, width)\n\nSCALE=1\nfigsize = (width / float(dpi))/SCALE, (height / float(dpi))/SCALE\n\nfig = plt.figure(figsize=figsize)\nplt.imshow(image, cmap='gray')\n\n\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Comparision of 0.Level and 4.level Diabetic Retinopathy","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"dpi = 80 #inch\n\npath=f\"../input/aptos2019-blindness-detection/train_images/78937523f7a8.png\" \nimage = load_ben_color(path,sigmaX=10)\n\nheight, width = IMG_SIZE, IMG_SIZE\nprint(height, width)\n\nSCALE=1\nfigsize = (width / float(dpi))/SCALE, (height / float(dpi))/SCALE\n\nfig = plt.figure(figsize=figsize)\nplt.imshow(image, cmap='gray')\ndpi = 80 #inch\n\n\npath=f\"../input/aptos2019-blindness-detection/train_images/838c87c63422.png\" \nimage = load_ben_color(path,sigmaX=10)\n\nheight, width = IMG_SIZE, IMG_SIZE\nprint(height, width)\n\nSCALE=1\nfigsize = (width / float(dpi))/SCALE, (height / float(dpi))/SCALE\n\nfig = plt.figure(figsize=figsize)\nplt.imshow(image, cmap='gray')\n\n\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Diabetic Retinopathy Detection with Logistic Regression\n* Logistic regression is the basis of artificial neural networks. Therefore, I will use logistic regression.\n* Logistic regression is a binary classification algorithm.So I'm going to take the illness level 4 and level 0 ones.","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"## Basic Data Analysis","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"train=pd.read_csv(\"../input/aptos2019-blindness-detection/train.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"patient=train[train[\"diagnosis\"]==4]\nhealt=train[train[\"diagnosis\"]==0]\ntrain_df=pd.concat([patient,healt])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df[\"diagnosis\"]=[1 if i==4 else 0 for i in train_df.diagnosis]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x=train_df.drop(columns=[\"diagnosis\"])\ny=train_df.diagnosis","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nx_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.30,random_state=42)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dn_x = [ Image.open('../input/aptos2019-blindness-detection/train_images/'+i+'.png') for i in x_train.id_code[:5]]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dn_x","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for i in dn_x:\n    \n    plt.figure(figsize=(5,3))\n    i = cv2.resize(np.asarray(i),(64,64))\n    i= cv2.cvtColor(i,cv2.COLOR_BGR2GRAY)\n    plt.imshow(i,cmap=\"gray\")\n    plt.axis(\"off\")\n    plt.show","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train = [cv2.resize(np.asarray(Image.open('../input/aptos2019-blindness-detection/train_images/'+i+'.png').convert(\"L\")),(64,64)) for i in x_train.id_code]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_test = [cv2.resize(np.asarray(Image.open('../input/aptos2019-blindness-detection/train_images/'+i+'.png').convert(\"L\")),(64,64)) for i in x_test.id_code]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_test=np.array(x_test)\nx_test.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train=np.array(x_train)\nx_train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train_flatten=x_train.reshape(x_train.shape[0],x_train.shape[1]*x_train.shape[2])\nx_test_flatten=x_test.reshape(x_test.shape[0],x_test.shape[1]*x_test.shape[2])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train=x_train_flatten.T\ny_train=y_train.T\nx_test=x_test_flatten.T\ny_test=y_test.T\nprint(\"x_train: \",x_train.shape)\nprint(\"x_test: \",x_test.shape)\nprint(\"y_train: \",y_train.shape)\nprint(\"y_test: \",y_test.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_train=np.array(y_train)\ny_test=np.array(y_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_train=y_train.reshape(-1,1)\ny_test=y_test.reshape(-1,1)\nprint(\"y_train: \",y_train.shape)\nprint(\"y_test: \",y_test.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Initialize Parameters","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def initialize_weights_and_bias(dimension):\n    w=np.full((dimension,1),0.01)\n    b=0.0\n    return w,b","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Sigmoid Function","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def sigmoid(z):\n    # sigmoid function is 1/(1+e^-z)\n    y_head=1/(1+np.exp(-z))\n    return y_head","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Forward Propagation","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def forward_propagation(w,b,x_train,y_train):\n    z=np.dot(w.T,x_train)+b\n    y_head=sigmoid(z)\n    loss=-y_train*np.log(y_head)-(1-y_train)*np.log(1-y_head)\n    cost=(np.sum(loss))/x_train.shape[1]\n    return cost","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Optimization Algorithm with Gradient Descent","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def forward_backward_propagation(w,b,x_train,y_train):\n    # forward propagation\n    z=np.dot(w.T,x_train)+b\n    y_head=sigmoid(z)\n    loss=-y_train*np.log(y_head)-(1-y_train)*np.log(1-y_head)\n    cost=(np.sum(loss))/x_train.shape[1]\n    #backward propagation\n    derivative_weight = (np.dot(x_train,((y_head-y_train).T)))/x_train.shape[1]\n    derivative_bias=np.sum(y_head-y_train)/x_train.shape[1]\n    gradients={\"derivative_weight\":derivative_weight,\"derivative_bias\":derivative_bias}\n    return cost,gradients\n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Updating(learning) parameters\n\ndef update(w,b,x_train,y_train,learning_rate,number_of_iteration):\n    cost_list=[]\n    cost_list2=[]\n    index=[]\n    for i in range(number_of_iteration):\n        cost,gradients=forward_backward_propagation(w,b,x_train,y_train)\n        cost_list.append(cost)\n        w=w-learning_rate*gradients[\"derivative_weight\"]\n        b=b-learning_rate*gradients[\"derivative_bias\"]\n    parameters ={\"weight\":w,\"bias\":b}\n    \n    return parameters,gradients,cost_list","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# prediction\ndef predict(w,b,x_test):\n    z=sigmoid(np.dot(w.T,x_test)+b)\n    Y_prediction=np.zeros((1,x_test.shape[1]))\n    for i in range(z.shape[1]):\n        if z[0,i]<=0.5:\n            Y_prediction[0,i]=0\n        else:\n            Y_prediction[0,i]=1\n    return Y_prediction   \n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Logistic regression initialize\ndef logistic_regression(x_train,y_train,x_test,y_test,learning_rate,num_iterations):\n    dimension=x_train.shape[0]\n    w,b=initialize_weights_and_bias(dimension)\n    parameters,gradients,cost_list=update(w,b,x_train,y_train,learning_rate,num_iterations)\n    y_prediction_test=predict(parameters[\"weight\"],parameters[\"bias\"],x_test)\n    y_prediction_train=predict(parameters[\"weight\"],parameters[\"bias\"],x_train)\n    print(\"train accuracy: {} %\".format(100 - np.mean(np.abs(y_prediction_train - y_train)) * 100))\n    print(\"test accuracy: {} %\".format(100 - np.mean(np.abs(y_prediction_test - y_test)) * 100))\nlogistic_regression(x_train, y_train, x_test, y_test,learning_rate = 0.01, num_iterations = 50)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Scikit Learn with Logistic Regression","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn import linear_model\nlogreg = linear_model.LogisticRegression(random_state = 42,max_iter= 150)\nprint(\"test accuracy: {} \".format(logreg.fit(x_train.T, y_train).score(x_test.T, y_test)))","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}