{"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\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-12-24T11:44:51.746106Z","iopub.execute_input":"2021-12-24T11:44:51.74647Z","iopub.status.idle":"2021-12-24T11:44:51.772505Z","shell.execute_reply.started":"2021-12-24T11:44:51.746382Z","shell.execute_reply":"2021-12-24T11:44:51.771867Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import json\nimport math\n\nimport cv2\nfrom PIL import Image\nimport numpy as np\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.applications import InceptionV3\nfrom tensorflow.keras.callbacks import Callback, ModelCheckpoint\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.optimizers import Adam\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import cohen_kappa_score, accuracy_score\nimport scipy\nimport tensorflow as tf\nfrom tqdm import tqdm\n\n%matplotlib inline","metadata":{"execution":{"iopub.status.busy":"2021-12-24T11:45:23.78047Z","iopub.execute_input":"2021-12-24T11:45:23.780721Z","iopub.status.idle":"2021-12-24T11:45:29.475286Z","shell.execute_reply.started":"2021-12-24T11:45:23.780694Z","shell.execute_reply":"2021-12-24T11:45:29.474369Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Reading and printing the shapes of the train and test datasets**","metadata":{}},{"cell_type":"code","source":"train_df = pd.read_csv('../input/aptos2019-blindness-detection/train.csv')\ntest_df = pd.read_csv('../input/aptos2019-blindness-detection/test.csv')\nprint(train_df.shape)\nprint(test_df.shape)\ntrain_df.head()","metadata":{"execution":{"iopub.status.busy":"2021-12-24T11:45:03.938815Z","iopub.execute_input":"2021-12-24T11:45:03.939356Z","iopub.status.idle":"2021-12-24T11:45:03.982414Z","shell.execute_reply.started":"2021-12-24T11:45:03.939319Z","shell.execute_reply":"2021-12-24T11:45:03.981767Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def display_samples(df, columns=4, rows=3):\n    fig=plt.figure(figsize=(18, 10))\n\n    for i in range(columns*rows):\n        image_path = df.loc[i,'id_code']\n        image_id = df.loc[i,'diagnosis']\n        img = cv2.imread(f'../input/aptos2019-blindness-detection/train_images/{image_path}.png')\n        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n        \n        fig.add_subplot(rows, columns, i+1)\n        plt.title(image_id)\n        plt.imshow(img)\n    \ndisplay_samples(train_df)","metadata":{"execution":{"iopub.status.busy":"2021-12-24T11:46:33.652694Z","iopub.execute_input":"2021-12-24T11:46:33.653008Z","iopub.status.idle":"2021-12-24T11:46:43.823899Z","shell.execute_reply.started":"2021-12-24T11:46:33.652972Z","shell.execute_reply":"2021-12-24T11:46:43.823255Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Since i want to try the classification using InceptionV3, the images in the dataset must be resized to 299x299**","metadata":{}},{"cell_type":"code","source":"def resize_image(image_path, desired_size=299):\n    im = Image.open(image_path)\n    im = im.resize((desired_size, desired_size ), resample=Image.ANTIALIAS)\n    \n    return im","metadata":{"execution":{"iopub.status.busy":"2021-12-24T12:16:52.094403Z","iopub.execute_input":"2021-12-24T12:16:52.09513Z","iopub.status.idle":"2021-12-24T12:16:52.100348Z","shell.execute_reply.started":"2021-12-24T12:16:52.095092Z","shell.execute_reply":"2021-12-24T12:16:52.099615Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Resizing the images**","metadata":{}},{"cell_type":"code","source":"N = train_df.shape[0]\nx_train = np.empty((N, 299, 299, 3), dtype=np.uint8)\n\nfor i, image_id in enumerate(tqdm(train_df['id_code'])):\n    x_train[i, :, :, :] = resize_image(\n        f'../input/aptos2019-blindness-detection/train_images/{image_id}.png'\n    )","metadata":{"execution":{"iopub.status.busy":"2021-12-24T12:41:21.032937Z","iopub.execute_input":"2021-12-24T12:41:21.03364Z","iopub.status.idle":"2021-12-24T12:51:12.988628Z","shell.execute_reply.started":"2021-12-24T12:41:21.0336Z","shell.execute_reply":"2021-12-24T12:51:12.987936Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"N = test_df.shape[0]\nx_test = np.empty((N, 299, 299, 3), dtype=np.uint8)\n\nfor i, image_id in enumerate(tqdm(test_df['id_code'])):\n    x_test[i, :, :, :] = resize_image(\n        f'../input/aptos2019-blindness-detection/test_images/{image_id}.png'\n    )","metadata":{"execution":{"iopub.status.busy":"2021-12-24T12:51:30.45633Z","iopub.execute_input":"2021-12-24T12:51:30.456588Z","iopub.status.idle":"2021-12-24T12:53:39.497718Z","shell.execute_reply.started":"2021-12-24T12:51:30.45656Z","shell.execute_reply":"2021-12-24T12:53:39.497031Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"****loading the target classes into y_train****","metadata":{}},{"cell_type":"code","source":"y_train = pd.get_dummies(train_df['diagnosis']).values\n\nprint(x_train.shape)\nprint(y_train.shape)\nprint(y_train[:10])\nprint(x_test.shape)\n","metadata":{"execution":{"iopub.status.busy":"2021-12-24T12:53:45.757051Z","iopub.execute_input":"2021-12-24T12:53:45.757598Z","iopub.status.idle":"2021-12-24T12:53:45.767548Z","shell.execute_reply.started":"2021-12-24T12:53:45.75756Z","shell.execute_reply":"2021-12-24T12:53:45.766764Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"****converting the target classes to multilabel (if the class is 4 [0,0,0,1,0] all three previous classes are also active [1,1,1,1,0]","metadata":{}},{"cell_type":"code","source":"y_train_multi = np.empty(y_train.shape, dtype=y_train.dtype)\ny_train_multi[:, 4] = y_train[:, 4]\n\nfor i in range(3, -1, -1):\n    y_train_multi[:, i] = np.logical_or(y_train[:, i], y_train_multi[:, i+1])\n\nprint(\"Original y_train:\", y_train.sum(axis=0))\nprint(\"Multilabel version:\", y_train_multi.sum(axis=0))\nprint(y_train)\nprint(y_train_multi)","metadata":{"execution":{"iopub.status.busy":"2021-12-24T12:53:57.066452Z","iopub.execute_input":"2021-12-24T12:53:57.066702Z","iopub.status.idle":"2021-12-24T12:53:57.077822Z","shell.execute_reply.started":"2021-12-24T12:53:57.066674Z","shell.execute_reply":"2021-12-24T12:53:57.076928Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**splitting the dataset into train and validation**","metadata":{}},{"cell_type":"code","source":"print(x_train.shape)\nprint(y_train_multi.shape)\n\nx_trn, x_val, y_trn, y_val = train_test_split(\n    x_train, y_train_multi, \n    test_size=0.2,\n    random_state=1738\n)","metadata":{"execution":{"iopub.status.busy":"2021-12-24T13:00:34.097266Z","iopub.execute_input":"2021-12-24T13:00:34.097533Z","iopub.status.idle":"2021-12-24T13:00:34.387485Z","shell.execute_reply.started":"2021-12-24T13:00:34.097506Z","shell.execute_reply":"2021-12-24T13:00:34.386765Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(x_trn.shape)\nprint(x_val.shape)\nprint(y_trn.shape)\nprint(y_val.shape)","metadata":{"execution":{"iopub.status.busy":"2021-12-24T13:01:17.275661Z","iopub.execute_input":"2021-12-24T13:01:17.275992Z","iopub.status.idle":"2021-12-24T13:01:17.282504Z","shell.execute_reply.started":"2021-12-24T13:01:17.27596Z","shell.execute_reply":"2021-12-24T13:01:17.281787Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Data augmentation using ImageDataGenerator with the parameters:**\n* Random zoom of 15%\n* Random rotation from -90° to 90°\n* Random horizontal and vertical flip ","metadata":{}},{"cell_type":"code","source":"BATCH_SIZE = 32\n\ndef create_datagen():\n    return ImageDataGenerator(\n        zoom_range=0.15,  \n        rotation_range=90,\n        fill_mode='constant',\n        cval=0.,  \n        horizontal_flip=True,  \n        vertical_flip=True, \n    )\n\ndata_generator = create_datagen().flow(x_trn, y_trn, batch_size=BATCH_SIZE, seed=1738)","metadata":{"execution":{"iopub.status.busy":"2021-12-24T13:09:11.235675Z","iopub.execute_input":"2021-12-24T13:09:11.236451Z","iopub.status.idle":"2021-12-24T13:09:12.570701Z","shell.execute_reply.started":"2021-12-24T13:09:11.236409Z","shell.execute_reply":"2021-12-24T13:09:12.569935Z"},"trusted":true},"execution_count":null,"outputs":[]}]}