{"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":"code","source":"","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"execution_count":null,"outputs":[]},{"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-11-27T09:46:42.250248Z","iopub.execute_input":"2023-11-27T09:46:42.251216Z","iopub.status.idle":"2023-11-27T09:46:54.341965Z","shell.execute_reply.started":"2023-11-27T09:46:42.251171Z","shell.execute_reply":"2023-11-27T09:46:54.341122Z"},"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-11-27T09:46:54.343912Z","iopub.execute_input":"2023-11-27T09:46:54.344941Z","iopub.status.idle":"2023-11-27T09:46:54.383696Z","shell.execute_reply.started":"2023-11-27T09:46:54.344901Z","shell.execute_reply":"2023-11-27T09:46:54.382790Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df['type'].value_counts().plot(kind='barh')","metadata":{"execution":{"iopub.status.busy":"2023-11-27T09:46:54.385231Z","iopub.execute_input":"2023-11-27T09:46:54.385541Z","iopub.status.idle":"2023-11-27T09:46:54.696152Z","shell.execute_reply.started":"2023-11-27T09:46:54.385514Z","shell.execute_reply":"2023-11-27T09:46:54.695064Z"},"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-11-27T09:46:54.698931Z","iopub.execute_input":"2023-11-27T09:46:54.699706Z","iopub.status.idle":"2023-11-27T09:46:54.727432Z","shell.execute_reply.started":"2023-11-27T09:46:54.699671Z","shell.execute_reply":"2023-11-27T09:46:54.726561Z"},"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-11-27T09:46:54.728499Z","iopub.execute_input":"2023-11-27T09:46:54.728785Z","iopub.status.idle":"2023-11-27T09:46:54.736594Z","shell.execute_reply.started":"2023-11-27T09:46:54.728738Z","shell.execute_reply":"2023-11-27T09:46:54.735588Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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)\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-11-27T09:46:54.737735Z","iopub.execute_input":"2023-11-27T09:46:54.738094Z","iopub.status.idle":"2023-11-27T09:47:29.767505Z","shell.execute_reply.started":"2023-11-27T09:46:54.738067Z","shell.execute_reply":"2023-11-27T09:47:29.766508Z"},"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-11-27T09:47:29.768725Z","iopub.execute_input":"2023-11-27T09:47:29.769054Z","iopub.status.idle":"2023-11-27T09:47:29.920558Z","shell.execute_reply.started":"2023-11-27T09:47:29.769028Z","shell.execute_reply":"2023-11-27T09:47:29.919670Z"},"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-11-27T09:47:29.921882Z","iopub.execute_input":"2023-11-27T09:47:29.922501Z","iopub.status.idle":"2023-11-27T09:49:45.424890Z","shell.execute_reply.started":"2023-11-27T09:47:29.922467Z","shell.execute_reply":"2023-11-27T09:49:45.424035Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.save('64x3-CNN.model')","metadata":{"execution":{"iopub.status.busy":"2023-11-27T09:49:45.426139Z","iopub.execute_input":"2023-11-27T09:49:45.426410Z","iopub.status.idle":"2023-11-27T09:49:47.566805Z","shell.execute_reply.started":"2023-11-27T09:49:45.426388Z","shell.execute_reply":"2023-11-27T09:49:47.566014Z"},"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-11-27T09:49:47.569542Z","iopub.execute_input":"2023-11-27T09:49:47.569837Z","iopub.status.idle":"2023-11-27T09:49:49.121035Z","shell.execute_reply.started":"2023-11-27T09:49:47.569811Z","shell.execute_reply":"2023-11-27T09:49:49.120138Z"},"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-11-27T09:49:49.122216Z","iopub.execute_input":"2023-11-27T09:49:49.122510Z","iopub.status.idle":"2023-11-27T09:49:49.307964Z","shell.execute_reply.started":"2023-11-27T09:49:49.122485Z","shell.execute_reply":"2023-11-27T09:49:49.307152Z"},"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/1b495ac025b7.png')\npredict_class('/kaggle/working/train/No_DR/66b88a4bc474.png')","metadata":{"execution":{"iopub.status.busy":"2023-11-27T09:49:49.309210Z","iopub.execute_input":"2023-11-27T09:49:49.309957Z","iopub.status.idle":"2023-11-27T09:49:51.022994Z","shell.execute_reply.started":"2023-11-27T09:49:49.309921Z","shell.execute_reply":"2023-11-27T09:49:51.022126Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}