{"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":"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-08-12T14:58:30.534281Z","iopub.execute_input":"2021-08-12T14:58:30.534597Z","iopub.status.idle":"2021-08-12T14:58:30.545573Z","shell.execute_reply.started":"2021-08-12T14:58:30.534568Z","shell.execute_reply":"2021-08-12T14:58:30.544403Z"},"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-08-12T14:58:30.547673Z","iopub.execute_input":"2021-08-12T14:58:30.548092Z","iopub.status.idle":"2021-08-12T14:58:32.208443Z","shell.execute_reply.started":"2021-08-12T14:58:30.548004Z","shell.execute_reply":"2021-08-12T14:58:32.207381Z"},"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-08-12T14:58:32.210678Z","iopub.execute_input":"2021-08-12T14:58:32.210965Z","iopub.status.idle":"2021-08-12T14:58:32.217724Z","shell.execute_reply.started":"2021-08-12T14:58:32.210936Z","shell.execute_reply":"2021-08-12T14:58:32.216852Z"},"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-08-12T14:58:32.219513Z","iopub.execute_input":"2021-08-12T14:58:32.220125Z","iopub.status.idle":"2021-08-12T14:58:32.266624Z","shell.execute_reply.started":"2021-08-12T14:58:32.220088Z","shell.execute_reply":"2021-08-12T14:58:32.265908Z"},"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-08-12T14:58:32.269109Z","iopub.execute_input":"2021-08-12T14:58:32.269345Z","iopub.status.idle":"2021-08-12T14:58:32.458495Z","shell.execute_reply.started":"2021-08-12T14:58:32.269322Z","shell.execute_reply":"2021-08-12T14:58:32.457709Z"},"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-08-12T14:58:32.459788Z","iopub.execute_input":"2021-08-12T14:58:32.46012Z","iopub.status.idle":"2021-08-12T14:58:42.020958Z","shell.execute_reply.started":"2021-08-12T14:58:32.460084Z","shell.execute_reply":"2021-08-12T14:58:42.019923Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img_ht = 256\nimg_wd = 256\n","metadata":{"execution":{"iopub.status.busy":"2021-08-12T14:58:42.022281Z","iopub.execute_input":"2021-08-12T14:58:42.022716Z","iopub.status.idle":"2021-08-12T14:58:42.026418Z","shell.execute_reply.started":"2021-08-12T14:58:42.022673Z","shell.execute_reply":"2021-08-12T14:58:42.025733Z"},"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-08-12T14:58:42.027521Z","iopub.execute_input":"2021-08-12T14:58:42.028027Z","iopub.status.idle":"2021-08-12T14:58:42.037093Z","shell.execute_reply.started":"2021-08-12T14:58:42.027992Z","shell.execute_reply":"2021-08-12T14:58:42.036303Z"},"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-08-12T14:58:42.04025Z","iopub.execute_input":"2021-08-12T14:58:42.040821Z","iopub.status.idle":"2021-08-12T15:10:47.952793Z","shell.execute_reply.started":"2021-08-12T14:58:42.040716Z","shell.execute_reply":"2021-08-12T15:10:47.951886Z"},"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-08-12T15:10:47.954863Z","iopub.execute_input":"2021-08-12T15:10:47.955259Z","iopub.status.idle":"2021-08-12T15:10:47.964111Z","shell.execute_reply.started":"2021-08-12T15:10:47.955216Z","shell.execute_reply":"2021-08-12T15:10:47.962907Z"},"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-08-12T15:10:47.96556Z","iopub.execute_input":"2021-08-12T15:10:47.965964Z","iopub.status.idle":"2021-08-12T15:10:47.978116Z","shell.execute_reply.started":"2021-08-12T15:10:47.965927Z","shell.execute_reply":"2021-08-12T15:10:47.976922Z"},"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-08-12T15:10:47.979808Z","iopub.execute_input":"2021-08-12T15:10:47.980147Z","iopub.status.idle":"2021-08-12T15:10:48.223451Z","shell.execute_reply.started":"2021-08-12T15:10:47.980114Z","shell.execute_reply":"2021-08-12T15:10:48.222483Z"},"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-08-12T15:10:48.224815Z","iopub.execute_input":"2021-08-12T15:10:48.225148Z","iopub.status.idle":"2021-08-12T15:10:49.165404Z","shell.execute_reply.started":"2021-08-12T15:10:48.225114Z","shell.execute_reply":"2021-08-12T15:10:49.164555Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"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-08-12T15:10:49.166854Z","iopub.execute_input":"2021-08-12T15:10:49.167204Z","iopub.status.idle":"2021-08-12T15:10:49.174043Z","shell.execute_reply.started":"2021-08-12T15:10:49.167167Z","shell.execute_reply":"2021-08-12T15:10:49.172903Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install efficientnet==1.1.0","metadata":{"execution":{"iopub.status.busy":"2021-08-12T15:10:49.175458Z","iopub.execute_input":"2021-08-12T15:10:49.17581Z","iopub.status.idle":"2021-08-12T15:10:57.713682Z","shell.execute_reply.started":"2021-08-12T15:10:49.175775Z","shell.execute_reply":"2021-08-12T15:10:57.712772Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import efficientnet.tfkeras as efn","metadata":{"execution":{"iopub.status.busy":"2021-08-12T15:10:57.716995Z","iopub.execute_input":"2021-08-12T15:10:57.717269Z","iopub.status.idle":"2021-08-12T15:10:58.045718Z","shell.execute_reply.started":"2021-08-12T15:10:57.717241Z","shell.execute_reply":"2021-08-12T15:10:58.044908Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img_ht = 256\nimg_wd = 256","metadata":{"execution":{"iopub.status.busy":"2021-08-12T15:10:58.0469Z","iopub.execute_input":"2021-08-12T15:10:58.047399Z","iopub.status.idle":"2021-08-12T15:10:58.054536Z","shell.execute_reply.started":"2021-08-12T15:10:58.047364Z","shell.execute_reply":"2021-08-12T15:10:58.053614Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"effnet = efn.EfficientNetB5(weights=None,\n                        include_top=False,\n                        input_shape=(img_wd, img_ht, 3))\neffnet.load_weights('../input/efficientnet/efficientnet-b5_imagenet_1000_notop.h5/efficientnet-b5_imagenet_1000_notop.h5')","metadata":{"execution":{"iopub.status.busy":"2021-08-12T15:10:58.05587Z","iopub.execute_input":"2021-08-12T15:10:58.056346Z","iopub.status.idle":"2021-08-12T15:11:04.490373Z","shell.execute_reply.started":"2021-08-12T15:10:58.05631Z","shell.execute_reply":"2021-08-12T15:11:04.489392Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = build_model()\n","metadata":{"execution":{"iopub.status.busy":"2021-08-12T15:11:04.492266Z","iopub.execute_input":"2021-08-12T15:11:04.492628Z","iopub.status.idle":"2021-08-12T15:11:05.961754Z","shell.execute_reply.started":"2021-08-12T15:11:04.492589Z","shell.execute_reply":"2021-08-12T15:11:05.960848Z"},"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-08-12T15:11:05.963253Z","iopub.execute_input":"2021-08-12T15:11:05.963637Z","iopub.status.idle":"2021-08-12T15:11:05.976496Z","shell.execute_reply.started":"2021-08-12T15:11:05.963599Z","shell.execute_reply":"2021-08-12T15:11:05.975258Z"},"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-08-12T15:11:05.978616Z","iopub.execute_input":"2021-08-12T15:11:05.979047Z","iopub.status.idle":"2021-08-12T15:11:05.986353Z","shell.execute_reply.started":"2021-08-12T15:11:05.979007Z","shell.execute_reply":"2021-08-12T15:11:05.985054Z"},"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-08-12T15:11:05.988377Z","iopub.execute_input":"2021-08-12T15:11:05.988874Z","iopub.status.idle":"2021-08-12T15:46:04.412619Z","shell.execute_reply.started":"2021-08-12T15:11:05.988835Z","shell.execute_reply":"2021-08-12T15:46:04.411727Z"},"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-08-12T15:46:04.414357Z","iopub.execute_input":"2021-08-12T15:46:04.414725Z","iopub.status.idle":"2021-08-12T15:46:04.420827Z","shell.execute_reply.started":"2021-08-12T15:46:04.414682Z","shell.execute_reply":"2021-08-12T15:46:04.419919Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.ylim((0.7,1.0))\nplt.plot(kappa_metrics.val_kappas)","metadata":{"execution":{"iopub.status.busy":"2021-08-12T15:46:04.422222Z","iopub.execute_input":"2021-08-12T15:46:04.422679Z","iopub.status.idle":"2021-08-12T15:46:04.580102Z","shell.execute_reply.started":"2021-08-12T15:46:04.422642Z","shell.execute_reply":"2021-08-12T15:46:04.579292Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history_df = pd.DataFrame(history.history)\nprint(history_df.head())\n\nhistory_df[['loss', 'val_loss']].plot()\nhistory_df[['accuracy', 'val_accuracy']].plot()","metadata":{"execution":{"iopub.status.busy":"2021-08-12T15:46:04.581278Z","iopub.execute_input":"2021-08-12T15:46:04.581602Z","iopub.status.idle":"2021-08-12T15:46:05.242844Z","shell.execute_reply.started":"2021-08-12T15:46:04.581567Z","shell.execute_reply":"2021-08-12T15:46:05.242052Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"m1 = model.predict(x_val[0])\nprint(y_val, m1)","metadata":{"execution":{"iopub.status.busy":"2021-08-12T16:17:20.500422Z","iopub.execute_input":"2021-08-12T16:17:20.500832Z","iopub.status.idle":"2021-08-12T16:17:20.516816Z","shell.execute_reply.started":"2021-08-12T16:17:20.5008Z","shell.execute_reply":"2021-08-12T16:17:20.515263Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}