{"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-25T10:38:51.009362Z","iopub.execute_input":"2021-12-25T10:38:51.009951Z","iopub.status.idle":"2021-12-25T10:38:51.036652Z","shell.execute_reply.started":"2021-12-25T10:38:51.009830Z","shell.execute_reply":"2021-12-25T10:38:51.035531Z"},"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-25T10:38:51.040046Z","iopub.execute_input":"2021-12-25T10:38:51.040630Z","iopub.status.idle":"2021-12-25T10:38:56.998881Z","shell.execute_reply.started":"2021-12-25T10:38:51.040597Z","shell.execute_reply":"2021-12-25T10:38:56.998098Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-25T10:38:57.000307Z","iopub.execute_input":"2021-12-25T10:38:57.000552Z","iopub.status.idle":"2021-12-25T10:38:57.038833Z","shell.execute_reply.started":"2021-12-25T10:38:57.000518Z","shell.execute_reply":"2021-12-25T10:38:57.038096Z"},"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-25T10:38:57.041057Z","iopub.execute_input":"2021-12-25T10:38:57.041544Z","iopub.status.idle":"2021-12-25T10:39:07.916039Z","shell.execute_reply.started":"2021-12-25T10:38:57.041508Z","shell.execute_reply":"2021-12-25T10:39:07.915279Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-25T10:39:07.917050Z","iopub.execute_input":"2021-12-25T10:39:07.917258Z","iopub.status.idle":"2021-12-25T10:39:07.924868Z","shell.execute_reply.started":"2021-12-25T10:39:07.917230Z","shell.execute_reply":"2021-12-25T10:39:07.923829Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-25T10:39:07.926442Z","iopub.execute_input":"2021-12-25T10:39:07.926961Z","iopub.status.idle":"2021-12-25T10:52:11.149520Z","shell.execute_reply.started":"2021-12-25T10:39:07.926927Z","shell.execute_reply":"2021-12-25T10:52:11.148779Z"},"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-25T10:52:11.150965Z","iopub.execute_input":"2021-12-25T10:52:11.151374Z","iopub.status.idle":"2021-12-25T10:54:38.473750Z","shell.execute_reply.started":"2021-12-25T10:52:11.151335Z","shell.execute_reply":"2021-12-25T10:54:38.472976Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-25T10:54:38.475113Z","iopub.execute_input":"2021-12-25T10:54:38.475528Z","iopub.status.idle":"2021-12-25T10:54:38.490001Z","shell.execute_reply.started":"2021-12-25T10:54:38.475486Z","shell.execute_reply":"2021-12-25T10:54:38.489007Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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.shape)\nprint(x_train.shape)","metadata":{"execution":{"iopub.status.busy":"2021-12-25T10:54:38.491584Z","iopub.execute_input":"2021-12-25T10:54:38.491879Z","iopub.status.idle":"2021-12-25T10:54:38.504028Z","shell.execute_reply.started":"2021-12-25T10:54:38.491843Z","shell.execute_reply":"2021-12-25T10:54:38.503105Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-25T10:54:38.507274Z","iopub.execute_input":"2021-12-25T10:54:38.507491Z","iopub.status.idle":"2021-12-25T10:54:39.574265Z","shell.execute_reply.started":"2021-12-25T10:54:38.507455Z","shell.execute_reply":"2021-12-25T10:54:39.573523Z"},"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-25T10:54:39.575741Z","iopub.execute_input":"2021-12-25T10:54:39.576013Z","iopub.status.idle":"2021-12-25T10:54:39.583397Z","shell.execute_reply.started":"2021-12-25T10:54:39.575979Z","shell.execute_reply":"2021-12-25T10:54:39.582728Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-25T10:54:39.584721Z","iopub.execute_input":"2021-12-25T10:54:39.585011Z","iopub.status.idle":"2021-12-25T10:54:43.003701Z","shell.execute_reply.started":"2021-12-25T10:54:39.584972Z","shell.execute_reply":"2021-12-25T10:54:43.002759Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class Metrics(Callback):\n    def __init__(self, val_data = (x_val, y_val), batch_size = BATCH_SIZE):\n        super().__init__()\n        self.validation_data = val_data\n        self.batch_size = batch_size\n    def on_train_begin(self, logs={}):\n        self.val_kappas = []\n\n    def on_epoch_end(self, epoch, logs={}):\n        X_val, y_val = self.validation_data[:2]\n        y_val = y_val.sum(axis=1) - 1\n        \n        y_pred = self.model.predict(X_val) > 1.5\n        y_pred = y_pred.astype(int).sum(axis=1) - 1\n\n        _val_kappa = cohen_kappa_score(\n            y_val,\n            y_pred, \n            weights='quadratic'\n        )\n\n        self.val_kappas.append(_val_kappa)\n\n        print(f\"val_kappa: {_val_kappa:.4f}\")\n        \n        if _val_kappa == max(self.val_kappas):\n            print(\"Validation Kappa has improved. Saving model.\")\n            self.model.save('model.h5')\n\n        return","metadata":{"execution":{"iopub.status.busy":"2021-12-25T11:37:34.510502Z","iopub.execute_input":"2021-12-25T11:37:34.510795Z","iopub.status.idle":"2021-12-25T11:37:34.518948Z","shell.execute_reply.started":"2021-12-25T11:37:34.510745Z","shell.execute_reply":"2021-12-25T11:37:34.518091Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras import layers as L\nbase_model = tf.keras.applications.InceptionV3(input_shape=(299,299,3),\n                                               include_top=False,\n                                               weights='imagenet')","metadata":{"execution":{"iopub.status.busy":"2021-12-25T11:37:37.598601Z","iopub.execute_input":"2021-12-25T11:37:37.599195Z","iopub.status.idle":"2021-12-25T11:37:39.433920Z","shell.execute_reply.started":"2021-12-25T11:37:37.599154Z","shell.execute_reply":"2021-12-25T11:37:39.433135Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def build_model():\n    base_model.trainable = False\n    model = Sequential()\n    model.add(base_model)\n    model.add(L.Flatten())\n    model.add(L.Dense(1024, activation='relu'))\n    model.add(L.Dropout(0.2))\n    model.add(L.Dense(5, activation='softmax'))\n    \n    model.compile(\n        optimizer=tf.keras.optimizers.RMSprop(learning_rate=0.0001), \n        loss='binary_crossentropy', \n        metrics=['accuracy']\n    )\n    \n    return model","metadata":{"execution":{"iopub.status.busy":"2021-12-25T11:37:43.270039Z","iopub.execute_input":"2021-12-25T11:37:43.270491Z","iopub.status.idle":"2021-12-25T11:37:43.278323Z","shell.execute_reply.started":"2021-12-25T11:37:43.270454Z","shell.execute_reply":"2021-12-25T11:37:43.277472Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = build_model()\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2021-12-25T11:37:55.137825Z","iopub.execute_input":"2021-12-25T11:37:55.138464Z","iopub.status.idle":"2021-12-25T11:37:55.743065Z","shell.execute_reply.started":"2021-12-25T11:37:55.138425Z","shell.execute_reply":"2021-12-25T11:37:55.742250Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"kappa_metrics = Metrics()\n\nhistory = model.fit(\n    data_generator,\n    steps_per_epoch=x_trn.shape[0] / BATCH_SIZE,\n    epochs=10,\n    validation_data=(x_val, y_val),\n    callbacks=[kappa_metrics]\n)","metadata":{"execution":{"iopub.status.busy":"2021-12-25T11:38:04.529442Z","iopub.execute_input":"2021-12-25T11:38:04.530259Z","iopub.status.idle":"2021-12-25T11:39:33.215564Z","shell.execute_reply.started":"2021-12-25T11:38:04.530216Z","shell.execute_reply":"2021-12-25T11:39:33.214249Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with open('history.json', 'w') as f:\n    json.dump(history.history, f)\n\nhistory_df = pd.DataFrame(history.history)\nhistory_df[['loss', 'val_loss']].plot()\nhistory_df[['acc', 'val_acc']].plot()","metadata":{},"execution_count":null,"outputs":[]}]}