{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\nfrom keras import applications\nfrom keras.models import Model\nfrom keras.layers import Dense, Flatten, Dropout,GlobalMaxPooling2D\nimport matplotlib.pyplot as plt\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport os\nprint(os.listdir(\"../input\"))\nimport cv2\nfrom tqdm import tqdm_notebook\nimport matplotlib.pyplot as plt\n\n%matplotlib inline\n","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","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')\n\ntrain_dir = '../input/aptos2019-blindness-detection/train_images'\ntest_dir = '../input/aptos2019-blindness-detection/test_images'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df[\"id_code\"]=train_df[\"id_code\"].apply(lambda x:x+\".png\")\ntrain_df['diagnosis'] = train_df['diagnosis'].astype(str)\n\ntest_df[\"id_code\"]=test_df[\"id_code\"].apply(lambda x:x+\".png\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Showing some images"},{"metadata":{"trusted":true},"cell_type":"code","source":"imgs = []\nfor imgk in tqdm_notebook(os.listdir(train_dir)[:5]):\n        path = os.path.join(train_dir,imgk)\n        imgl = cv2.imread(path,cv2.IMREAD_COLOR)\n        imgs.append(np.array(imgl))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"imgs = np.asarray(imgs)\nprint(imgs[1].shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"   \nfig, axs = plt.subplots(2, 2)\naxs[0, 0].imshow(imgs[0])\naxs[1, 0].imshow(imgs[1])\naxs[0, 1].imshow(imgs[2])\naxs[1, 1].imshow(imgs[3])\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"imgsize = 250","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = applications.ResNet50(include_top=False,input_shape= (imgsize,imgsize,3), \n                              weights = '../input/resnet50/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#model.trainable = False\nfor layer in model.layers[:-15]:\n       layer.trainable = False","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model_x = model.output\nmodel_x = GlobalMaxPooling2D()(model_x)\nmodel_x = Dropout(0.3)(model_x)\nmodel_x = Dense(1024,activation='relu')(model_x)\nmodel_x = Dropout(0.3)(model_x)\npredictions = Dense(5, activation='softmax')(model_x)\n\nmodel_output = Model(inputs=model.input, outputs=predictions)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_tr = [] #training image\nY_tr = [] #training lables\ntest_img = [] #test images","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#loading training images and labels\ndef load_train_image(f_path):\n        imges = train_df['id_code']\n        for img_id in tqdm_notebook(imges):\n                img = cv2.imread(os.path.join(f_path, img_id), cv2.IMREAD_COLOR)\n                img = cv2.resize(img,(imgsize,imgsize))\n                X_tr.append(np.array(img))\n                Y_tr.append(train_df[train_df['id_code'] == img_id]['diagnosis'].values[0])  \n        return X_tr, Y_tr","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#loading test images\ndef load_test_image(ft_path):\n        imgts = test_df['id_code']\n        for img_id_ts in tqdm_notebook(imgts):\n                imgk = cv2.imread(os.path.join(ft_path, img_id_ts), cv2.IMREAD_COLOR)\n                imgk = cv2.resize(imgk,(imgsize,imgsize))\n                test_img.append(np.array(imgk))\n                  \n        return test_img","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"load_train_image(f'../input/aptos2019-blindness-detection/train_images/')\n\nX_tr = np.array(X_tr)\nX_tr = X_tr.astype('float32')\nX_tr /= 255\nY_tr = np.array(Y_tr)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"load_test_image(f'../input/aptos2019-blindness-detection/test_images/')\n\ntest_img = np.array(test_img)\ntest_img = test_img.astype('float32')\ntest_img /= 255","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\ndata_gen = ImageDataGenerator(horizontal_flip = True,\n                              vertical_flip = True,\n                             rotation_range=20,\n                             width_shift_range=0.2,\n                             height_shift_range=0.2,\n                             validation_split = 0.20\n                                                   )\ntrain_aug = data_gen.flow(X_tr,Y_tr,\n                          subset = 'training')\ntrain_valid_aug = data_gen.flow(X_tr,\n                               Y_tr,\n                               subset = 'validation')\n\ntest_aug = data_gen.flow(test_img)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model_output.compile(loss='sparse_categorical_crossentropy',             \n              optimizer='adam',      \n              metrics=['acc'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model_output.fit_generator(generator = train_aug,\n                              steps_per_epoch=90,\n                              epochs=10,\n                              validation_data=train_valid_aug,\n                              validation_steps=20\n                              )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# summarize history for accuracy\nplt.plot(history.history['acc'])\nplt.plot(history.history['val_acc'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()\n# summarize history for loss\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"batch_size = 32\nresult = model_output.predict_generator(test_aug ,steps = (test_img.shape[0] // batch_size)+1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(result)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Kernal Needs to be upated."}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.4","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}