{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","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 in \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 \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"../input\"))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from PIL import Image\nimport os\nimport glob\nimport matplotlib.pyplot as plt\nimport cv2\nfrom keras.utils import to_categorical\nimport keras\n","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"train = pd.read_csv(\"../input/aptos2019-blindness-detection/train.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\ndef convert_img(img):\n    desired_size = 224\n    im_pth = img\n\n    im = Image.open(im_pth)\n    old_size = im.size  # old_size[0] is in (width, height) format\n\n    ratio = float(desired_size)/max(old_size)\n    new_size = tuple([int(x*ratio) for x in old_size])\n    # use thumbnail() or resize() method to resize the input image\n\n    # thumbnail is a in-place operation\n\n    # im.thumbnail(new_size, Image.ANTIALIAS)\n\n    im = im.resize(new_size, Image.ANTIALIAS)\n    # create a new image and paste the resized on it\n\n    new_im = Image.new(\"RGB\", (desired_size, desired_size))\n    new_im.paste(im, ((desired_size-new_size[0])//2,\n                        (desired_size-new_size[1])//2))\n\n    new_im.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def convert_img(img):    \n    desired_size = 224\n    im_pth = img\n    im = Image.open(im_pth)\n    old_size = im.size  # old_size[0] is in (width, height) format\n\n    ratio = float(desired_size)/max(old_size)\n    new_size = tuple([int(x*ratio) for x in old_size])\n    # use thumbnail() or resize() method to resize the input image\n\n    # thumbnail is a in-place operation\n\n    # im.thumbnail(new_size, Image.ANTIALIAS)\n\n    im = im.resize(new_size, Image.ANTIALIAS)\n    # create a new image and paste the resized on it\n\n    new_im = Image.new(\"RGB\", (desired_size, desired_size))\n    new_im.paste(im, ((desired_size-new_size[0])//2,\n                        (desired_size-new_size[1])//2))\n    return new_im","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"raw","source":"test_list = [[Image.open('../input/aptos2019-blindness-detection/train_images/'+i+\".png\"),j] for i,j in zip(train.id_code[0:6],train.diagnosis[0:6])]    \nfor i,j in test_list:\n    plt.figure(figsize=(5,5))\n    i = cv2.resize(np.asarray(i),(224,224))\n    plt.title(j)\n    plt.imshow(i)\n    plt.show \n    convert_img(img)"},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train = [np.array(convert_img(\"../input/aptos2019-blindness-detection/train_images/\"+i+\".png\")) for i in train.id_code]  ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train = np.array(x_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_train = train.diagnosis","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.groupby(train.diagnosis).count()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_train = to_categorical(y_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = keras.applications.densenet.DenseNet121(include_top=True, weights=None)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.load_weights(\"../input/densenet121/densenet121.h5\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"raw","source":"import keras.backend as K\nimport tensorflow as tf\ndef _cohen_kappa(y_true, y_pred, num_classes, weights=None, metrics_collections=None, updates_collections=None, name=None):\n    kappa, update_op = tf.contrib.metrics.cohen_kappa(y_true, y_pred, num_classes, weights, metrics_collections, updates_collections, name)\n    K.get_session().run(tf.local_variables_initializer())\n    with tf.control_dependencies([update_op]):\n        kappa = tf.identity(kappa)\n    return kappa\n\ndef cohen_kappa_loss(num_classes, weights=None, metrics_collections=None, updates_collections=None, name=None):\n    def cohen_kappa(y_true, y_pred):\n        return -_cohen_kappa(y_true, y_pred, num_classes, weights, metrics_collections, updates_collections, name)\n    return cohen_kappa\nmodel_cohen_kappa = cohen_kappa_loss(num_classes=5,weights='quadratic')"},{"metadata":{"trusted":true},"cell_type":"code","source":"x = model.layers[-2].output\nd = keras.layers.Dense(512,activation='relu')(x)\ne = keras.layers.Dense(5,activation='softmax')(d)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model1 = keras.models.Model(model.input,e)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model1.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model1.fit(x_train,y_train,validation_split=0.10,epochs=20,class_weight={0:0.1,1:0.5,2:0.4,3:0.8,4:0.6})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model1.fit(x_train,y_train,validation_split=0.10,epochs=10)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"testdf = pd.read_csv(\"../input/aptos2019-blindness-detection/test.csv\")\ntestx = []\nfor i in testdf.id_code:\n    temp = np.array(cv2.resize(np.array(Image.open('../input/aptos2019-blindness-detection/test_images/'+i+\".png\")),(224,224)))\n    testx.append(temp)\ntestx = np.array(testx)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"result = model1.predict(testx)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"res = []\nfor i in result:\n    res.append(np.argmax(i))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_test = pd.DataFrame({\"id_code\": testdf[\"id_code\"].values, \"diagnosis\": res})\ndf_test.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len(testdf)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_test.to_csv('submission.csv', index=False)\n","execution_count":null,"outputs":[]}],"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}