{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"collapsed":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\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","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array\nfrom keras.models import Sequential, load_model\nfrom keras.layers import (Activation, Dropout, Flatten, Dense, GlobalMaxPooling2D,\n                          BatchNormalization, Input, Conv2D, GlobalAveragePooling2D,concatenate,Concatenate)\nfrom keras.callbacks import ModelCheckpoint\nfrom keras import metrics\nfrom keras.optimizers import Adam \nfrom keras import backend as K\nimport keras\nfrom keras.models import Model\nimport matplotlib.pyplot as plt\n\nimport PIL\nfrom PIL import Image, ImageOps\nimport cv2\n\nfrom keras.losses import binary_crossentropy, categorical_crossentropy\nimport keras.backend as K\nimport tensorflow as tf\nfrom sklearn.metrics import f1_score, fbeta_score, cohen_kappa_score\nfrom keras.utils import Sequence\nfrom keras.utils import to_categorical\nfrom sklearn.model_selection import train_test_split\nimport imgaug as ia\nfrom keras.applications.vgg16 import VGG16\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import warnings\nwarnings.filterwarnings(\"ignore\")","execution_count":null,"outputs":[]},{"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":"num_train = df_train.shape[0]\ndf_train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"num_test = df_test.shape[0]\ndf_train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_images =  \"../input/aptos2019-blindness-detection/train_images/\"\ntest_images = \"../input/aptos2019-blindness-detection/test_images/\"","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":"df_test.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Sample Images"},{"metadata":{"trusted":true},"cell_type":"code","source":"img = load_img(train_images +  df_train['id_code'].iloc[1] +\".png\")\nplt.imshow(img)\nplt.axis(\"off\")\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X = df_train['id_code']\ny = df_train['diagnosis']\n\n\ny.hist()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"num_classes = 5","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y = to_categorical(y, num_classes=num_classes)\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.15, random_state=42)\n\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Transfer Learning with VGG16"},{"metadata":{"trusted":true},"cell_type":"code","source":"vgg = VGG16()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true},"cell_type":"code","source":"vgg.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"vgg_layers_list = vgg.layers","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### removing prediction layer"},{"metadata":{"trusted":true},"cell_type":"code","source":"for i in range(len(vgg_layers_list)-1):\n    model.add(vgg_layers_list[i])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### freeze the pretrained layers"},{"metadata":{"trusted":true},"cell_type":"code","source":"for layers in model.layers:\n    layers.trainable = False","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.add(Dense(num_classes, activation=\"softmax\"))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"num_classes","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(loss = \"categorical_crossentropy\",\n              optimizer = \"adam\",\n              metrics = [\"accuracy\"])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"diagnosis = [0,1,2,3,4]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"datagen=ImageDataGenerator(rescale=1./255.)\ntest_datagen=ImageDataGenerator(rescale=1./255.)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train['diagnosis'] = df_train['diagnosis'].astype('str')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def append_ext(fn):\n    return fn+\".png\"\n\ndf_train[\"id_code\"]=df_train[\"id_code\"].apply(append_ext)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_test[\"id_code\"]=df_test[\"id_code\"].apply(append_ext)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_generator=datagen.flow_from_dataframe(\n    dataframe=df_train[:2929],\n    directory= \"../input/aptos2019-blindness-detection/train_images\",\n    x_col=\"id_code\",\n    y_col=\"diagnosis\",\n    batch_size=32,\n    seed=42,\n    shuffle=True,\n    class_mode=\"categorical\",\n    target_size=(224,224))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_generator=test_datagen.flow_from_dataframe(\ndataframe=df_test,\ndirectory=\"../input/aptos2019-blindness-detection/test_images\",\nx_col=\"id_code\",\nbatch_size=1,\nseed=42,\nshuffle=False,\nclass_mode=None,\ntarget_size=(224,224))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"valid_generator=datagen.flow_from_dataframe(\ndataframe=df_train[2929:],\ndirectory=\"../input/aptos2019-blindness-detection/train_images\",\nx_col=\"id_code\",\ny_col=\"diagnosis\",\nbatch_size=32,\nseed=42,\nshuffle=True,\nclass_mode=\"categorical\",\nclasses=[\"0\", \"1\", \"2\", \"3\", \"4\"],\ntarget_size=(224,224))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"batch_size = 32","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.fit(train_generator,\n           steps_per_epoch=num_train//batch_size,\n           epochs= 10,\n           validation_data=valid_generator,\n           validation_steps= num_test//batch_size)","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}