{"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":"# 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\nfor 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 20GB 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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-02-08T09:46:56.904382Z","iopub.execute_input":"2023-02-08T09:46:56.904841Z","iopub.status.idle":"2023-02-08T09:47:02.286929Z","shell.execute_reply.started":"2023-02-08T09:46:56.904747Z","shell.execute_reply":"2023-02-08T09:47:02.285881Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np \nimport pandas as pd \nimport cv2\nimport os\nfrom zipfile import ZipFile\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.utils import img_to_array\nfrom keras.utils import np_utils\nfrom keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout\nfrom keras.models import Sequential","metadata":{"execution":{"iopub.status.busy":"2023-02-08T09:47:02.289219Z","iopub.execute_input":"2023-02-08T09:47:02.290073Z","iopub.status.idle":"2023-02-08T09:47:08.197624Z","shell.execute_reply.started":"2023-02-08T09:47:02.290025Z","shell.execute_reply":"2023-02-08T09:47:08.196298Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataset = []\nlabels = []","metadata":{"execution":{"iopub.status.busy":"2023-02-08T09:47:08.203451Z","iopub.execute_input":"2023-02-08T09:47:08.204933Z","iopub.status.idle":"2023-02-08T09:47:08.228269Z","shell.execute_reply.started":"2023-02-08T09:47:08.204854Z","shell.execute_reply":"2023-02-08T09:47:08.222768Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def prepare_Images(label,path):\n    img=cv2.imread(path,cv2.IMREAD_COLOR)\n    try:\n      img_res=cv2.resize(img,(256,256))\n      img_array = img_to_array(img_res)\n      img_array = img_array/255.0\n      dataset.append(img_array)\n      if str(label) == '0':\n        labels.append('0')\n      else:\n        labels.append('1')\n    except:\n      print(\"error\")","metadata":{"execution":{"iopub.status.busy":"2023-02-08T09:47:08.236798Z","iopub.execute_input":"2023-02-08T09:47:08.243491Z","iopub.status.idle":"2023-02-08T09:47:08.255330Z","shell.execute_reply.started":"2023-02-08T09:47:08.243443Z","shell.execute_reply":"2023-02-08T09:47:08.253966Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_Data = pd.read_csv(\"/kaggle/input/aptos2019-blindness-detection/train.csv\")\ntrain_Data.head()","metadata":{"execution":{"iopub.status.busy":"2023-02-08T09:47:08.257515Z","iopub.execute_input":"2023-02-08T09:47:08.258366Z","iopub.status.idle":"2023-02-08T09:47:08.299998Z","shell.execute_reply.started":"2023-02-08T09:47:08.258325Z","shell.execute_reply":"2023-02-08T09:47:08.298816Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"id_code_Data = train_Data['id_code']\ndiagnosis_Data = train_Data['diagnosis']","metadata":{"execution":{"iopub.status.busy":"2023-02-08T09:47:08.304963Z","iopub.execute_input":"2023-02-08T09:47:08.305799Z","iopub.status.idle":"2023-02-08T09:47:08.315117Z","shell.execute_reply.started":"2023-02-08T09:47:08.305758Z","shell.execute_reply":"2023-02-08T09:47:08.313781Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for id_code,diagnosis in tqdm(zip(id_code_Data,diagnosis_Data)):\n    path = os.path.join('/kaggle/input/aptos2019-blindness-detection/train_images','{}.png'.format(id_code))\n    prepare_Images(diagnosis,path)","metadata":{"execution":{"iopub.status.busy":"2023-02-08T09:47:08.320737Z","iopub.execute_input":"2023-02-08T09:47:08.321720Z","iopub.status.idle":"2023-02-08T09:51:00.924920Z","shell.execute_reply.started":"2023-02-08T09:47:08.321654Z","shell.execute_reply":"2023-02-08T09:51:00.921874Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"images = np.array(dataset)\nlabel_arr = np.array(labels)\n","metadata":{"execution":{"iopub.status.busy":"2023-02-08T09:51:04.754906Z","iopub.execute_input":"2023-02-08T09:51:04.755292Z","iopub.status.idle":"2023-02-08T09:51:05.238566Z","shell.execute_reply.started":"2023-02-08T09:51:04.755260Z","shell.execute_reply":"2023-02-08T09:51:05.237446Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nx_train,x_test,y_train,y_test = train_test_split(images,label_arr,stratify=label_arr,test_size=0.20,random_state=44)\n","metadata":{"execution":{"iopub.status.busy":"2023-02-08T09:51:05.240680Z","iopub.execute_input":"2023-02-08T09:51:05.241135Z","iopub.status.idle":"2023-02-08T09:51:06.174570Z","shell.execute_reply.started":"2023-02-08T09:51:05.241087Z","shell.execute_reply":"2023-02-08T09:51:06.173383Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_train= np_utils.to_categorical(y_train, num_classes=2)\ny_test = np_utils.to_categorical(y_test, num_classes=2)","metadata":{"execution":{"iopub.status.busy":"2023-02-08T09:51:06.177164Z","iopub.execute_input":"2023-02-08T09:51:06.177601Z","iopub.status.idle":"2023-02-08T09:51:06.184825Z","shell.execute_reply.started":"2023-02-08T09:51:06.177560Z","shell.execute_reply":"2023-02-08T09:51:06.183600Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os, sys\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport skimage.io\nfrom skimage.transform import resize\nfrom imgaug import augmenters as iaa\nfrom tqdm import tqdm\nimport PIL\nfrom PIL import Image, ImageOps\nimport cv2\nfrom sklearn.utils import class_weight, shuffle\nfrom keras.losses import binary_crossentropy\nfrom keras.applications.resnet import preprocess_input\nimport keras.backend as K\nimport tensorflow as tf\nfrom sklearn.metrics import f1_score, fbeta_score\n\nfrom sklearn.model_selection import train_test_split\n\ninput_shape = (128,256, 256, 3)\nn_classes = 2\n\nresnet_model = tf.keras.applications.ResNet50(\n    input_shape=(256,256,3), \n    include_top=False, \n    weights='imagenet'\n)\n\nresnet_model.trainable =False\n\nresnet_model.summary()\n","metadata":{"execution":{"iopub.status.busy":"2023-02-08T09:51:07.329656Z","iopub.execute_input":"2023-02-08T09:51:07.330405Z","iopub.status.idle":"2023-02-08T09:51:13.566356Z","shell.execute_reply.started":"2023-02-08T09:51:07.330366Z","shell.execute_reply":"2023-02-08T09:51:13.563954Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"resnettrain = tf.keras.Sequential([\n    resnet_model,\n    tf.keras.layers.BatchNormalization(),\n\n    tf.keras.layers.Flatten(),\n    \n    tf.keras.layers.Dense(16, activation='relu'),\n    tf.keras.layers.Dropout(0.5),\n    tf.keras.layers.Dense(8, activation='relu'),\n    tf.keras.layers.Dropout(0.5),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.Dense(2, activation='sigmoid')\n])\n\nresnettrain.summary()","metadata":{"execution":{"iopub.status.busy":"2023-02-08T09:51:19.858478Z","iopub.execute_input":"2023-02-08T09:51:19.858898Z","iopub.status.idle":"2023-02-08T09:51:20.333390Z","shell.execute_reply.started":"2023-02-08T09:51:19.858862Z","shell.execute_reply":"2023-02-08T09:51:20.332285Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"resnettrain.compile(\n    optimizer=\"adam\",\n    loss=tf.keras.losses.CategoricalCrossentropy(from_logits=False),\n    metrics=[\"accuracy\"]\n)","metadata":{"execution":{"iopub.status.busy":"2023-02-08T09:51:24.471487Z","iopub.execute_input":"2023-02-08T09:51:24.471894Z","iopub.status.idle":"2023-02-08T09:51:24.494795Z","shell.execute_reply.started":"2023-02-08T09:51:24.471859Z","shell.execute_reply":"2023-02-08T09:51:24.493381Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = resnettrain.fit(\n    x_train,\n    y_train,\n    batch_size=128,\n    verbose=1,\n    epochs=100\n    \n)","metadata":{"execution":{"iopub.status.busy":"2023-02-08T09:51:36.287796Z","iopub.execute_input":"2023-02-08T09:51:36.288166Z","iopub.status.idle":"2023-02-08T09:58:04.568555Z","shell.execute_reply.started":"2023-02-08T09:51:36.288132Z","shell.execute_reply":"2023-02-08T09:58:04.567497Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred = resnettrain.predict(x_test)\n\nresnettrain.evaluate(x_test,y_test)","metadata":{"execution":{"iopub.status.busy":"2023-02-08T09:58:04.570713Z","iopub.execute_input":"2023-02-08T09:58:04.571285Z","iopub.status.idle":"2023-02-08T09:58:10.408166Z","shell.execute_reply.started":"2023-02-08T09:58:04.571244Z","shell.execute_reply":"2023-02-08T09:58:10.407086Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import accuracy_score, classification_report,confusion_matrix\nconMat = confusion_matrix(y_test.argmax(axis=1),pred.argmax(axis=1))\nprint(conMat)","metadata":{"execution":{"iopub.status.busy":"2023-02-08T09:58:16.229876Z","iopub.execute_input":"2023-02-08T09:58:16.230275Z","iopub.status.idle":"2023-02-08T09:58:16.241001Z","shell.execute_reply.started":"2023-02-08T09:58:16.230241Z","shell.execute_reply":"2023-02-08T09:58:16.239674Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nscore = round(accuracy_score(y_test.argmax(axis=1), pred.argmax(axis=1)),2)\nprint(score)","metadata":{"execution":{"iopub.status.busy":"2023-02-08T09:58:19.010898Z","iopub.execute_input":"2023-02-08T09:58:19.011265Z","iopub.status.idle":"2023-02-08T09:58:19.019870Z","shell.execute_reply.started":"2023-02-08T09:58:19.011235Z","shell.execute_reply":"2023-02-08T09:58:19.018750Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.preprocessing import normalize\nimport seaborn as sns\nnormed_confusion_matrix = normalize(conMat , axis = 1, norm = 'l1')\ncm_df = pd.DataFrame(normed_confusion_matrix)\nsns.heatmap (cm_df , annot =True)","metadata":{"execution":{"iopub.status.busy":"2023-02-08T09:58:21.540009Z","iopub.execute_input":"2023-02-08T09:58:21.540414Z","iopub.status.idle":"2023-02-08T09:58:21.967215Z","shell.execute_reply.started":"2023-02-08T09:58:21.540380Z","shell.execute_reply":"2023-02-08T09:58:21.966040Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"report = classification_report(y_test.argmax(axis=1), pred.argmax(axis=1))\nprint(report)","metadata":{"execution":{"iopub.status.busy":"2023-02-08T09:58:26.135828Z","iopub.execute_input":"2023-02-08T09:58:26.136231Z","iopub.status.idle":"2023-02-08T09:58:26.152060Z","shell.execute_reply.started":"2023-02-08T09:58:26.136198Z","shell.execute_reply":"2023-02-08T09:58:26.150600Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"acc = history.history['accuracy']\nloss = history.history['loss']\n\nplt.figure(figsize = (8,8))\nplt.subplot(1,2,1)\nplt.plot(range(100),acc,label='Training Accuracy')\nplt.legend(loc=\"lower right\")\nplt.title(\"Training over 100 epochs\")\n","metadata":{"execution":{"iopub.status.busy":"2023-02-08T09:59:32.904636Z","iopub.execute_input":"2023-02-08T09:59:32.905206Z","iopub.status.idle":"2023-02-08T09:59:33.197599Z","shell.execute_reply.started":"2023-02-08T09:59:32.905165Z","shell.execute_reply":"2023-02-08T09:59:33.196575Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize = (8,8))\nplt.subplot(1,2,1)\nplt.plot(range(100),loss,label='Training Loss')\nplt.legend(loc=\"upper right\")\nplt.title(\"Training Loss over 100 epochs\")","metadata":{"execution":{"iopub.status.busy":"2023-02-08T10:12:41.207531Z","iopub.execute_input":"2023-02-08T10:12:41.208224Z","iopub.status.idle":"2023-02-08T10:12:41.434860Z","shell.execute_reply.started":"2023-02-08T10:12:41.208183Z","shell.execute_reply":"2023-02-08T10:12:41.433732Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}