{"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":"none","dataSources":[{"sourceType":"competition","sourceId":14774,"databundleVersionId":875431}],"dockerImageVersionId":31286,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"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 EfficientNetB4         \nfrom tensorflow.keras.applications.efficientnet import preprocess_input  \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\n\nprint(\"✅ All libraries imported successfully!\")\nprint(f\"TensorFlow version: {tf.__version__}\")","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2026-03-17T20:04:37.245953Z","iopub.execute_input":"2026-03-17T20:04:37.246612Z","iopub.status.idle":"2026-03-17T20:04:37.252522Z","shell.execute_reply.started":"2026-03-17T20:04:37.246581Z","shell.execute_reply":"2026-03-17T20:04:37.251835Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\n\ntrain_path = '/kaggle/input/competitions/aptos2019-blindness-detection/train.csv'\ntest_path  = '/kaggle/input/competitions/aptos2019-blindness-detection/test.csv'\n\ntrain_df = pd.read_csv(train_path)\ntest_df  = pd.read_csv(test_path)\n\nprint(\"Status: Success! ✅\")\nprint(f\"Train data shape: {train_df.shape}\")\nprint(f\"Test data shape : {test_df.shape}\")\n\ntrain_df.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-17T20:04:41.826113Z","iopub.execute_input":"2026-03-17T20:04:41.826407Z","iopub.status.idle":"2026-03-17T20:04:41.845540Z","shell.execute_reply.started":"2026-03-17T20:04:41.826382Z","shell.execute_reply":"2026-03-17T20:04:41.844809Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"IMG_SIZE = 260\n\ndef preprocess_image(path):\n    img = Image.open(path)\n    img = img.resize((IMG_SIZE, IMG_SIZE))\n    img = np.array(img, dtype=np.float32)\n    img = preprocess_input(img)\n    return img","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-17T20:04:45.946387Z","iopub.execute_input":"2026-03-17T20:04:45.947125Z","iopub.status.idle":"2026-03-17T20:04:45.951427Z","shell.execute_reply.started":"2026-03-17T20:04:45.947095Z","shell.execute_reply":"2026-03-17T20:04:45.950651Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\n\nN = train_df.shape[0]\n\nx = np.empty((N, 260, 260, 3), dtype=np.float32)\n\nfor i, img_id in enumerate(train_df['id_code']):\n    path = f\"/kaggle/input/competitions/aptos2019-blindness-detection/train_images/{img_id}.png\"\n    x[i] = preprocess_image(path)\n\ny = train_df['diagnosis'].values\n\nprint(f\"✅ Loaded {len(x)} images!\")\nprint(f\"   x shape: {x.shape}\")\nprint(f\"   Label distribution: {dict(zip(*np.unique(y, return_counts=True)))}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-17T20:04:52.976590Z","iopub.execute_input":"2026-03-17T20:04:52.976926Z","iopub.status.idle":"2026-03-17T20:12:12.186350Z","shell.execute_reply.started":"2026-03-17T20:04:52.976897Z","shell.execute_reply":"2026-03-17T20:12:12.185614Z"}},"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)\n\nprint(f\"✅ Data split complete!\")\nprint(f\"   Training   samples: {x_train.shape[0]}\")\nprint(f\"   Validation samples: {x_val.shape[0]}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-17T20:12:45.201627Z","iopub.execute_input":"2026-03-17T20:12:45.201963Z","iopub.status.idle":"2026-03-17T20:12:47.888029Z","shell.execute_reply.started":"2026-03-17T20:12:45.201938Z","shell.execute_reply":"2026-03-17T20:12:47.883675Z"}},"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\nbase_model = EfficientNetB4(\n    weights='imagenet',\n    include_top=False,\n    input_shape=(260, 260, 3)   \n)\n\nx = base_model.output\nx = GlobalAveragePooling2D()(x)\n\nx = Dropout(0.7)(x)\n\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\nmodel.compile(\n    optimizer=Adam(learning_rate=0.00005),\n    loss='sparse_categorical_crossentropy',\n    metrics=['accuracy']\n)\n\nmodel.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-17T20:13:07.437333Z","iopub.execute_input":"2026-03-17T20:13:07.437663Z","iopub.status.idle":"2026-03-17T20:13:10.066081Z","shell.execute_reply.started":"2026-03-17T20:13:07.437627Z","shell.execute_reply":"2026-03-17T20:13:10.065461Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"tf.keras.mixed_precision.set_global_policy('mixed_float16')\n\nearly_stop = tf.keras.callbacks.EarlyStopping(\n    monitor='val_loss',\n    patience=5,\n    restore_best_weights=True\n)\n\nhistory = model.fit(\n    x_train,\n    y_train,\n    validation_data=(x_val, y_val),\n    epochs=15,\n    batch_size=8,       \n    callbacks=[early_stop]\n)\n\nprint(\"\\n✅ Training complete!\")\nprint(f\"   Stopped at epoch: {len(history.history['loss'])}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-17T20:13:25.551088Z","iopub.execute_input":"2026-03-17T20:13:25.551401Z","iopub.status.idle":"2026-03-17T20:25:00.991448Z","shell.execute_reply.started":"2026-03-17T20:13:25.551376Z","shell.execute_reply":"2026-03-17T20:25:00.990813Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\nplt.figure(figsize=(16, 6))\n\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\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.suptitle('EfficientNetB4 Training History', fontsize=14, fontweight='bold')\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-17T20:25:07.711440Z","iopub.execute_input":"2026-03-17T20:25:07.711962Z","iopub.status.idle":"2026-03-17T20:25:08.116175Z","shell.execute_reply.started":"2026-03-17T20:25:07.711931Z","shell.execute_reply":"2026-03-17T20:25:08.115544Z"}},"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\nCLASS_NAMES = ['Normal', 'Mild', 'Moderate', 'Severe', 'Proliferative']\n\ny_pred         = model.predict(x_val)\ny_pred_classes = np.argmax(y_pred, axis=1)\n\ncm = confusion_matrix(y_val, y_pred_classes)\n\nplt.figure(figsize=(10, 8))\nsns.heatmap(\n    cm,\n    annot=True,\n    fmt='d',\n    cmap='Blues',\n    xticklabels=CLASS_NAMES,\n    yticklabels=CLASS_NAMES\n)\nplt.title('Confusion Matrix — Validation Set', fontsize=14, fontweight='bold')\nplt.ylabel('Actual Label')\nplt.xlabel('Predicted Label')\nplt.tight_layout()\nplt.show()\n\nprint(\"\\n--- Classification Report (Validation Set) ---\")\nprint(classification_report(y_val, y_pred_classes, target_names=CLASS_NAMES))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-17T20:25:31.658440Z","iopub.execute_input":"2026-03-17T20:25:31.659216Z","iopub.status.idle":"2026-03-17T20:26:19.339377Z","shell.execute_reply.started":"2026-03-17T20:25:31.659187Z","shell.execute_reply":"2026-03-17T20:26:19.338741Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"N_test = test_df.shape[0]\n\nx_test = np.empty((N_test, 260, 260, 3), dtype=np.float32)\n\nfor i, img_id in enumerate(test_df['id_code']):\n    path = f\"/kaggle/input/competitions/aptos2019-blindness-detection/test_images/{img_id}.png\"\n    x_test[i] = preprocess_image(path)\n\nprint(f\"✅ Loaded {N_test} test images!\")\nprint(f\"   x_test shape: {x_test.shape}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-17T20:26:28.458035Z","iopub.execute_input":"2026-03-17T20:26:28.458331Z","iopub.status.idle":"2026-03-17T20:28:06.777232Z","shell.execute_reply.started":"2026-03-17T20:26:28.458309Z","shell.execute_reply":"2026-03-17T20:28:06.776529Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y_test_pred    = model.predict(x_test)\ny_test_classes = np.argmax(y_test_pred, axis=1)\n\nprint(f\"✅ Inference complete!\")\nprint(f\"   Predictions shape      : {y_test_pred.shape}\")\nprint(f\"   Unique classes predicted: {np.unique(y_test_classes)}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-17T20:28:30.142265Z","iopub.execute_input":"2026-03-17T20:28:30.142596Z","iopub.status.idle":"2026-03-17T20:28:49.379900Z","shell.execute_reply.started":"2026-03-17T20:28:30.142569Z","shell.execute_reply":"2026-03-17T20:28:49.379145Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_df['predicted_diagnosis'] = y_test_classes\n\nprint(\"✅ Predictions added to test_df!\")\nprint(f\"   Distribution: {dict(zip(*np.unique(y_test_classes, return_counts=True)))}\")\n\ntest_df.head(10)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-17T20:28:53.508134Z","iopub.execute_input":"2026-03-17T20:28:53.508866Z","iopub.status.idle":"2026-03-17T20:28:53.518120Z","shell.execute_reply.started":"2026-03-17T20:28:53.508837Z","shell.execute_reply":"2026-03-17T20:28:53.517391Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"CLASS_NAMES = ['Normal', 'Mild', 'Moderate', 'Severe', 'Proliferative']\n\nprint(\"Sample Predictions (first 10 test images):\")\nprint(\"-\" * 50)\nfor i in range(10):\n    img_id     = test_df['id_code'][i]\n    pred_label = y_test_classes[i]\n    pred_name  = CLASS_NAMES[pred_label]\n    print(f\"Image: {img_id}  →  Prediction: {pred_label} ({pred_name})\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-17T20:28:58.373651Z","iopub.execute_input":"2026-03-17T20:28:58.373958Z","iopub.status.idle":"2026-03-17T20:28:58.379477Z","shell.execute_reply.started":"2026-03-17T20:28:58.373934Z","shell.execute_reply":"2026-03-17T20:28:58.378697Z"}},"outputs":[],"execution_count":null}]}