{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":59093,"databundleVersionId":7469972,"sourceType":"competition"}],"dockerImageVersionId":31090,"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\n#import os\n#for 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":"2025-08-13T13:41:03.316449Z","iopub.execute_input":"2025-08-13T13:41:03.316750Z","iopub.status.idle":"2025-08-13T13:41:03.567320Z","shell.execute_reply.started":"2025-08-13T13:41:03.316727Z","shell.execute_reply":"2025-08-13T13:41:03.566726Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport os\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler, LabelEncoder\nfrom sklearn.metrics import accuracy_score, classification_report, confusion_matrix\nfrom tensorflow.keras.utils import to_categorical\nimport pyarrow.parquet as pq\nimport io\nimport scipy.signal\nfrom PIL import Image\n\n# Define dataset directories\ndata_csv = \"/kaggle/input/hms-harmful-brain-activity-classification/train.csv\"\nparquet_dir = \"/kaggle/input/hms-harmful-brain-activity-classification/train_spectrograms\"\n\n# Load metadata\ndf = pd.read_csv(data_csv)\n\n# Filter rows that have corresponding parquet files\nexisting_files = set(os.listdir(parquet_dir))\ndf = df[df[\"spectrogram_id\"].apply(lambda x: f\"{x}.parquet\" in existing_files)]\n\n# Limit to first 5000 samples\ndf = df.head(5000)\n\nif df.empty:\n    raise ValueError(\"No matching parquet files found. Check your directory and filenames.\")\n\n# Encode labels\ny = df[\"expert_consensus\"].dropna()\ndf = df.loc[y.index]\nle = LabelEncoder()\ny_encoded = le.fit_transform(y)\ny_categorical = to_categorical(y_encoded)\n\n# Metadata features\nX_meta = df[['seizure_vote', 'lpd_vote', 'gpd_vote', 'lrda_vote', 'grda_vote', 'other_vote']].values\nscaler = StandardScaler()\nX_meta = scaler.fit_transform(X_meta)\n\n# Helper to convert spectrogram parquet to image array\ndef load_spectrogram_as_image(spectrogram_id, size=(224, 224)):\n    file_path = os.path.join(parquet_dir, f\"{spectrogram_id}.parquet\")\n    table = pq.read_table(file_path)\n    data = table.to_pandas().values.T  # Transpose to get (freq, time)\n    data = np.log1p(data)\n    data = (data - np.min(data)) / (np.max(data) - np.min(data))\n    img = Image.fromarray(np.uint8(data * 255)).convert(\"RGB\").resize(size)\n    return np.array(img) / 255.0\n\n# Load spectrogram images\nX_images = np.stack([load_spectrogram_as_image(sid) for sid in df[\"spectrogram_id\"]])\n\n# Split dataset\nX_img_train, X_img_temp, X_meta_train, X_meta_temp, y_train, y_temp = train_test_split(\n    X_images, X_meta, y_categorical, test_size=0.3, random_state=42, stratify=y_categorical)\nX_img_val, X_img_test, X_meta_val, X_meta_test, y_val, y_test = train_test_split(\n    X_img_temp, X_meta_temp, y_temp, test_size=0.5, random_state=42, stratify=y_temp)\n\n# Define RetNet-inspired image model \nfrom tensorflow.keras.applications import ResNet50\n\nimage_input = keras.Input(shape=(224, 224, 3), name=\"image_input\")\nx = layers.Conv2D(32, (3, 3), activation='relu', padding='same')(image_input)\nx = layers.MaxPooling2D((2, 2))(x)\nx = layers.Conv2D(64, (3, 3), activation='relu', padding='same')(x)\nx = layers.MaxPooling2D((2, 2))(x)\nx = layers.Conv2D(128, (3, 3), activation='relu', padding='same')(x)\nx = layers.GlobalAveragePooling2D()(x)\nx = layers.Dense(128, activation='relu')(x)\nimage_features = layers.Dropout(0.3)(x)\n\n# Metadata model\nmeta_input = keras.Input(shape=(X_meta.shape[1],), name=\"meta_input\")\ny_meta = layers.Dense(32, activation='relu')(meta_input)\nmeta_features = layers.Dense(16, activation='relu')(y_meta)\n\n# Merge models\nmerged = layers.concatenate([image_features, meta_features])\nz = layers.Dense(64, activation='relu')(merged)\nout = layers.Dense(y_categorical.shape[1], activation='softmax')(z)\n\nmodel = keras.Model(inputs=[image_input, meta_input], outputs=out)\nmodel.compile(optimizer=keras.optimizers.Adam(learning_rate=1e-4),\n              loss='categorical_crossentropy', metrics=['accuracy'])\n\n# Train model\nmodel.fit(\n    x=[X_img_train, X_meta_train],\n    y=y_train,\n    epochs=10,\n    batch_size=32,\n    validation_data=([X_img_val, X_meta_val], y_val)\n)\n\n# Evaluate model\ny_pred = model.predict([X_img_test, X_meta_test])\ny_pred_classes = np.argmax(y_pred, axis=1)\ny_true_classes = np.argmax(y_test, axis=1)\n\nprint(\"Test Accuracy:\", accuracy_score(y_true_classes, y_pred_classes))\nprint(\"Test Report:\\n\", classification_report(y_true_classes, y_pred_classes))\n\n# Confusion Matrix\nplt.figure(figsize=(6, 4))\nplt.imshow(confusion_matrix(y_true_classes, y_pred_classes), cmap='Blues', interpolation='nearest')\nplt.colorbar()\nplt.title(\"Confusion Matrix - Test Set\")\nplt.xlabel(\"Predicted\")\nplt.ylabel(\"True\")\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-13T13:41:04.753808Z","iopub.execute_input":"2025-08-13T13:41:04.754180Z","iopub.status.idle":"2025-08-13T13:45:53.754311Z","shell.execute_reply.started":"2025-08-13T13:41:04.754159Z","shell.execute_reply":"2025-08-13T13:45:53.753424Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install lime --quiet\n\nfrom lime import lime_image\nfrom skimage.segmentation import mark_boundaries\nimport random\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow as tf\n\n# --------------------------\n# 1. Define class name mapping\n# --------------------------\nclass_names = [\n    \"Seizure\",\n    \"LPDA\",\n    \"LPD\",\n    \"Normal\",\n    \"GPD\",\n    \"GPDA\"\n]\n\n# --------------------------\n# 2. Pick a random test image\n# --------------------------\nidx = np.random.randint(0, len(X_img_test)-1)\ntest_img = X_img_test[idx]\ntrue_label = np.argmax(y_test[idx])\nprint(f\"Explaining Test Sample Index: {idx}, True Class: {class_names[true_label]}\")\n\n# --------------------------\n# 3. LIME prediction wrapper\n# --------------------------\ndef predict_fn(images):\n    images = tf.image.resize(images, (224, 224))  # Ensure size\n    metas = np.tile(X_meta_test[idx], (images.shape[0], 1))  # Repeat metadata\n    return model.predict([images, metas])\n\n# --------------------------\n# 4. Run LIME\n# --------------------------\nexplainer = lime_image.LimeImageExplainer()\nnum_classes = model.output_shape[-1]  # Get total classes\n\nexplanation = explainer.explain_instance(\n    image=test_img,\n    classifier_fn=predict_fn,\n    top_labels=num_classes,  # Explain all classes\n    hide_color=0,\n    num_samples=1000\n)\n\n# --------------------------\n# 5. Plot results in a 2×3 grid\n# --------------------------\nfig, axes = plt.subplots(2, 3, figsize=(12, 8))\naxes = axes.flatten()\n\nfor i, label in enumerate(explanation.top_labels):\n    temp, mask = explanation.get_image_and_mask(\n        label=label,\n        positive_only=True,\n        num_features=10,\n        hide_rest=False\n    )\n\n    axes[i].imshow(mark_boundaries(temp, mask))\n    axes[i].set_title(f\"LIME - {class_names[label]}\")\n    axes[i].axis('off')\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-13T14:44:40.814246Z","iopub.execute_input":"2025-08-13T14:44:40.814542Z","iopub.status.idle":"2025-08-13T14:44:58.389117Z","shell.execute_reply.started":"2025-08-13T14:44:40.814515Z","shell.execute_reply":"2025-08-13T14:44:58.388120Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install lime --quiet\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom lime import lime_image\nfrom skimage.segmentation import mark_boundaries\nfrom skimage.color import label2rgb\n\n# --------------------------\n# Class names for 6 diseases (update order if needed)\n# --------------------------\nclass_names = [\n    \"Seizure\",\n    \"LPDA\",\n    \"LPD\",\n    \"Normal\",\n    \"GPD\",\n    \"GPDA\"\n]\n\n# Choose a random test image index\nidx = 449\ntest_img = X_img_test[idx]\ntrue_label = np.argmax(y_test[idx])\n\nprint(f\"Explaining test sample index: {idx}, True class: {class_names[true_label]}\")\n\n# Define classifier function for LIME (resizes + adds metadata)\ndef predict_fn(images):\n    images_resized = tf.image.resize(images, (224, 224)).numpy()\n    metas = np.tile(X_meta_test[idx], (images_resized.shape[0], 1))\n    return model.predict([images_resized, metas])\n\n# Initialize LIME image explainer\nexplainer = lime_image.LimeImageExplainer()\n\n# Run LIME explanation on the test image\nexplanation = explainer.explain_instance(\n    image=test_img,\n    classifier_fn=predict_fn,\n    top_labels=6,          # Number of classes\n    hide_color=0,\n    num_samples=1000\n)\n\n# Plot explanations for all classes\nfig, axes = plt.subplots(2, 3, figsize=(18, 10))  # 2x3 grid for 6 classes\naxes = axes.flatten()\n\nfor i, class_id in enumerate(explanation.top_labels):\n    temp, mask = explanation.get_image_and_mask(\n        label=class_id,\n        positive_only=True,\n        num_features=10,\n        hide_rest=False\n    )\n    \n    axes[i].imshow(mark_boundaries(temp, mask))\n    axes[i].set_title(f\"LIME - {class_names[class_id]}\")\n    axes[i].axis('off')\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-13T14:44:58.390997Z","iopub.execute_input":"2025-08-13T14:44:58.391244Z","iopub.status.idle":"2025-08-13T14:45:16.891609Z","shell.execute_reply.started":"2025-08-13T14:44:58.391221Z","shell.execute_reply":"2025-08-13T14:45:16.890830Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install lime --quiet\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport random\nfrom lime import lime_image\nfrom skimage.segmentation import mark_boundaries\n\n# --------------------------\n# 1. Class names in correct order\n# --------------------------\nclass_names = [\n    \"Seizure\",\n    \"LPDA\",\n    \"LPD\",\n    \"Normal\",\n    \"GPD\",\n    \"GPDA\"\n]\n\nnum_classes = len(class_names)\n\n# --------------------------\n# 2. Set seeds for reproducibility\n# --------------------------\nnp.random.seed(123)\nrandom.seed(123)\ntf.random.set_seed(123)\n\n# --------------------------\n# 3. Pick a fixed test image index\n# --------------------------\nidx = 42  # <-- change if you want a different fixed sample\ntest_img = X_img_test[idx]\ntrue_label = np.argmax(y_test[idx])\nprint(f\"Explaining Test Sample Index: {idx}, True Class: {class_names[true_label]}\")\n\n# --------------------------\n# 4. Define LIME prediction wrapper\n# --------------------------\ndef predict_fn(images):\n    images_resized = tf.image.resize(images, (224, 224)).numpy()\n    metas = np.tile(X_meta_test[idx], (images_resized.shape[0], 1))\n    return model.predict([images_resized, metas])\n\n# --------------------------\n# 5. Create and run LIME explainer\n# --------------------------\nexplainer = lime_image.LimeImageExplainer()\n\nexplanation = explainer.explain_instance(\n    image=test_img,\n    classifier_fn=predict_fn,\n    top_labels=num_classes,    # Explain all classes\n    hide_color=0,\n    num_samples=1000\n)\n\n# --------------------------\n# 6. Plot all classes in fixed order (0 to 5)\n# --------------------------\nfig, axes = plt.subplots(2, 3, figsize=(18, 10))\naxes = axes.flatten()\n\nfor class_id in range(num_classes):  # Fixed order\n    temp, mask = explanation.get_image_and_mask(\n        label=class_id,\n        positive_only=True,\n        num_features=10,\n        hide_rest=False\n    )\n\n    axes[class_id].imshow(mark_boundaries(temp, mask))\n    axes[class_id].set_title(f\"LIME - {class_names[class_id]}\")\n    axes[class_id].axis('off')\n\nplt.tight_layout()\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-13T14:45:16.892734Z","iopub.execute_input":"2025-08-13T14:45:16.893399Z","iopub.status.idle":"2025-08-13T14:45:35.135322Z","shell.execute_reply.started":"2025-08-13T14:45:16.893363Z","shell.execute_reply":"2025-08-13T14:45:35.134491Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install lime --quiet\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom lime import lime_image\nfrom skimage.segmentation import mark_boundaries\nfrom skimage.color import label2rgb\n\n# Choose a random test image index\nidx = np.random.randint(0, len(X_img_test))\ntest_img = X_img_test[idx]\ntrue_label = np.argmax(y_test[idx])\n\nprint(f\"Explaining test sample index: {idx}, True class: {true_label}\")\n\n# Define classifier function for LIME (resizes + adds metadata)\ndef predict_fn(images):\n    images_resized = tf.image.resize(images, (224, 224)).numpy()\n    metas = np.tile(X_meta_test[idx], (images_resized.shape[0], 1))\n    return model.predict([images_resized, metas])\n\n# Initialize LIME image explainer\nexplainer = lime_image.LimeImageExplainer()\n\n# Run LIME explanation on the test image\nexplanation = explainer.explain_instance(\n    image=test_img,\n    classifier_fn=predict_fn,\n    top_labels=6,          # Set to number of total classes\n    hide_color=0,\n    num_samples=1000\n)\n\n# Plot explanations for **all classes**\nnum_classes = 6  # Replace with your actual number of classes\n\nfig, axes = plt.subplots(2, 3, figsize=(18, 10))  # Adjust subplot size for 6 classes\naxes = axes.flatten()\n\nfor i, class_id in enumerate(explanation.top_labels):\n    temp, mask = explanation.get_image_and_mask(\n        label=class_id,\n        positive_only=True,\n        num_features=10,\n        hide_rest=False\n    )\n    \n    axes[i].imshow(mark_boundaries(temp, mask))\n    axes[i].set_title(f\"LIME - {class_names[class_id]}\")\n    axes[i].axis('off')\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-13T14:45:35.137398Z","iopub.execute_input":"2025-08-13T14:45:35.137707Z","iopub.status.idle":"2025-08-13T14:45:54.188213Z","shell.execute_reply.started":"2025-08-13T14:45:35.137678Z","shell.execute_reply":"2025-08-13T14:45:54.187369Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}