{"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,"isSourceIdPinned":false}],"dockerImageVersionId":31286,"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,"execution":{"iopub.status.busy":"2026-03-16T09:26:57.427619Z","iopub.execute_input":"2026-03-16T09:26:57.427846Z","iopub.status.idle":"2026-03-16T09:27:56.034616Z","shell.execute_reply.started":"2026-03-16T09:26:57.427824Z","shell.execute_reply":"2026-03-16T09:27:56.033976Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nos.listdir('/kaggle/input')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-16T09:27:56.036138Z","iopub.execute_input":"2026-03-16T09:27:56.036489Z","iopub.status.idle":"2026-03-16T09:27:56.042046Z","shell.execute_reply.started":"2026-03-16T09:27:56.036467Z","shell.execute_reply":"2026-03-16T09:27:56.041445Z"}},"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,"execution":{"iopub.status.busy":"2026-03-16T09:27:56.042917Z","iopub.execute_input":"2026-03-16T09:27:56.043465Z","iopub.status.idle":"2026-03-16T09:28:21.653479Z","shell.execute_reply.started":"2026-03-16T09:27:56.043442Z","shell.execute_reply":"2026-03-16T09:28:21.652862Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nos.listdir('/kaggle/input/competitions')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-16T09:28:21.654353Z","iopub.execute_input":"2026-03-16T09:28:21.654911Z","iopub.status.idle":"2026-03-16T09:28:21.660215Z","shell.execute_reply.started":"2026-03-16T09:28:21.654884Z","shell.execute_reply":"2026-03-16T09:28:21.659371Z"}},"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-16T09:28:21.661201Z","iopub.execute_input":"2026-03-16T09:28:21.661503Z","iopub.status.idle":"2026-03-16T09:28:21.676573Z","shell.execute_reply.started":"2026-03-16T09:28:21.661480Z","shell.execute_reply":"2026-03-16T09:28:21.675982Z"}},"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,"execution":{"iopub.status.busy":"2026-03-16T09:28:21.677581Z","iopub.execute_input":"2026-03-16T09:28:21.677982Z","iopub.status.idle":"2026-03-16T09:28:24.347527Z","shell.execute_reply.started":"2026-03-16T09:28:21.677962Z","shell.execute_reply":"2026-03-16T09:28:24.346795Z"}},"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-16T09:28:24.350010Z","iopub.execute_input":"2026-03-16T09:28:24.350422Z","iopub.status.idle":"2026-03-16T09:28:24.394169Z","shell.execute_reply.started":"2026-03-16T09:28:24.350401Z","shell.execute_reply":"2026-03-16T09:28:24.393552Z"}},"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-16T09:28:24.394991Z","iopub.execute_input":"2026-03-16T09:28:24.395261Z","iopub.status.idle":"2026-03-16T09:28:24.399195Z","shell.execute_reply.started":"2026-03-16T09:28:24.395234Z","shell.execute_reply":"2026-03-16T09:28:24.398599Z"}},"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\"تم تحميل ومعالجة {len(x)} صورة بنجاح!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-16T09:28:24.400220Z","iopub.execute_input":"2026-03-16T09:28:24.400589Z","iopub.status.idle":"2026-03-16T09:37:52.853105Z","shell.execute_reply.started":"2026-03-16T09:28:24.400554Z","shell.execute_reply":"2026-03-16T09:37:52.852373Z"}},"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-16T09:37:52.854113Z","iopub.execute_input":"2026-03-16T09:37:52.854349Z","iopub.status.idle":"2026-03-16T09:37:53.021209Z","shell.execute_reply.started":"2026-03-16T09:37:52.854327Z","shell.execute_reply":"2026-03-16T09:37:53.020549Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.layers import Dense, GlobalAveragePooling2D, Dropout, BatchNormalization\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.optimizers import Adam\nimport tensorflow as tf\n\n\nbase_model = DenseNet121(\n    weights='imagenet',\n    include_top=False,\n    input_shape=(224, 224, 3)\n)\n\nx = base_model.output\nx = GlobalAveragePooling2D()(x)\n\n\nx = Dropout(0.7)(x) \n\n\nx = Dense(512, activation='relu')(x)\nx = Dropout(0.5)(x)\n\npredictions = Dense(5, activation='softmax')(x)\nmodel = Model(inputs=base_model.input, outputs=predictions)\n\n\nmodel.compile(\n    optimizer=Adam(learning_rate=0.00005), \n    loss='sparse_categorical_crossentropy',\n    metrics=['accuracy']\n)\nmodel.summary()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-16T09:37:53.022209Z","iopub.execute_input":"2026-03-16T09:37:53.022439Z","iopub.status.idle":"2026-03-16T09:37:57.802514Z","shell.execute_reply.started":"2026-03-16T09:37:53.022418Z","shell.execute_reply":"2026-03-16T09:37:57.801964Z"}},"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=15,\n    batch_size=32,\n    callbacks=[early_stop]\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-16T09:37:57.803505Z","iopub.execute_input":"2026-03-16T09:37:57.803813Z","iopub.status.idle":"2026-03-16T09:46:08.150255Z","shell.execute_reply.started":"2026-03-16T09:37:57.803790Z","shell.execute_reply":"2026-03-16T09:46:08.149526Z"}},"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.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-16T09:46:08.151138Z","iopub.execute_input":"2026-03-16T09:46:08.151348Z","iopub.status.idle":"2026-03-16T09:46:08.443756Z","shell.execute_reply.started":"2026-03-16T09:46:08.151328Z","shell.execute_reply":"2026-03-16T09:46:08.443017Z"}},"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# 1. استخراج التوقعات لبيانات التحقق (Validation)\ny_pred = model.predict(x_val)\ny_pred_classes = np.argmax(y_pred, axis=1)\n\n# 2. إنشاء مصفوفة الارتباك\ncm = confusion_matrix(y_val, y_pred_classes)\n\n# 3. رسم المصفوفة بشكل احترافي\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# 4. طباعة تقرير التقييمات الكامل\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-16T09:46:08.444809Z","iopub.execute_input":"2026-03-16T09:46:08.445144Z","iopub.status.idle":"2026-03-16T09:46:32.304457Z","shell.execute_reply.started":"2026-03-16T09:46:08.445113Z","shell.execute_reply":"2026-03-16T09:46:32.303876Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"N_test = test_df.shape[0]\n\nx_test = np.empty((N_test,224,224,3),dtype=np.uint8)\n\nfor i,img_id in enumerate(test_df['id_code']):\n    \n    path=f\"/kaggle/input/competitions/aptos2019-blindness-detection/test_images/{img_id}.png\"\n    \n    x_test[i]=preprocess_image(path)\n\nprint(\"تم تحميل صور test بنجاح\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-16T09:46:32.305877Z","iopub.execute_input":"2026-03-16T09:46:32.306127Z","iopub.status.idle":"2026-03-16T09:48:23.629766Z","shell.execute_reply.started":"2026-03-16T09:46:32.306104Z","shell.execute_reply":"2026-03-16T09:48:23.629110Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y_test_pred=model.predict(x_test)\n\ny_test_classes=np.argmax(y_test_pred,axis=1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-16T09:48:23.630808Z","iopub.execute_input":"2026-03-16T09:48:23.631087Z","iopub.status.idle":"2026-03-16T09:48:37.126751Z","shell.execute_reply.started":"2026-03-16T09:48:23.631061Z","shell.execute_reply":"2026-03-16T09:48:37.126107Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_df['predicted_diagnosis'] = y_test_classes\n\ntest_df.head(10)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-16T09:49:54.240847Z","iopub.execute_input":"2026-03-16T09:49:54.241661Z","iopub.status.idle":"2026-03-16T09:49:54.250213Z","shell.execute_reply.started":"2026-03-16T09:49:54.241630Z","shell.execute_reply":"2026-03-16T09:49:54.249508Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for i in range(10):\n    print(\"Image:\", test_df['id_code'][i],\n          \"Prediction:\", y_test_classes[i])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-16T09:51:51.278510Z","iopub.execute_input":"2026-03-16T09:51:51.278969Z","iopub.status.idle":"2026-03-16T09:51:51.283996Z","shell.execute_reply.started":"2026-03-16T09:51:51.278940Z","shell.execute_reply":"2026-03-16T09:51:51.283306Z"}},"outputs":[],"execution_count":null}]}