{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":4104,"databundleVersionId":46661,"sourceType":"competition"},{"sourceId":952401,"sourceType":"datasetVersion","datasetId":517172}],"dockerImageVersionId":30588,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"from tensorflow import lite\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nimport numpy as np\nimport pandas as pd\nimport random, os\nimport shutil\nimport matplotlib.pyplot as plt\nfrom matplotlib.image import imread\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.metrics import categorical_accuracy\nfrom sklearn.model_selection import train_test_split","metadata":{"execution":{"iopub.status.busy":"2023-12-03T17:51:40.390946Z","iopub.execute_input":"2023-12-03T17:51:40.391707Z","iopub.status.idle":"2023-12-03T17:51:52.233645Z","shell.execute_reply.started":"2023-12-03T17:51:40.391668Z","shell.execute_reply":"2023-12-03T17:51:52.232855Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.read_csv(r'../input/diabetic-retinopathy-224x224-gaussian-filtered/train.csv')\n\ndiagnosis_dict_binary = {\n    0: 'No_DR',\n    1: 'DR',\n    2: 'DR',\n    3: 'DR',\n    4: 'DR'\n}\n\ndiagnosis_dict = {\n    0: 'No_DR',\n    1: 'Mild',\n    2: 'Moderate',\n    3: 'Severe',\n    4: 'Proliferate_DR',\n}\n\n\ndf['binary_type'] =  df['diagnosis'].map(diagnosis_dict_binary.get)\ndf['type'] = df['diagnosis'].map(diagnosis_dict.get)\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2023-12-03T17:51:52.235244Z","iopub.execute_input":"2023-12-03T17:51:52.235721Z","iopub.status.idle":"2023-12-03T17:51:52.276855Z","shell.execute_reply.started":"2023-12-03T17:51:52.235695Z","shell.execute_reply":"2023-12-03T17:51:52.276037Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df['type'].value_counts().plot(kind='barh')","metadata":{"execution":{"iopub.status.busy":"2023-12-03T17:51:52.277969Z","iopub.execute_input":"2023-12-03T17:51:52.278720Z","iopub.status.idle":"2023-12-03T17:51:52.559432Z","shell.execute_reply.started":"2023-12-03T17:51:52.278686Z","shell.execute_reply":"2023-12-03T17:51:52.558466Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_intermediate, val = train_test_split(df, test_size = 0.15, stratify = df['type'])\ntrain, test = train_test_split(train_intermediate, test_size = 0.15 / (1 - 0.15), stratify = train_intermediate['type'])\n\nprint(\"For Training Dataset :\")\nprint(train['type'].value_counts(), '\\n')\nprint(\"For Testing Dataset :\")\nprint(test['type'].value_counts(), '\\n')\nprint(\"For Validation Dataset :\")\nprint(val['type'].value_counts(), '\\n')","metadata":{"execution":{"iopub.status.busy":"2023-12-03T17:51:52.562217Z","iopub.execute_input":"2023-12-03T17:51:52.562584Z","iopub.status.idle":"2023-12-03T17:51:52.589992Z","shell.execute_reply.started":"2023-12-03T17:51:52.562547Z","shell.execute_reply":"2023-12-03T17:51:52.589119Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"base_dir = ''\n\ntrain_dir = os.path.join(base_dir, 'train')\nval_dir = os.path.join(base_dir, 'val')\ntest_dir = os.path.join(base_dir, 'test')\n\nif os.path.exists(base_dir):\n    shutil.rmtree(base_dir)\n\nif os.path.exists(train_dir):\n    shutil.rmtree(train_dir)\nos.makedirs(train_dir)\n\nif os.path.exists(val_dir):\n    shutil.rmtree(val_dir)\nos.makedirs(val_dir)\n\nif os.path.exists(test_dir):\n    shutil.rmtree(test_dir)\nos.makedirs(test_dir)","metadata":{"execution":{"iopub.status.busy":"2023-12-03T17:51:52.592618Z","iopub.execute_input":"2023-12-03T17:51:52.592895Z","iopub.status.idle":"2023-12-03T17:51:52.599381Z","shell.execute_reply.started":"2023-12-03T17:51:52.592870Z","shell.execute_reply":"2023-12-03T17:51:52.598579Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"src_dir = r'../input/diabetic-retinopathy-224x224-gaussian-filtered/gaussian_filtered_images/gaussian_filtered_images'\nfor index, row in train.iterrows():\n    diagnosis = row['type']\n    binary_diagnosis = row['binary_type']\n    id_code = row['id_code'] + \".png\"\n    srcfile = os.path.join(src_dir, diagnosis, id_code)\n    dstfile = os.path.join(train_dir, binary_diagnosis)\n    os.makedirs(dstfile, exist_ok = True)\n    shutil.copy(srcfile, dstfile)\n\nfor index, row in val.iterrows():\n    diagnosis = row['type']\n    binary_diagnosis = row['binary_type']\n    id_code = row['id_code'] + \".png\"\n    srcfile = os.path.join(src_dir, diagnosis, id_code)\n    dstfile = os.path.join(val_dir, binary_diagnosis)\n    os.makedirs(dstfile, exist_ok = True)\n    shutil.copy(srcfile, dstfile)\n \nfor index, row in test.iterrows():\n    diagnosis = row['type']\n    binary_diagnosis = row['binary_type']\n    id_code = row['id_code'] + \".png\"\n    srcfile = os.path.join(src_dir, diagnosis, id_code)\n    dstfile = os.path.join(test_dir, binary_diagnosis)\n    os.makedirs(dstfile, exist_ok = True)\n    shutil.copy(srcfile, dstfile)","metadata":{"execution":{"iopub.status.busy":"2023-12-03T17:51:52.600979Z","iopub.execute_input":"2023-12-03T17:51:52.601318Z","iopub.status.idle":"2023-12-03T17:52:46.824653Z","shell.execute_reply.started":"2023-12-03T17:51:52.601287Z","shell.execute_reply":"2023-12-03T17:52:46.823648Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_path = 'train'\nval_path = 'val'\ntest_path = 'test'\n\ntrain_batches = ImageDataGenerator(rescale = 1./255).flow_from_directory(train_path, target_size=(224,224), shuffle = True)\nval_batches = ImageDataGenerator(rescale = 1./255).flow_from_directory(val_path, target_size=(224,224), shuffle = True)\ntest_batches = ImageDataGenerator(rescale = 1./255).flow_from_directory(test_path, target_size=(224,224), shuffle = False)","metadata":{"execution":{"iopub.status.busy":"2023-12-03T17:52:46.826019Z","iopub.execute_input":"2023-12-03T17:52:46.826420Z","iopub.status.idle":"2023-12-03T17:52:46.989691Z","shell.execute_reply.started":"2023-12-03T17:52:46.826383Z","shell.execute_reply":"2023-12-03T17:52:46.988912Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = tf.keras.Sequential([\n    layers.Conv2D(8, (3,3), padding=\"valid\", input_shape=(224,224,3), activation = 'relu'),\n    layers.MaxPooling2D(pool_size=(2,2)),\n    layers.BatchNormalization(),\n    \n    layers.Conv2D(16, (3,3), padding=\"valid\", activation = 'relu'),\n    layers.MaxPooling2D(pool_size=(2,2)),\n    layers.BatchNormalization(),\n    \n    layers.Conv2D(32, (4,4), padding=\"valid\", activation = 'relu'),\n    layers.MaxPooling2D(pool_size=(2,2)),\n    layers.BatchNormalization(),\n    \n    layers.Conv2D(64, (4,4), padding=\"valid\", activation = 'relu'),\n    layers.MaxPooling2D(pool_size=(2,2)),\n    layers.BatchNormalization(),\n \n    layers.Flatten(),\n    layers.Dense(64, activation = 'relu'),\n    layers.Dropout(0.15),\n    layers.Dense(2, activation = 'softmax')\n])\n\nmodel.compile(optimizer=tf.keras.optimizers.Adam(lr = 1e-5),\n              loss=tf.keras.losses.BinaryCrossentropy(),\n              metrics=['acc'])\n\nhistory = model.fit(train_batches,\n                    epochs=15,\n                    validation_data=val_batches)","metadata":{"execution":{"iopub.status.busy":"2023-12-03T17:52:46.990925Z","iopub.execute_input":"2023-12-03T17:52:46.991432Z","iopub.status.idle":"2023-12-03T17:55:03.442410Z","shell.execute_reply.started":"2023-12-03T17:52:46.991397Z","shell.execute_reply":"2023-12-03T17:55:03.441500Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.save('64x3-CNN.model')","metadata":{"execution":{"iopub.status.busy":"2023-12-03T17:55:03.443713Z","iopub.execute_input":"2023-12-03T17:55:03.444043Z","iopub.status.idle":"2023-12-03T17:55:05.575779Z","shell.execute_reply.started":"2023-12-03T17:55:03.444011Z","shell.execute_reply":"2023-12-03T17:55:05.574801Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"loss, acc = model.evaluate_generator(test_batches, verbose=1)\nprint(\"Loss: \", loss)\nprint(\"Accuracy: \", acc)","metadata":{"execution":{"iopub.status.busy":"2023-12-03T17:55:05.580051Z","iopub.execute_input":"2023-12-03T17:55:05.580656Z","iopub.status.idle":"2023-12-03T17:55:07.090348Z","shell.execute_reply.started":"2023-12-03T17:55:05.580620Z","shell.execute_reply":"2023-12-03T17:55:07.089451Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef predict_class(path):\n    img = cv2.imread(path)\n\n    RGBImg = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)\n    RGBImg= cv2.resize(RGBImg,(224,224))\n    plt.imshow(RGBImg)\n    image = np.array(RGBImg) / 255.0\n    new_model = tf.keras.models.load_model(\"64x3-CNN.model\")\n    predict=new_model.predict(np.array([image]))\n    per=np.argmax(predict,axis=1)\n    if per==1:\n        print('Diabetic Retinopathy Not Detected')\n    else:\n        print('Diabetic Retinopathy Detected')","metadata":{"execution":{"iopub.status.busy":"2023-12-03T17:55:07.092744Z","iopub.execute_input":"2023-12-03T17:55:07.093030Z","iopub.status.idle":"2023-12-03T17:55:07.274931Z","shell.execute_reply.started":"2023-12-03T17:55:07.093003Z","shell.execute_reply":"2023-12-03T17:55:07.274211Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predict_class('/kaggle/input/diabetic-retinopathy-224x224-gaussian-filtered/gaussian_filtered_images/gaussian_filtered_images/Severe/0104b032c141.png')","metadata":{"execution":{"iopub.status.busy":"2023-12-03T18:01:10.186645Z","iopub.execute_input":"2023-12-03T18:01:10.187004Z","iopub.status.idle":"2023-12-03T18:01:11.540365Z","shell.execute_reply.started":"2023-12-03T18:01:10.186973Z","shell.execute_reply":"2023-12-03T18:01:11.539419Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}