{"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","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import json\nimport math\nimport os\n\nimport cv2\nfrom PIL import Image\nimport numpy as np\nfrom keras import layers\nfrom keras.applications import DenseNet121\nfrom keras.callbacks import Callback, ModelCheckpoint\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom 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 keras.callbacks import EarlyStopping,ReduceLROnPlateau,LearningRateScheduler\nfrom tqdm import tqdm_notebook as tqdm\n\n%matplotlib inline","metadata":{"execution":{"iopub.status.busy":"2021-07-02T07:57:29.169610Z","iopub.execute_input":"2021-07-02T07:57:29.169925Z","iopub.status.idle":"2021-07-02T07:57:34.814942Z","shell.execute_reply.started":"2021-07-02T07:57:29.169896Z","shell.execute_reply":"2021-07-02T07:57:34.814002Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nimport timeit\n\ndevice_name = tf.test.gpu_device_name()\nprint(device_name)","metadata":{"execution":{"iopub.status.busy":"2021-07-02T07:57:38.647030Z","iopub.execute_input":"2021-07-02T07:57:38.647393Z","iopub.status.idle":"2021-07-02T07:57:40.630238Z","shell.execute_reply.started":"2021-07-02T07:57:38.647353Z","shell.execute_reply":"2021-07-02T07:57:40.629140Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"np.random.seed(2020)\ntf.random.set_seed(2020)","metadata":{"execution":{"iopub.status.busy":"2021-07-02T07:57:42.490615Z","iopub.execute_input":"2021-07-02T07:57:42.490923Z","iopub.status.idle":"2021-07-02T07:57:42.497620Z","shell.execute_reply.started":"2021-07-02T07:57:42.490894Z","shell.execute_reply":"2021-07-02T07:57:42.496661Z"},"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-07-02T07:57:45.581371Z","iopub.execute_input":"2021-07-02T07:57:45.581708Z","iopub.status.idle":"2021-07-02T07:57:45.625407Z","shell.execute_reply.started":"2021-07-02T07:57:45.581680Z","shell.execute_reply":"2021-07-02T07:57:45.624105Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df['diagnosis'].hist()\ntrain_df['diagnosis'].value_counts()","metadata":{"execution":{"iopub.status.busy":"2021-07-02T07:57:49.440154Z","iopub.execute_input":"2021-07-02T07:57:49.440459Z","iopub.status.idle":"2021-07-02T07:57:49.617598Z","shell.execute_reply.started":"2021-07-02T07:57:49.440432Z","shell.execute_reply":"2021-07-02T07:57:49.616527Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def display_samples(df, columns=4, rows=3):\n    fig=plt.figure(figsize=(5*columns, 4*rows))\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    \n    plt.tight_layout()\n\ndisplay_samples(train_df)","metadata":{"execution":{"iopub.status.busy":"2021-07-02T07:57:52.806376Z","iopub.execute_input":"2021-07-02T07:57:52.806684Z","iopub.status.idle":"2021-07-02T07:58:00.896816Z","shell.execute_reply.started":"2021-07-02T07:57:52.806656Z","shell.execute_reply":"2021-07-02T07:58:00.895787Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img_ht = 256\nimg_wd = 256","metadata":{"execution":{"iopub.status.busy":"2021-07-02T07:58:06.196611Z","iopub.execute_input":"2021-07-02T07:58:06.196930Z","iopub.status.idle":"2021-07-02T07:58:06.203221Z","shell.execute_reply.started":"2021-07-02T07:58:06.196900Z","shell.execute_reply":"2021-07-02T07:58:06.202438Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def preprocess_image(image_path, desired_size=256):\n    im = Image.open(image_path)\n    im = im.resize((desired_size, )*2, resample=Image.LANCZOS)\n    \n    return im","metadata":{"execution":{"iopub.status.busy":"2021-07-02T07:58:07.664303Z","iopub.execute_input":"2021-07-02T07:58:07.664649Z","iopub.status.idle":"2021-07-02T07:58:07.669245Z","shell.execute_reply.started":"2021-07-02T07:58:07.664601Z","shell.execute_reply":"2021-07-02T07:58:07.668256Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"N = train_df.shape[0]\nx_train = np.empty((N, img_ht, img_wd, 3), dtype=np.uint8)\n\nwith tf.device('/gpu:0'):\n    for i, image_id in enumerate(tqdm(train_df['id_code'])):\n        x_train[i, :, :, :] = preprocess_image(\n\n            f'../input/aptos2019-blindness-detection/train_images/{image_id}.png'\n        )","metadata":{"execution":{"iopub.status.busy":"2021-07-02T07:58:09.651457Z","iopub.execute_input":"2021-07-02T07:58:09.651775Z","iopub.status.idle":"2021-07-02T08:08:25.175946Z","shell.execute_reply.started":"2021-07-02T07:58:09.651746Z","shell.execute_reply":"2021-07-02T08:08:25.175114Z"},"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)","metadata":{"execution":{"iopub.status.busy":"2021-07-02T08:08:29.635439Z","iopub.execute_input":"2021-07-02T08:08:29.635755Z","iopub.status.idle":"2021-07-02T08:08:29.645579Z","shell.execute_reply.started":"2021-07-02T08:08:29.635726Z","shell.execute_reply":"2021-07-02T08:08:29.644576Z"},"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))","metadata":{"execution":{"iopub.status.busy":"2021-07-02T08:08:30.975847Z","iopub.execute_input":"2021-07-02T08:08:30.976277Z","iopub.status.idle":"2021-07-02T08:08:30.991746Z","shell.execute_reply.started":"2021-07-02T08:08:30.976239Z","shell.execute_reply":"2021-07-02T08:08:30.990943Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train, x_val, y_train, y_val = train_test_split(\n    x_train, y_train_multi, \n    test_size=0.15, \n    random_state=2019\n)","metadata":{"execution":{"iopub.status.busy":"2021-07-02T08:08:33.859569Z","iopub.execute_input":"2021-07-02T08:08:33.859895Z","iopub.status.idle":"2021-07-02T08:08:34.094525Z","shell.execute_reply.started":"2021-07-02T08:08:33.859860Z","shell.execute_reply":"2021-07-02T08:08:34.093739Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"BATCH_SIZE = 4\n\ndef create_datagen():\n    return ImageDataGenerator(\n        zoom_range=0.15,  # set range for random zoom\n        # set mode for filling points outside the input boundaries\n        fill_mode='constant',\n        cval=0.,  # value used for fill_mode = \"constant\"\n        horizontal_flip=True,  # randomly flip images\n        vertical_flip=True,  # randomly flip images\n        width_shift_range = 0.3,\n        height_shift_range=0.3\n    )\n\n# Using original generator\ndata_generator = create_datagen().flow(x_train, y_train, batch_size=BATCH_SIZE, seed=2020)","metadata":{"execution":{"iopub.status.busy":"2021-07-02T08:08:35.925364Z","iopub.execute_input":"2021-07-02T08:08:35.925688Z","iopub.status.idle":"2021-07-02T08:08:36.776770Z","shell.execute_reply.started":"2021-07-02T08:08:35.925659Z","shell.execute_reply":"2021-07-02T08:08:36.775995Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def build_model():\n    model = Sequential()\n    model.add(effnet)\n    model.add(layers.GlobalAveragePooling2D())\n    model.add(layers.Dropout(0.5))\n    model.add(layers.Dense(5, activation='sigmoid'))\n    \n    model.compile(\n        loss='binary_crossentropy',\n        optimizer=Adam(lr=0.00005),\n        metrics=['accuracy']\n    )\n    \n    return model","metadata":{"execution":{"iopub.status.busy":"2021-07-02T08:08:40.919363Z","iopub.execute_input":"2021-07-02T08:08:40.919677Z","iopub.status.idle":"2021-07-02T08:08:40.924838Z","shell.execute_reply.started":"2021-07-02T08:08:40.919649Z","shell.execute_reply":"2021-07-02T08:08:40.923906Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install efficientnet==1.1.0","metadata":{"execution":{"iopub.status.busy":"2021-07-02T08:08:43.599235Z","iopub.execute_input":"2021-07-02T08:08:43.599557Z","iopub.status.idle":"2021-07-02T08:08:51.435056Z","shell.execute_reply.started":"2021-07-02T08:08:43.599528Z","shell.execute_reply":"2021-07-02T08:08:51.434075Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import efficientnet.tfkeras as efn","metadata":{"execution":{"iopub.status.busy":"2021-07-02T08:08:51.438216Z","iopub.execute_input":"2021-07-02T08:08:51.438579Z","iopub.status.idle":"2021-07-02T08:08:51.743663Z","shell.execute_reply.started":"2021-07-02T08:08:51.438539Z","shell.execute_reply":"2021-07-02T08:08:51.742807Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img_ht = 256\nimg_wd = 256","metadata":{"execution":{"iopub.status.busy":"2021-07-02T08:08:55.179410Z","iopub.execute_input":"2021-07-02T08:08:55.179719Z","iopub.status.idle":"2021-07-02T08:08:55.184306Z","shell.execute_reply.started":"2021-07-02T08:08:55.179689Z","shell.execute_reply":"2021-07-02T08:08:55.183375Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"effnet = efn.EfficientNetB4(weights=None,\n                        include_top=False,\n                        input_shape=(img_wd, img_ht, 3))\neffnet.load_weights('../input/efficientnet/efficientnet-b4_imagenet_1000_notop.h5/efficientnet-b4_imagenet_1000_notop.h5')","metadata":{"execution":{"iopub.status.busy":"2021-07-02T08:08:58.129637Z","iopub.execute_input":"2021-07-02T08:08:58.129950Z","iopub.status.idle":"2021-07-02T08:09:02.576747Z","shell.execute_reply.started":"2021-07-02T08:08:58.129919Z","shell.execute_reply":"2021-07-02T08:09:02.575853Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = build_model()","metadata":{"execution":{"iopub.status.busy":"2021-07-02T08:09:05.649499Z","iopub.execute_input":"2021-07-02T08:09:05.649817Z","iopub.status.idle":"2021-07-02T08:09:06.621899Z","shell.execute_reply.started":"2021-07-02T08:09:05.649788Z","shell.execute_reply":"2021-07-02T08:09:06.621143Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class Metrics(Callback):\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 = x_val, y_val\n        Y_val = Y_val.sum(axis=1) - 1\n        \n        y_pred = self.model.predict(X_val) > 0.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-07-02T08:09:10.658870Z","iopub.execute_input":"2021-07-02T08:09:10.659199Z","iopub.status.idle":"2021-07-02T08:09:10.666253Z","shell.execute_reply.started":"2021-07-02T08:09:10.659167Z","shell.execute_reply":"2021-07-02T08:09:10.665282Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"es = EarlyStopping(monitor='val_loss',\n                                      mode='auto',\n                                      verbose=1,\n                                      patience=10)\n\nlearning_rate_reduction = ReduceLROnPlateau(monitor='val_loss',\n                                            patience=3,\n                                            verbose=1,\n                                            mode = 'auto',\n                                            factor=0.25,\n                                            min_lr=0.000001)","metadata":{"execution":{"iopub.status.busy":"2021-07-02T08:09:16.349723Z","iopub.execute_input":"2021-07-02T08:09:16.350039Z","iopub.status.idle":"2021-07-02T08:09:16.355928Z","shell.execute_reply.started":"2021-07-02T08:09:16.350008Z","shell.execute_reply":"2021-07-02T08:09:16.354622Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with tf.device('/gpu:0'):\n    kappa_metrics = Metrics()\n    history = model.fit_generator(\n        data_generator,\n        steps_per_epoch=x_train.shape[0] / BATCH_SIZE,\n        #steps_per_epoch=5,\n        epochs=15,\n        validation_data=(x_val, y_val),\n        callbacks=[kappa_metrics,es, learning_rate_reduction]\n    )","metadata":{"execution":{"iopub.status.busy":"2021-07-02T08:09:20.749081Z","iopub.execute_input":"2021-07-02T08:09:20.749393Z","iopub.status.idle":"2021-07-02T08:36:09.070495Z","shell.execute_reply.started":"2021-07-02T08:09:20.749364Z","shell.execute_reply":"2021-07-02T08:36:09.069507Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with open('history.json', 'w') as f:\n    try:\n        json.dump(history.history, f)\n    except:\n        pass","metadata":{"execution":{"iopub.status.busy":"2021-07-02T08:36:16.729900Z","iopub.execute_input":"2021-07-02T08:36:16.730235Z","iopub.status.idle":"2021-07-02T08:36:16.735945Z","shell.execute_reply.started":"2021-07-02T08:36:16.730202Z","shell.execute_reply":"2021-07-02T08:36:16.734887Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot(kappa_metrics.val_kappas)","metadata":{"execution":{"iopub.status.busy":"2021-07-02T08:36:18.849560Z","iopub.execute_input":"2021-07-02T08:36:18.849886Z","iopub.status.idle":"2021-07-02T08:36:18.998147Z","shell.execute_reply.started":"2021-07-02T08:36:18.849855Z","shell.execute_reply":"2021-07-02T08:36:18.997299Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}