{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"import time\nt_start = time.time()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import warnings\nwarnings.filterwarnings(\"ignore\")\n\nimport pandas as pd \nimport numpy as np\nimport os, gc, sys\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport keras\nfrom keras import backend as k\nfrom keras import layers, models, optimizers, applications\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.preprocessing.image import img_to_array, load_img\n\nfrom keras.models import Model, load_model\nfrom keras.applications.resnet50 import preprocess_input\nfrom keras.layers import Dense, Dropout, GlobalAveragePooling2D, Input\nfrom keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint\n\n\nsys.path.append(os.path.abspath('../input/efficientnet/efficientnet-master/efficientnet-master/'))\nfrom efficientnet import EfficientNetB5","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"IMG_WIDTH   = 456\nIMG_HEIGHT  = 456\nCHANNEL     = 3\n\n\n# Model parameters\nBATCH_SIZE      = 4\nEPOCHS_OLD_DATA = 10\nWARMUP_EPOCHS   = 3\n\nNUM_CLASSES = 5\nSEED        = 2\n\nLEARNING_RATE        = 1e-4\nWARMUP_LEARNING_RATE = 1e-3\n\nES_PATIENCE    = 5\nRLROP_PATIENCE = 3\nDECAY_DROP     = 0.5","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"BASE_DIR  = '/kaggle/input/aptos2019-blindness-detection/'\nTRAIN_DIR = '/kaggle/input/aptos2019-blindness-detection/train_images'\nTEST_DIR  = '/kaggle/input/aptos2019-blindness-detection/test_images'\n\nTRAIN_DIR = '/kaggle/input/diabetic-retinopathy-resized/resized_train/resized_train'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"TRAIN_DF = pd.read_csv(BASE_DIR + \"train.csv\",dtype='object')\nTEST_DF = pd.read_csv(BASE_DIR + \"test.csv\",dtype='object')\n\n# changing columns using .columns() ---> oly required with new data\nTRAIN_DF = pd.read_csv(\"/kaggle/input/diabetic-retinopathy-resized/trainLabels.csv\",dtype='object')\n\n\nX_COL='id_code'\nY_COL='diagnosis'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# changing columns using .columns() ---> oly required with new data\nTRAIN_DF.columns = ['id_code', 'diagnosis'] \n\n# print(TRAIN_DF.head())\n# print(TEST_DF.head())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def append_file_ext(file_name):\n    return file_name + \".png\"\n\n\n# changing columns using .columns() ---> oly required with new data\ndef append_file_ext_jpeg(file_name):\n    return file_name.replace(\".png\",\".jpeg\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"TRAIN_DF[X_COL] = TRAIN_DF[X_COL].apply(append_file_ext)\nTEST_DF[X_COL] = TEST_DF[X_COL].apply(append_file_ext)\n\n\n# changing columns using .columns() ---> oly required with new data\nTRAIN_DF[X_COL] = TRAIN_DF[X_COL].apply(append_file_ext_jpeg)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(TRAIN_DF.head())\nprint('************************')\nprint(TEST_DF.head())\nprint('************************')\nprint(len(TRAIN_DF))\nprint('************************')\nprint(len(TEST_DF))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# TRAIN_DF['diagnosis'].hist(figsize=(10,5), bins=10)\n# print(TRAIN_DF['diagnosis'].value_counts())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df0 = TRAIN_DF.loc[TRAIN_DF['diagnosis'] == '0']\ndf1 = TRAIN_DF.loc[TRAIN_DF['diagnosis'] == '1']\ndf2 = TRAIN_DF.loc[TRAIN_DF['diagnosis'] == '2']\ndf3 = TRAIN_DF.loc[TRAIN_DF['diagnosis'] == '3']\ndf4 = TRAIN_DF.loc[TRAIN_DF['diagnosis'] == '4']\n\ndf0 = df0.head(2000)\ndf1 = df1.head(2000)\ndf2 = df2.head(2000)\n\nTRAIN_DF = df0.append([df1, df2, df3, df4],ignore_index = True)\nprint(TRAIN_DF.head())\nprint('**********************************')\nfrom sklearn.utils import shuffle\nTRAIN_DF = shuffle(TRAIN_DF)\n\nprint('**********************************')\nprint(len(TRAIN_DF))\nprint(TRAIN_DF.head())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# TRAIN_DF = TRAIN_DF.head(200)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# print(TRAIN_DF.head())\n# print('************************')\n# print(TEST_DF.head())\n# print('************************')\n# print(len(TRAIN_DF))\n# print('************************')\n# print(len(TEST_DF))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def create_model(input_shape, n_out):\n    input_tensor = Input(shape=input_shape)\n    \n    base_model = EfficientNetB5(weights=None, \n                                       include_top=False,\n                                       input_tensor=input_tensor)\n    base_model.load_weights('/kaggle/input/efficientnet-keras-weights-b0b5/efficientnet-b5_imagenet_1000_notop.h5')\n        \n\n    x = GlobalAveragePooling2D()(base_model.output)\n    x = Dropout(0.5)(x)\n    x = Dense(2048, activation='relu')(x)\n#     x = Dropout(0.5)(x)\n#     x = Dense(1024, activation='relu')(x)\n    \n    final_output = Dense(n_out, activation='softmax', name='final_output')(x)\n    model = Model(input_tensor, final_output)\n    \n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = create_model(input_shape=(IMG_WIDTH, IMG_HEIGHT, CHANNEL), n_out=NUM_CLASSES)\n\n# # Replace all Batch Normalization layers by Group Normalization layers\n# for i, layer in enumerate(model.layers):\n#     if \"batch_normalization\" in layer.name:\n#         model.layers[i] = GroupNormalization(groups=32, axis=-1, epsilon=0.00001)\n        \n        \nfor layer in model.layers:\n    layer.trainable = False\n\nfor i in range(-7, 0):\n    model.layers[i].trainable = True\n\nmetric_list = [\"accuracy\"]\noptimizer = optimizers.Adam(lr=WARMUP_LEARNING_RATE)\nmodel.compile(optimizer=optimizer, loss=\"categorical_crossentropy\",  metrics=metric_list)\n# model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def crop_image_from_gray(img, tol=7):\n    # If for some reason we only have two channels\n    if img.ndim == 2:\n        mask = img > tol\n        return img[np.ix_(mask.any(1),mask.any(0))]\n    # If we have a normal RGB images\n    elif img.ndim == 3:\n        gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n        mask = gray_img > tol\n        \n        check_shape = img[:,:,0][np.ix_(mask.any(1),mask.any(0))].shape[0]\n        if (check_shape == 0): # image is too dark so that we crop out everything,\n            return img # return original image\n        else:\n            img1=img[:,:,0][np.ix_(mask.any(1),mask.any(0))]\n            img2=img[:,:,1][np.ix_(mask.any(1),mask.any(0))]\n            img3=img[:,:,2][np.ix_(mask.any(1),mask.any(0))]\n            img = np.stack([img1,img2,img3],axis=-1)\n        return img\n\ndef preprocess_image(path, sigmaX=10):\n    image = cv2.imread(path)\n    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n    image = crop_image_from_gray(image)\n    image = cv2.resize(image, (img_width, img_height))\n    image = cv2.addWeighted (image,4, cv2.GaussianBlur(image, (0,0) ,sigmaX), -4, 128)\n    return image","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# print(TRAIN_DF.head())\n# print(TRAIN_DIR)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"datagen         = ImageDataGenerator(\n                    rescale=1./255.,\n                    validation_split=0.25)\n\ntrain_generator = datagen.flow_from_dataframe(\n                    dataframe=TRAIN_DF,\n                    directory=TRAIN_DIR,\n                    x_col=X_COL,\n                    y_col=Y_COL,\n                    subset=\"training\",\n                    batch_size=BATCH_SIZE,\n                    seed=SEED,\n                    zoom_range=0.2,\n                    horizontal_flip=True,\n                    class_mode=\"categorical\",\n                    preprocessing_function=preprocess_image,\n                    target_size=(IMG_WIDTH,IMG_HEIGHT))\n\nvalid_generator=datagen.flow_from_dataframe(\n                    dataframe=TRAIN_DF,\n                    directory=TRAIN_DIR,\n                    x_col=X_COL,\n                    y_col=Y_COL,\n                    subset=\"validation\",\n                    batch_size=BATCH_SIZE,\n                    seed=SEED,\n                    zoom_range=0.2,\n                    horizontal_flip=True,\n                    class_mode=\"categorical\",\n                    preprocessing_function=preprocess_image,    \n                    target_size=(IMG_WIDTH,IMG_HEIGHT))\n\ntest_datagen=ImageDataGenerator(rescale=1./255.)\n\ntest_generator=test_datagen.flow_from_dataframe(\n                    dataframe=TEST_DF,\n                    directory=TEST_DIR,\n                    x_col=X_COL,\n                    y_col=None,\n                    batch_size=BATCH_SIZE,\n                    seed=SEED,\n                    shuffle=False,\n                    class_mode=None,\n                    preprocessing_function=preprocess_image,    \n                    target_size=(IMG_WIDTH,IMG_HEIGHT))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"STEP_SIZE_TRAIN=train_generator.n//train_generator.batch_size\nSTEP_SIZE_VALID=valid_generator.n//valid_generator.batch_size\nSTEP_SIZE_TEST=test_generator.n//test_generator.batch_size\n\nprint(STEP_SIZE_TRAIN)\nprint(STEP_SIZE_VALID)\nprint(STEP_SIZE_TEST)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"gc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history_warmup = model.fit_generator(generator=train_generator,\n                              steps_per_epoch=STEP_SIZE_TRAIN,\n                              validation_data=valid_generator,\n                              validation_steps=STEP_SIZE_VALID,\n                              epochs=WARMUP_EPOCHS,\n                              verbose=1).history","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"gc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for layer in model.layers:\n    layer.trainable = True\n\nes = EarlyStopping(monitor='val_loss',\n                   mode='min', \n                   patience=ES_PATIENCE, \n                   restore_best_weights=True, \n                   verbose=1)\n\nrlrop = ReduceLROnPlateau(monitor='val_loss', \n                          mode='min', \n                          patience=RLROP_PATIENCE, \n                          factor=DECAY_DROP, \n                          min_lr=1e-6, \n                          verbose=1)\n\n#define the model checkpoint callback -> this will keep on saving the model as a physical file\nmodel_checkpoint = ModelCheckpoint('EfficientNetB5_Best_KV.h5',\n                                   verbose=1, \n                                   save_best_only=True)\n\ncallback_list = [es, rlrop, model_checkpoint]\noptimizer = optimizers.Adam(lr=LEARNING_RATE)\nmodel.compile(optimizer=optimizer, loss=\"binary_crossentropy\",  metrics=metric_list)\n# model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"collected = gc.collect() \nprint(\"Garbage collector: collected\",\"%d objects.\" % collected) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history_finetunning = model.fit_generator(generator=train_generator,\n                              steps_per_epoch=STEP_SIZE_TRAIN,\n                              validation_data=valid_generator,\n                              validation_steps=STEP_SIZE_VALID,\n                              epochs=EPOCHS_OLD_DATA,\n                              callbacks=callback_list,\n                              verbose=1).history","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"gc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = {'loss': history_warmup['loss'] + history_finetunning['loss'], \n           'val_loss': history_warmup['val_loss'] + history_finetunning['val_loss'], \n           'acc': history_warmup['acc'] + history_finetunning['acc'], \n           'val_acc': history_warmup['val_acc'] + history_finetunning['val_acc']}\n\nsns.set_style(\"whitegrid\")\nfig, (ax1, ax2) = plt.subplots(2, 1, sharex='col', figsize=(20, 14))\n\nax1.plot(history['loss'], label='Train loss')\nax1.plot(history['val_loss'], label='Validation loss')\nax1.legend(loc='best')\nax1.set_title('Loss')\n\nax2.plot(history['acc'], label='Train Accuracy')\nax2.plot(history['val_acc'], label='Validation accuracy')\nax2.legend(loc='best')\nax2.set_title('Accuracy')\n\nplt.xlabel('Epochs')\nsns.despine()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = load_model('EfficientNetB5_Best_KV.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"if test_generator.n%BATCH_SIZE > 0:\n    PREDICTION_STEPS = (test_generator.n//BATCH_SIZE) + 1\nelse:\n    PREDICTION_STEPS = (test_generator.n//BATCH_SIZE)\n\nprint(PREDICTION_STEPS)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(test_generator.n)\nprint(test_generator.batch_size)\nprint(STEP_SIZE_TEST)\nprint(BATCH_SIZE)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_generator.reset()\npreds = model.predict_generator(test_generator,\n                                steps=PREDICTION_STEPS, \n                                verbose=1) \npredictions = [np.argmax(pred) for pred in preds]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"gc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"filenames = test_generator.filenames\n# print(len(filenames))\n# print(len(predictions))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"results = pd.DataFrame({'id_code':filenames, 'diagnosis':predictions})\nresults['id_code'] = results['id_code'].map(lambda x: str(x)[:-4])\nresults.astype({'diagnosis': 'int64'})\nresults.to_csv('submission.csv',index=False)\nprint(results.head(10))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"gc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Check kernels run-time. GPU limit for this competition is set to ± 9 hours.\nt_finish = time.time()\ntotal_time = round((t_finish-t_start) / 3600, 4)\nprint('Kernel runtime = {} hours ({} minutes)'.format(total_time, \n                                                      int(total_time*60)))","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":1}