{"cells":[{"metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_kg_hide-output":true,"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","trusted":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\n# for 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 5GB 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":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"\n\nimport 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, auc, roc_auc_score, roc_curve\nimport sklearn\nimport scipy\nimport tensorflow as tf\nfrom tqdm import tqdm\nfrom keras.preprocessing import image\nfrom keras.models import Model\nfrom keras.layers import BatchNormalization, Dropout, Conv2D, MaxPooling2D, GlobalAveragePooling2D, Flatten, Dense\n\n%matplotlib inline\n\n","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-output":true,"trusted":true},"cell_type":"code","source":"!pip install git+https://github.com/qubvel/efficientnet","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from efficientnet.tfkeras import EfficientNetB7 as effnetb7","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"np.random.seed(2019)\ntf.random.set_seed(2019)\nTEST_SIZE = 0.40\nSEED = 2019\nBATCH_SIZE = 8","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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')\ntrain_df.head(7)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train = np.load('../input/four-fold-aptos/train_all_four.npy')\nx_test = np.load('../input/four-fold-aptos/test_all_four.npy')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_train = train_df['diagnosis'].values\ny_train\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_train_one_hot = pd.get_dummies(train_df['diagnosis']).values\n\ny_train_multi = np.empty(y_train_one_hot.shape, dtype=y_train_one_hot.dtype)\ny_train_multi[:, 4] = y_train_one_hot[:, 4]\n\nfor i in range(3, -1, -1):\n    y_train_multi[:, i] = np.logical_or(y_train_one_hot[:, i], y_train_multi[:, i+1])\n\nprint(\"Original y_train:\", y_train_one_hot.sum(axis=0))\nprint(\"Multilabel version:\", y_train_multi.sum(axis=0))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train, x_val, y_train, y_val = train_test_split(\n    x_train, y_train_multi, \n    test_size=TEST_SIZE, \n    random_state=SEED\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def 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    )\n\n# Using original generator\ndata_generator = create_datagen().flow(x_train, y_train, batch_size=BATCH_SIZE, seed=SEED)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def vgg19():\n    base_model = tf.keras.applications.VGG19(include_top=False,\n                                            weights=\"imagenet\",\n                                            input_shape=x_train[0].shape)\n    x = base_model.output\n    batch_normal = BatchNormalization()(x)\n    global_avg_pooling = GlobalAveragePooling2D()(batch_normal)\n    drop_out = Dropout(0.5)(global_avg_pooling)\n    dense1 = Dense(1024, activation='relu')(drop_out)\n    dense2 = Dense(5, activation = 'sigmoid')(dense1)\n    model = Model(inputs = base_model.input, outputs = dense2)\n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def resnet50():\n    base_model = tf.keras.applications.ResNet50(include_top=False,\n                                            weights=\"imagenet\",\n                                            input_shape=x_train[0].shape)\n    x = base_model.output\n    batch_normal = BatchNormalization()(x)\n    global_avg_pooling = GlobalAveragePooling2D()(batch_normal)\n    drop_out = Dropout(0.5)(global_avg_pooling)\n    dense1 = Dense(1024, activation='relu')(drop_out)\n    dense2 = Dense(5, activation = 'sigmoid')(dense1)\n    model = Model(inputs = base_model.input, outputs = dense2)\n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def efficientnetb7():\n    base_model = effnetb7(include_top=False,\n                     weights = None,\n                     input_shape=(224,224,3))\n    x = base_model.output\n    batch_normal = BatchNormalization()(x)\n    global_avg_pooling = GlobalAveragePooling2D()(batch_normal)\n    drop_out = Dropout(0.5)(global_avg_pooling)\n    dense1 = Dense(1024, activation='relu')(drop_out)\n    dense2 = Dense(5, activation = 'sigmoid')(dense1)\n    model = Model(inputs = base_model.input, outputs = dense2)\n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def densenet121():\n    densenet = DenseNet121(weights=None, include_top=False, input_shape=(224,224,3))\n    x = densenet.output\n    batch_normal = BatchNormalization()(x)\n    global_avg_pooling = GlobalAveragePooling2D()(batch_normal)\n    drop_out = Dropout(0.5)(global_avg_pooling)\n    dense1 = Dense(1024, activation='relu')(drop_out)\n    dense2 = Dense(5, activation = 'sigmoid')(dense1)\n    model = Model(inputs = densenet.input, outputs = dense2)\n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"vgg = vgg19()\nvgg.load_weights('../input/resnet50-weights-aptos/vgg19_aptos.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"resnet = resnet50()\nresnet.load_weights('../input/all-nets-aptos/resnet50_aptos.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"effnet = efficientnetb7()\neffnet.load_weights('../input/effnet-weights-aptos/efficientnet-b7_noisy_student_notop_four_fold_preprocess_aptos.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"densenet = densenet121()\ndensenet.load_weights('../input/aptos-densenet121/densenet121.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"eff_pred = effnet.predict(x_val)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def multi_label(x):\n    val_y = x > 0.5\n    val_y = val_y.astype(int).sum(axis=1) - 1\n    return val_y","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"eff_label = multi_label(eff_pred)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"res_pred = resnet.predict(x_val)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"res_label = multi_label(res_pred)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"vgg_pred = vgg.predict(x_val)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"vgg_label = multi_label(vgg_pred)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dense_pred = densenet.predict(x_val)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dense_label = multi_label(dense_pred)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.iloc[[20,21]]['diagnosis']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pd.get_dummies(vgg_label).values","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"vgg_label","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"res_label","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_real = [4 if (list(i)[4]==1) else list(i).index(0)-1 for i in y_val]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import math","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"f = (eff_label + vgg_label + res_label + dense_label)/4","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"final = []\nfor i in f:\n    final.append(math.ceil(i))","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-output":true,"trusted":true},"cell_type":"code","source":"final","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-output":true,"trusted":true},"cell_type":"code","source":"y_real","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cohen_kappa_score(\n            y_real,\n            final, \n            weights='quadratic'\n        )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.metrics import confusion_matrix \nfrom sklearn.metrics import accuracy_score \nfrom sklearn.metrics import classification_report\n\nactual = y_real\npredicted = final\nresults = confusion_matrix(actual, predicted) \n  \nprint ('Confusion Matrix :')\nprint(results)\nprint ('Accuracy Score :',accuracy_score(actual, predicted) )\nprint ('Report : ')\nprint (classification_report(actual, predicted))","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}