{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.11","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":14774,"databundleVersionId":875431,"sourceType":"competition"}],"dockerImageVersionId":31011,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-21T05:25:30.325752Z","iopub.execute_input":"2025-04-21T05:25:30.325945Z","iopub.status.idle":"2025-04-21T05:25:41.150386Z","shell.execute_reply.started":"2025-04-21T05:25:30.325929Z","shell.execute_reply":"2025-04-21T05:25:41.149551Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\nimport os\nimport random\nimport warnings\nimport cv2 as cv\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom tensorflow import keras\nfrom tensorflow.keras import Sequential\nfrom tensorflow.keras.losses import SparseCategoricalCrossentropy\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import confusion_matrix,ConfusionMatrixDisplay\nfrom tensorflow.keras.optimizers import Adam\n\n# Added for InceptionV3 \nfrom tensorflow.keras.applications import InceptionV3\nfrom tensorflow.keras.applications.inception_v3 import preprocess_input\nfrom tensorflow.keras.layers import GlobalAveragePooling2D, Dense, Dropout\nfrom tensorflow.keras.models import Model\\\n\n# Set seed for reproducibility \nSEED = 42\nnp.random.seed(SEED)\nrandom.seed(SEED)\nimport tensorflow as tf\ntf.random.set_seed(SEED)\n\n\nwarnings.filterwarnings(\"ignore\")\nsns.set_style(style=\"darkgrid\")\n\ndef apply_clahe_lab(img):\n    lab = cv.cvtColor(img, cv.COLOR_BGR2LAB)\n    l, a, b = cv.split(lab)\n    clahe = cv.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))\n    cl = clahe.apply(l)\n    limg = cv.merge((cl, a, b))\n    final = cv.cvtColor(limg, cv.COLOR_LAB2BGR)\n    return final\n\n\n# **Read Data**\"\"\"\n\ndf = pd.read_csv(\"/kaggle/input/aptos2019-blindness-detection/train.csv\")\nprint(df.shape)\ndf.head()\n\n## Data consist of two columns, first column have name of image and second column have classify of diagnosis of image**\n\n\n## **Visualize Distribution**\n\n\ndata = df.replace({\"diagnosis\":{0:\"No DR\",1:\"Mild\",2:\"Moderate\",3:\"Severe\",4:\"Proliferative DR\"}})\ndiagnosis_count = data.diagnosis.value_counts()\nsns.countplot(data=data,x=\"diagnosis\",order=diagnosis_count.index)\nplt.xlabel(\"Diagnosis\",weight=\"bold\",size=15)\nplt.ylabel(\"Freq\",weight=\"bold\",size=15)\nfor i,v in enumerate(diagnosis_count.values,0):\n    text = f\"{v*100/len(data):0.2f}%\"\n    plt.text(s=text,x=i,y=v+10,ha=\"center\",weight=\"bold\")\nplt.show()\ndel data\n\n\n## **Read Image & preprocessing**\n\nX = []\ny = []\nfor target in range(5):\n    for image in df[df[\"diagnosis\"] == target][\"id_code\"]:\n        path = os.path.join(\"/kaggle/input/aptos2019-blindness-detection/train_images\", f\"{image}.png\")\n        img = cv.imread(path, 1)\n        img = apply_clahe_lab(img)  # Apply CLAHE before resizing\n        img = cv.resize(img, (299, 299))  # Resize after enhancement\n        img = preprocess_input(img)  \n        X.append(img)\n        y.append(target)\n        if target in (3, 4):\n            flipped = cv.flip(img, 1)\n            X.append(flipped)\n            y.append(target)\n\nX = np.asarray(X)\ny = np.asarray(y)\n\ndata = pd.Series(y)\ndata = data.replace({0:\"No DR\",1:\"Mild\",2:\"Moderate\",3:\"Severe\",4:\"Proliferative DR\"})\ndiagnosis_count = data.value_counts()\nsns.countplot(x=data,order=diagnosis_count.index)\nplt.xlabel(\"Diagnosis\",weight=\"bold\",size=15)\nplt.ylabel(\"Freq\",weight=\"bold\",size=15)\nfor i,v in enumerate(diagnosis_count.values,0):\n    text = f\"{v*100/len(data):0.2f}%\"\n    plt.text(s=text,x=i,y=v+10,ha=\"center\",weight=\"bold\")\nplt.show()\ndel data\n\n## **Splitting**\"\"\"\n\nx_train,x_test,y_train,y_test = train_test_split(X,y,test_size=0.3,random_state=0,shuffle=True)\nx_test,x_val,y_test,y_val = train_test_split(x_test,y_test,test_size=0.5,random_state=0,shuffle=True)\ndel X,y\n\n# Print dataset\nprint(\"after increasing data of class 3,4\")\nprint(f\"Total samples: {len(x_train) + len(x_val) + len(x_test)}\")  # ✅ Added total count\nprint(f\"Training samples: {len(x_train)}\")\nprint(f\"Validation samples: {len(x_val)}\")\nprint(f\"Test samples: {len(x_test)}\")\n\n\n\n","metadata":{"_uuid":"ba0e7c43-cf5f-47dc-ad0d-ff33ce94de1f","_cell_guid":"8b318437-26fd-4826-ab03-88311f76d3ea","trusted":true,"collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2025-04-21T05:25:41.152142Z","iopub.execute_input":"2025-04-21T05:25:41.152407Z","iopub.status.idle":"2025-04-21T05:35:20.928711Z","shell.execute_reply.started":"2025-04-21T05:25:41.152388Z","shell.execute_reply":"2025-04-21T05:35:20.927858Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# **Workin On Model**\n\n## **Building Model**\n\n\n# Replaced custom CNN with InceptionV3\nbase_model = InceptionV3(include_top=False, weights='imagenet', input_shape=(299, 299, 3))\n\n# Freeze base model (optional: change to True for fine-tuning)\nbase_model.trainable = False\n\nx = base_model.output\nx = GlobalAveragePooling2D()(x)\nx = Dropout(0.5)(x)\nx = Dense(256, activation='relu')(x)\nx = Dense(5, activation='softmax')(x)\n\nmodel = Model(inputs=base_model.input, outputs=x)\n\nmodel.compile(optimizer=Adam(learning_rate=1e-4),\n              loss=SparseCategoricalCrossentropy(),\n              metrics=[\"accuracy\"])\n\n# Summary for model\nmodel.summary()\n\n# model.add(keras.layers.BatchNormalization())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-21T05:35:20.929590Z","iopub.execute_input":"2025-04-21T05:35:20.929883Z","iopub.status.idle":"2025-04-21T05:35:23.292391Z","shell.execute_reply.started":"2025-04-21T05:35:20.929857Z","shell.execute_reply":"2025-04-21T05:35:23.291681Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\ndatagen = ImageDataGenerator(\n    rotation_range=360,\n    \n    horizontal_flip=True,\n    fill_mode='nearest'\n)\n\n\n## **Model Training**\"\"\"\n\nes = EarlyStopping(monitor='val_accuracy',\n                   mode=\"max\",\n                   verbose=1,\n                   patience=6,\n                   restore_best_weights=True)\n\n\nhistory = model.fit(\n    datagen.flow(x_train, y_train, batch_size=64),\n    epochs=25,\n    validation_data=(x_val, y_val),\n    callbacks=[es]\n)\n\n\nplt.figure(figsize=(13,5))\nplt.subplot(1,2,1)\nplt.title(\"Accuracy\")\nplt.plot(history.history[\"val_accuracy\"],label=\"val accuracy\")\nplt.plot(history.history[\"accuracy\"],label=\"accuracy\")\nplt.legend()\nplt.subplot(1,2,2)\nplt.title(\"Loss\")\nplt.plot(history.history[\"val_loss\"],label=\"val loss\")\nplt.plot(history.history[\"loss\"],label=\"loss\")\nplt.legend()\nplt.show()\n\n## **Model Evaluation**\"\"\"\n\ny_predicted = model.predict(x_test)\ny_predicted = np.argmax(y_predicted,axis=1)\ncm = confusion_matrix(y_test,y_predicted)\ncmd = ConfusionMatrixDisplay(confusion_matrix = cm, display_labels = [\"No DR\",\"Mild\",\"Moderate\",\"Severe\",\"Proliferative DR\"])\ncmd.plot(cmap=plt.cm.Blues, values_format='d',xticks_rotation=\"vertical\")\nplt.show()\n\nacc = accuracy_score(y_test,y_predicted)\nprint(f\"Test score: {acc*100:.2f}\")\n\n## **Random Test**\"\"\"\n\ndecode = {0:\"No DR\",1:\"Mild\",2:\"Moderate\",3:\"Severe\",4:\"Proliferative DR\"}\nplt.figure(figsize=(15,5))\nfor i,test in enumerate(np.random.randint(0,len(df)-1,8),1):\n    plt.subplot(2,4,i)\n    image = df.loc[test,\"id_code\"]\n    path = os.path.join(\"/kaggle/input/aptos2019-blindness-detection/train_images\",f\"{image}.png\")\n    img = cv.imread(path,1)\n    img = cv.resize(img, (299, 299))  # Resize after enhancement\n        \n    plt.imshow(cv.cvtColor(img,cv.COLOR_BGR2RGB))\n    \n    img = preprocess_input(img)\n    img = np.expand_dims(img,axis=0)\n    res = model.predict(img)\n    res = f\"Prediction is {decode[np.argmax(res)]}\"\n    true = f\"Real is {decode[df.loc[test,'diagnosis']]}\"\n    plt.axis(\"off\")\n    plt.text(x=10,y=20,s=true,color=\"Blue\",weight=\"bold\",backgroundcolor=\"Gray\",size=8)\n    plt.text(x=10,y=215,s=res,color=\"Blue\",weight=\"bold\",backgroundcolor=\"Gray\",size=8)\nplt.show()\n\n## **Save Model**\"\"\"\n\nmodel.save(\"Blind_DetectionV1.keras\")\n\ndel x_train,x_test,x_val,y_train,y_test,y_val,history,df","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-21T05:35:23.293201Z","iopub.execute_input":"2025-04-21T05:35:23.293407Z","iopub.status.idle":"2025-04-21T05:54:53.961481Z","shell.execute_reply.started":"2025-04-21T05:35:23.293391Z","shell.execute_reply":"2025-04-21T05:54:53.960889Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# **Submit file**\"\"\"\n\ndf2 = pd.read_csv(\"/kaggle/input/aptos2019-blindness-detection/test.csv\")\ndf2.head()\n\ndiagnosis = []\nfor j,i in enumerate(df2[\"id_code\"],1):\n    path=os.path.join(\"/kaggle/input/aptos2019-blindness-detection/test_images\",f\"{i}.png\")\n    img = cv.imread(path,1)\n    img = apply_clahe_lab(img)\n    img = cv.resize(img,(299,299))\n    img = preprocess_input(img)\n    diagnosis.append(img)\n    if j%500==0:\n        print(\"Done of 500 images\")\ndiagnosis = np.asarray(diagnosis)\n\ndiagnosis = model.predict(diagnosis)\ndiagnosis = np.argmax(diagnosis,axis=1)\ndf2[\"diagnosis\"]=diagnosis\ndf2.head()\n\ndf2.to_csv(path_or_buf=\"submission.csv\",index=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-21T05:55:49.392253Z","iopub.execute_input":"2025-04-21T05:55:49.393154Z","iopub.status.idle":"2025-04-21T05:58:09.398449Z","shell.execute_reply.started":"2025-04-21T05:55:49.393127Z","shell.execute_reply":"2025-04-21T05:58:09.397832Z"}},"outputs":[],"execution_count":null}]}