{"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":"2024-01-23T05:53:34.218185Z","iopub.execute_input":"2024-01-23T05:53:34.219064Z","iopub.status.idle":"2024-01-23T05:53:34.225777Z","shell.execute_reply.started":"2024-01-23T05:53:34.219028Z","shell.execute_reply":"2024-01-23T05:53:34.224724Z"},"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":"2024-01-23T05:53:35.378641Z","iopub.execute_input":"2024-01-23T05:53:35.379308Z","iopub.status.idle":"2024-01-23T05:53:35.420894Z","shell.execute_reply.started":"2024-01-23T05:53:35.379275Z","shell.execute_reply":"2024-01-23T05:53:35.419874Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df['type'].value_counts().plot(kind='barh')","metadata":{"execution":{"iopub.status.busy":"2024-01-23T05:53:36.565281Z","iopub.execute_input":"2024-01-23T05:53:36.566179Z","iopub.status.idle":"2024-01-23T05:53:36.882101Z","shell.execute_reply.started":"2024-01-23T05:53:36.566137Z","shell.execute_reply":"2024-01-23T05:53:36.881103Z"},"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":"2024-01-23T05:53:38.032295Z","iopub.execute_input":"2024-01-23T05:53:38.033201Z","iopub.status.idle":"2024-01-23T05:53:38.063791Z","shell.execute_reply.started":"2024-01-23T05:53:38.033163Z","shell.execute_reply":"2024-01-23T05:53:38.062762Z"},"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":"2024-01-23T05:53:39.197606Z","iopub.execute_input":"2024-01-23T05:53:39.198014Z","iopub.status.idle":"2024-01-23T05:53:39.206265Z","shell.execute_reply.started":"2024-01-23T05:53:39.197971Z","shell.execute_reply":"2024-01-23T05:53:39.205125Z"},"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)\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":"2024-01-23T05:53:42.486958Z","iopub.execute_input":"2024-01-23T05:53:42.487331Z","iopub.status.idle":"2024-01-23T05:54:10.746168Z","shell.execute_reply.started":"2024-01-23T05:53:42.487304Z","shell.execute_reply":"2024-01-23T05:54:10.745229Z"},"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":"2024-01-23T05:54:18.992040Z","iopub.execute_input":"2024-01-23T05:54:18.992794Z","iopub.status.idle":"2024-01-23T05:54:19.189588Z","shell.execute_reply.started":"2024-01-23T05:54:18.992754Z","shell.execute_reply":"2024-01-23T05:54:19.188432Z"},"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":"2024-01-23T05:54:21.569432Z","iopub.execute_input":"2024-01-23T05:54:21.569848Z","iopub.status.idle":"2024-01-23T05:56:51.770413Z","shell.execute_reply.started":"2024-01-23T05:54:21.569817Z","shell.execute_reply":"2024-01-23T05:56:51.769497Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.save('64x3-CNN.model')","metadata":{"execution":{"iopub.status.busy":"2024-01-23T05:57:19.301235Z","iopub.execute_input":"2024-01-23T05:57:19.302150Z","iopub.status.idle":"2024-01-23T05:57:21.740303Z","shell.execute_reply.started":"2024-01-23T05:57:19.302114Z","shell.execute_reply":"2024-01-23T05:57:21.739345Z"},"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":"2024-01-23T05:57:21.743559Z","iopub.execute_input":"2024-01-23T05:57:21.743999Z","iopub.status.idle":"2024-01-23T05:57:23.622578Z","shell.execute_reply.started":"2024-01-23T05:57:21.743959Z","shell.execute_reply":"2024-01-23T05:57:23.621506Z"},"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":"2024-01-23T05:57:23.623714Z","iopub.execute_input":"2024-01-23T05:57:23.624004Z","iopub.status.idle":"2024-01-23T05:57:23.826931Z","shell.execute_reply.started":"2024-01-23T05:57:23.623978Z","shell.execute_reply":"2024-01-23T05:57:23.826139Z"},"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')","metadata":{"execution":{"iopub.status.busy":"2024-01-23T05:57:23.828606Z","iopub.execute_input":"2024-01-23T05:57:23.828884Z","iopub.status.idle":"2024-01-23T05:57:25.761599Z","shell.execute_reply.started":"2024-01-23T05:57:23.828859Z","shell.execute_reply":"2024-01-23T05:57:25.760518Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}