{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceType":"competition","sourceId":14774,"databundleVersionId":875431}],"dockerImageVersionId":31287,"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":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nos.listdir('/kaggle/input')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-23T14:32:54.077727Z","iopub.execute_input":"2026-03-23T14:32:54.078736Z","iopub.status.idle":"2026-03-23T14:32:54.084674Z","shell.execute_reply.started":"2026-03-23T14:32:54.078695Z","shell.execute_reply":"2026-03-23T14:32:54.083907Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport os\nimport cv2\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\n\nfrom tensorflow.keras.applications import DenseNet121\nfrom tensorflow.keras.layers import Dense, GlobalAveragePooling2D, Dropout\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.optimizers import Adam\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix, classification_report, accuracy_score\n\nimport seaborn as sns\nfrom PIL import Image","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nos.listdir('/kaggle/input/competitions')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-23T14:33:35.243799Z","iopub.execute_input":"2026-03-23T14:33:35.244768Z","iopub.status.idle":"2026-03-23T14:33:35.249747Z","shell.execute_reply.started":"2026-03-23T14:33:35.244735Z","shell.execute_reply":"2026-03-23T14:33:35.249194Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"os.listdir('/kaggle/input/competitions/aptos2019-blindness-detection')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-23T14:33:36.917810Z","iopub.execute_input":"2026-03-23T14:33:36.918518Z","iopub.status.idle":"2026-03-23T14:33:36.923556Z","shell.execute_reply.started":"2026-03-23T14:33:36.918487Z","shell.execute_reply":"2026-03-23T14:33:36.922795Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\n\n\ntrain_path = '/kaggle/input/competitions/aptos2019-blindness-detection/train.csv'\ntest_path = '/kaggle/input/competitions/aptos2019-blindness-detection/test.csv'\n\n# تحميل البيانات\ntrain_df = pd.read_csv(train_path)\ntest_df = pd.read_csv(test_path)\n\n\nprint(\"Status: Success! ✅\")\nprint(f\"Train data shape: {train_df.shape}\")\nprint(f\"Test data shape: {test_df.shape}\")\n\n# عرض أول 5 أسطر\ntrain_df.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-23T14:34:10.959552Z","iopub.execute_input":"2026-03-23T14:34:10.960164Z","iopub.status.idle":"2026-03-23T14:34:11.010321Z","shell.execute_reply.started":"2026-03-23T14:34:10.960094Z","shell.execute_reply":"2026-03-23T14:34:11.009649Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"IMG_SIZE = 224\n\ndef preprocess_image(path):\n    img = Image.open(path)\n    img = img.resize((IMG_SIZE, IMG_SIZE))\n    img = np.array(img)\n    return img","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-23T14:34:16.763476Z","iopub.execute_input":"2026-03-23T14:34:16.763919Z","iopub.status.idle":"2026-03-23T14:34:16.768722Z","shell.execute_reply.started":"2026-03-23T14:34:16.763888Z","shell.execute_reply":"2026-03-23T14:34:16.767885Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\n\nN = train_df.shape[0]\n\n\nx = np.empty((N, 224, 224, 3), dtype=np.uint8)\n\nfor i, img_id in enumerate(train_df['id_code']):\n    \n    path = f\"/kaggle/input/competitions/aptos2019-blindness-detection/train_images/{img_id}.png\"\n    \n   \n    x[i] = preprocess_image(path)\n\ny = train_df['diagnosis'].values\n\nprint(f\"The {len(x)} image has been successfully loaded and processed!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-23T14:34:49.683826Z","iopub.execute_input":"2026-03-23T14:34:49.684665Z","iopub.status.idle":"2026-03-23T14:43:05.382159Z","shell.execute_reply.started":"2026-03-23T14:34:49.684621Z","shell.execute_reply":"2026-03-23T14:43:05.381367Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"x_train, x_val, y_train, y_val = train_test_split(\n    x, y,\n    test_size=0.2,\n    random_state=42\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-23T14:44:14.758575Z","iopub.execute_input":"2026-03-23T14:44:14.758951Z","iopub.status.idle":"2026-03-23T14:44:14.935711Z","shell.execute_reply.started":"2026-03-23T14:44:14.758923Z","shell.execute_reply":"2026-03-23T14:44:14.934737Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"base_model = DenseNet121(\n    weights='imagenet',\n    include_top=False,\n    input_shape=(224, 224, 3)\n)\n\n# 🔹 Freeze all layers first\nfor layer in base_model.layers:\n    layer.trainable = False\n\n# 🔹 Unfreeze last 45 layers\nfor layer in base_model.layers[-45:]:\n    layer.trainable = True\n\n\n# Custom head\nx = base_model.output\nx = GlobalAveragePooling2D()(x)\n\nx = Dropout(0.5)(x)   # reduced from 0.7 (better)\nx = Dense(512, activation='relu')(x)\nx = Dropout(0.5)(x)\n\npredictions = Dense(5, activation='softmax')(x)\n\nmodel = Model(inputs=base_model.input, outputs=predictions)\n\n\n# Compile\nmodel.compile(\n    optimizer=Adam(learning_rate=5e-5),\n    loss='sparse_categorical_crossentropy',\n    metrics=['accuracy']\n)\n\nmodel.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-23T15:00:21.510629Z","iopub.execute_input":"2026-03-23T15:00:21.511144Z","iopub.status.idle":"2026-03-23T15:00:23.543012Z","shell.execute_reply.started":"2026-03-23T15:00:21.511080Z","shell.execute_reply":"2026-03-23T15:00:23.542298Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\nearly_stop = tf.keras.callbacks.EarlyStopping(\n    monitor='val_loss', \n    patience=5,            \n    restore_best_weights=True \n)\n\n\nhistory = model.fit(\n    x_train, \n    y_train,\n    validation_data=(x_val, y_val),\n    epochs=20,\n    batch_size=16,\n    callbacks=[early_stop],\n    verbose=1\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-23T15:06:27.426962Z","iopub.execute_input":"2026-03-23T15:06:27.427622Z","iopub.status.idle":"2026-03-23T15:09:05.517251Z","shell.execute_reply.started":"2026-03-23T15:06:27.427594Z","shell.execute_reply":"2026-03-23T15:09:05.516561Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.save(\"/kaggle/working/detection_model.keras\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-23T15:11:14.798098Z","iopub.execute_input":"2026-03-23T15:11:14.798474Z","iopub.status.idle":"2026-03-23T15:11:15.903861Z","shell.execute_reply.started":"2026-03-23T15:11:14.798445Z","shell.execute_reply":"2026-03-23T15:11:15.903218Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n\nplt.figure(figsize=(16, 6))\n\n# 1. (Accuracy)\nplt.subplot(1, 2, 1)\nplt.plot(history.history['accuracy'], label='Train Accuracy', marker='o')\nplt.plot(history.history['val_accuracy'], label='Valid Accuracy', marker='o')\nplt.title('Model Accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(loc='lower right')\nplt.grid(True)\n\n# 2.  (Loss)\nplt.subplot(1, 2, 2)\nplt.plot(history.history['loss'], label='Train Loss', marker='o')\nplt.plot(history.history['val_loss'], label='Valid Loss', marker='o')\nplt.title('Model Loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(loc='upper right')\nplt.grid(True)\n\nplt.savefig('/kaggle/working/training_plot.png', dpi=300, bbox_inches='tight')\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-23T15:11:52.583644Z","iopub.execute_input":"2026-03-23T15:11:52.583943Z","iopub.status.idle":"2026-03-23T15:11:53.542279Z","shell.execute_reply.started":"2026-03-23T15:11:52.583920Z","shell.execute_reply":"2026-03-23T15:11:53.541623Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.metrics import confusion_matrix, classification_report, f1_score\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n\ny_pred = model.predict(x_val)\ny_pred_classes = np.argmax(y_pred, axis=1)\n\n\ncm = confusion_matrix(y_val, y_pred_classes)\n\n\nplt.figure(figsize=(10, 8))\nsns.heatmap(cm, annot=True, fmt='d', cmap='Blues', \n            xticklabels=['Normal', 'Mild', 'Moderate', 'Severe', 'Proliferative'],\n            yticklabels=['Normal', 'Mild', 'Moderate', 'Severe', 'Proliferative'])\nplt.title('Confusion Matrix')\nplt.ylabel('Actual Label (الحقيقة)')\nplt.xlabel('Predicted Label')\nplt.show()\n\n\n\nplt.savefig('/kaggle/working/training_plot.png', dpi=300, bbox_inches='tight')\nprint(\"\\n--- Classification Report ---\")\nprint(classification_report(y_val, y_pred_classes, \n                            target_names=['Normal', 'Mild', 'Moderate', 'Severe', 'Proliferative']))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-23T15:09:29.679775Z","iopub.execute_input":"2026-03-23T15:09:29.680442Z","iopub.status.idle":"2026-03-23T15:09:53.342840Z","shell.execute_reply.started":"2026-03-23T15:09:29.680413Z","shell.execute_reply":"2026-03-23T15:09:53.341904Z"}},"outputs":[],"execution_count":null}]}