{"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_minor":4,"nbformat":4,"cells":[{"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\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB 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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2021-05-25T10:45:23.787479Z","iopub.execute_input":"2021-05-25T10:45:23.787889Z","iopub.status.idle":"2021-05-25T10:45:26.279473Z","shell.execute_reply.started":"2021-05-25T10:45:23.787809Z","shell.execute_reply":"2021-05-25T10:45:26.278502Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\n# from keras.preprocessing.image import img_to_array\n# from keras.preprocessing.image import array_to_img\n# from sklearn.model_selection import train_test_split\n# from PIL import Image\n# import scipy\n\nimport tensorflow as tf\nfrom tensorflow.keras.applications import *\nfrom tensorflow.keras.optimizers import *\nfrom tensorflow.keras.losses import *\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.models import *\nfrom tensorflow.keras.callbacks import *\nfrom tensorflow.keras.preprocessing.image import *\nfrom tensorflow.keras.utils import *\n# import pydot\nfrom sklearn.metrics import *\nfrom sklearn.model_selection import *\nimport tensorflow.keras.backend as K\n\n# from tqdm import tqdm, tqdm_notebook\n# from colorama import Fore\n# import json\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom glob import glob\nfrom skimage.io import *\n%config Completer.use_jedi = False\n# import time\n# from sklearn.decomposition import PCA\n# from sklearn.svm import LinearSVC\n# from sklearn.linear_model import LogisticRegression\n# from sklearn.metrics import accuracy_score\n# import lightgbm as lgb\n# import xgboost as xgb\n# !pip install livelossplot\n# import livelossplot\n# from livelossplot import PlotLossesKeras\nimport warnings\nwarnings.filterwarnings('ignore')\nprint(\"All modules have been imported\")","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport cv2\nimport matplotlib.pyplot as plt\nfrom glob import glob\n\n\nfrom keras.preprocessing import image\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras import layers\nfrom keras.layers import Flatten\nimport keras\nimport tensorflow.keras.backend as K\n#K.tensorflow_backend._get_available_gpus()\n\nimport os\nprint(os.listdir('../input'))\n#install keras-efficientnet","metadata":{"execution":{"iopub.status.busy":"2021-05-25T10:25:10.381536Z","iopub.execute_input":"2021-05-25T10:25:10.382162Z","iopub.status.idle":"2021-05-25T10:25:16.776782Z","shell.execute_reply.started":"2021-05-25T10:25:10.382059Z","shell.execute_reply":"2021-05-25T10:25:16.774475Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n!pip install -U efficientnet","metadata":{"execution":{"iopub.status.busy":"2021-05-25T10:25:19.881026Z","iopub.execute_input":"2021-05-25T10:25:19.881424Z","iopub.status.idle":"2021-05-25T10:25:29.99831Z","shell.execute_reply.started":"2021-05-25T10:25:19.881391Z","shell.execute_reply":"2021-05-25T10:25:29.997122Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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_BGR2GRAY)\n        mask = gray_img>tol        \n        check_shape = img[:,:,0][np.ix_(mask.any(1),mask.any(0))].shape[0]\n        if (check_shape == 0):\n            return img\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            img = np.stack([img1,img2,img3],axis=-1)\n        return img\n\ndef circle_crop(img):   \n    #img = cv2.imread(img)\n    img = crop_image_from_gray(img)    \n    \n    height, width, depth = img.shape    \n    \n    x = int(width/2)\n    y = int(height/2)\n    r = np.amin((x,y))\n    \n    circle_img = np.zeros((height, width), np.uint8)\n    cv2.circle(circle_img, (x,y), int(r), 1, thickness=-1)\n    img = cv2.bitwise_and(img, img, mask=circle_img)\n    img = crop_image_from_gray(img)\n    \n    return img","metadata":{"execution":{"iopub.status.busy":"2021-05-25T10:25:30.002633Z","iopub.execute_input":"2021-05-25T10:25:30.002968Z","iopub.status.idle":"2021-05-25T10:25:30.018856Z","shell.execute_reply.started":"2021-05-25T10:25:30.002931Z","shell.execute_reply":"2021-05-25T10:25:30.017466Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df=pd.read_csv('../input/aptos2019-blindness-detection/train.csv')\nl1=[s+'.png' for s in df['id_code']]\ndf['id_code']=l1\nl2=[str(s) for s in df['diagnosis']]\ndf['diagnosis']=l2\n#print(df)\nsigmaX=10\nIMG_SIZE=228\ndef preprocess(img_name):\n    \n    image = cv2.imread(img_name)\n    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n    image = cv2.resize(image, (IMG_SIZE, IMG_SIZE))\n    image = circle_crop(image)\n    image=cv2.addWeighted (image,4, cv2.GaussianBlur( image , (0,0) , sigmaX) ,-4 ,128)\n    image = cv2.normalize(image, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)\n    return(image)\n\nBATCH_SIZE = 32\nTRAIN_IMG_PATH='../input/aptos2019-blindness-detection/train_images'\n# Add Image augmentation to our generator\ntrain_datagen = ImageDataGenerator(rotation_range=15,horizontal_flip=True,zca_whitening=True)\n\n# Use the dataframe to define train and validation generators\ntrain_generator = train_datagen.flow_from_dataframe(df, \n                                                    x_col='id_code', \n                                                    y_col='diagnosis',\n                                                    directory = TRAIN_IMG_PATH,\n                                                    target_size=(IMG_SIZE,IMG_SIZE),\n                                                    batch_size=BATCH_SIZE,\n                                                    class_mode='sparse',\n                                                    preprocessing_function=preprocess, \n                                                    subset='training')","metadata":{"execution":{"iopub.status.busy":"2021-05-25T10:25:32.460684Z","iopub.execute_input":"2021-05-25T10:25:32.461076Z","iopub.status.idle":"2021-05-25T10:25:38.635763Z","shell.execute_reply.started":"2021-05-25T10:25:32.461044Z","shell.execute_reply":"2021-05-25T10:25:38.63472Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Use Efficient Net\nimport efficientnet.keras as efn \nefficient_model=efn.EfficientNetB5(weights=None,input_shape=(IMG_SIZE,IMG_SIZE,3),include_top=False)\nefficient_model.load_weights('../input/efficientnet-keras-weights-b0b5/efficientnet-b5_imagenet_1000_notop.h5')","metadata":{"execution":{"iopub.status.busy":"2021-05-25T10:26:09.638318Z","iopub.execute_input":"2021-05-25T10:26:09.638765Z","iopub.status.idle":"2021-05-25T10:26:20.484641Z","shell.execute_reply.started":"2021-05-25T10:26:09.638731Z","shell.execute_reply":"2021-05-25T10:26:20.483405Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model=Sequential()\nmodel.add(efficient_model)\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(2048))\nmodel.add(layers.LeakyReLU())\nmodel.add(layers.Dropout(0.25))\nmodel.add(layers.Dense(5,activation='softmax'))\n\nmodel.layers[0].trainable = False\n\nmodel.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n\n\"\"\"\nfor l in model.layers:\n    print(l.name, l.trainable)\n\"\"\"\n\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2021-05-25T10:26:23.052083Z","iopub.execute_input":"2021-05-25T10:26:23.052478Z","iopub.status.idle":"2021-05-25T10:26:24.806284Z","shell.execute_reply.started":"2021-05-25T10:26:23.05243Z","shell.execute_reply":"2021-05-25T10:26:24.805185Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.fit_generator(train_generator,\n                    steps_per_epoch=train_generator.samples // BATCH_SIZE,\n                    epochs=20)","metadata":{"execution":{"iopub.status.busy":"2021-05-25T10:26:30.631453Z","iopub.execute_input":"2021-05-25T10:26:30.631876Z","iopub.status.idle":"2021-05-25T10:36:05.848578Z","shell.execute_reply.started":"2021-05-25T10:26:30.631845Z","shell.execute_reply":"2021-05-25T10:36:05.845439Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"rom keras.utils import to_categorical\n#X_test = ImageDataset(csv_file = '../input/aptos2019-blindness-detection/test.csv', root_dir = '../input/aptos2019-blindness-detection/test_images/')\ndf_test=pd.read_csv('../input/aptos2019-blindness-detection/test.csv')\nl1=[s+'.png' for s in df_test['id_code']]\ndf_test['id_code']=l1\n#print(df_test)\ndatagen=ImageDataGenerator()\ngenerator = datagen.flow_from_dataframe(df_test,x_col='id_code',\n                                        directory='../input/aptos2019-blindness-detection/test_images',\n                                        target_size=(IMG_SIZE, IMG_SIZE),\n                                        batch_size=1,\n                                        class_mode=None,\n                                        preprocessing_function=preprocess,\n                                        shuffle=False)  \n\npredictions = model.predict_generator(generator,1928)\n\"\"\"TEST_IMG_PATH='../input/aptos2019-blindness-detection/test_images'\nN = df_test.shape[0]\nx_test = np.empty((N, 224, 224, 3), dtype=np.float32)\nfor i, image_id in enumerate(df_test['id_code']):\n    x_test[i, :, :, :] = preprocess(f'{TEST_IMG_PATH}/{image_id}')\"\"\"\n\n\n#print(np.argmax(predictions, axis=1))\nsubmission = pd.read_csv('../input/aptos2019-blindness-detection/sample_submission.csv')\nsubmission['diagnosis'] = np.argmax(predictions,axis=1)    \nsubmission.to_csv('submission.csv', index=False, encoding='utf-8')","metadata":{},"execution_count":null,"outputs":[]}]}