{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":3960,"databundleVersionId":868348,"sourceType":"competition"}],"dockerImageVersionId":30787,"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_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Importing Modules\n","metadata":{}},{"cell_type":"code","source":"import os\nimport scipy.io\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.signal import spectrogram\nimport random\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential, Model\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense, Input, GlobalAveragePooling2D, Multiply, Reshape\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Preprocessing function to load data\ndef load_patient_data(patient_num, types, num_segments):\n    all_X = []\n    all_Y = []\n    base_path = f'/kaggle/input/seizure-prediction/Patient_{patient_num}/Patient_{patient_num}/'\n    \n    for i, typ in enumerate(types):\n        for j in range(num_segments):\n            fl = os.path.join(base_path, '{}_{}.mat'.format(typ, str(j + 1).zfill(4)))\n            data = scipy.io.loadmat(fl)\n            k = typ.replace(f'Patient_{patient_num}_', '') + '_'\n            d_array = data[k + str(j + 1)][0][0][0]\n            \n            lst = list(range(3000000))  # Adjust for 10 minutes\n            for m in lst[::5000]:  # Create a spectrogram every 1 second (5000 samples)\n                p_secs = d_array[0][m:m+5000]\n                p_f, p_t, p_Sxx = spectrogram(p_secs, fs=5000, return_onesided=False)\n                p_SS = np.log1p(p_Sxx)\n                arr = p_SS[:] / np.max(p_SS)\n                all_X.append(arr)\n                all_Y.append(i)\n    \n    return all_X, all_Y","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load both Patient 1 and Patient 2 data\ntypes = ['Patient_1_interictal_segment', 'Patient_1_preictal_segment']\nall_X1, all_Y1 = load_patient_data(1, types, 18)\n\ntypes = ['Patient_2_interictal_segment', 'Patient_2_preictal_segment']\nall_X2, all_Y2 = load_patient_data(2, types, 18)\n\n# Combine data from both patients\nall_X = all_X1 + all_X2\nall_Y = all_Y1 + all_Y2","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Shuffle the data\ndataset = list(zip(all_X, all_Y))\nrandom.shuffle(dataset)\nall_X, all_Y = zip(*dataset)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Convert to numpy arrays\nx_train = np.array(all_X[:42000])\ny_train = np.array(all_Y[:42000])\nx_test = np.array(all_X[42000:])\ny_test = np.array(all_Y[42000:])\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Reshape and normalize the data\nimg_rows, img_cols = 256, 22\nx_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)\nx_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)\nx_train = x_train.astype('float32')\nx_test = x_test.astype('float32')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Convert class vectors to binary class matrices (one-hot encoding)\nnum_classes = 2\ny_train = tf.keras.utils.to_categorical(y_train, num_classes)\ny_test = tf.keras.utils.to_categorical(y_test, num_classes)\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Lstms with attention mechanism","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.layers import LSTM, TimeDistributed\n\n# Attention mechanism block (Self-attention)\ndef attention_block(inputs):\n    channels = inputs.shape[-1]\n    attention = GlobalAveragePooling2D()(inputs)\n    attention = Dense(channels // 8, activation='relu')(attention)\n    attention = Dense(channels, activation='sigmoid')(attention)\n    attention = Reshape((1, 1, channels))(attention)\n    attention = Multiply()([inputs, attention])\n    return attention\n\n# CNN-LSTM model with attention mechanism\ninput_shape = (img_rows, img_cols, 1)\ninputs = Input(shape=input_shape)\n\n# CNN layers for spatial feature extraction\nx = Conv2D(32, kernel_size=(5, 5), activation='relu')(inputs)\nx = Conv2D(32, kernel_size=(3, 3), activation='relu')(x)\nx = MaxPooling2D(pool_size=(2, 2))(x)\nx = Dropout(0.25)(x)\n\n# Apply attention mechanism after convolutional layers\nx = attention_block(x)\n\n# Reshaping for LSTM input\n# Reshape the data to (batch_size, time_steps, features) to fit LSTM requirements\nx = TimeDistributed(Flatten())(x)  # Flatten across time\n\n# LSTM layers for temporal feature extraction\nx = LSTM(64, return_sequences=False)(x)  # Add LSTM layer (no return sequences)\nx = Dropout(0.5)(x)\n\n# Output layer\noutputs = Dense(2, activation='sigmoid')(x)\n\n# Build the model\nmodel = Model(inputs, outputs)\n\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.utils import plot_model\n\n# Visualize the model layers\nplot_model(model, to_file='model_layers.png', show_shapes=True, show_layer_names=True)\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Using 'binary_crossentropy'","metadata":{}},{"cell_type":"code","source":"# Compile the model\nmodel.compile(loss='binary_crossentropy',\n              optimizer='adam',\n              metrics=['accuracy'])\n\n# Print model summary\nmodel.summary()\n\n# Train the model\nbatch_size = 128\nepochs = 20\nmodel.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, validation_split=0.1, verbose=1)\n\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Evaluate the model on test data\nscore = model.evaluate(x_test, y_test, verbose=0)\nprint('Test loss:', score[0])\nprint('Test accuracy:', score[1])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Using dice as loss function","metadata":{}},{"cell_type":"code","source":"import tensorflow.keras.backend as K\ndef dice_loss(y_true, y_pred):\n    intersection = K.sum(y_true * y_pred)\n    return 1 - (2. * intersection + 1) / (K.sum(y_true) + K.sum(y_pred) + 1)\n# Compile the model\nmodel2 = Model(inputs, outputs)\nmodel2.compile(loss=dice_loss, optimizer='adam', metrics=['accuracy'])\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Train the model\nbatch_size = 128\nepochs = 20\nmodel2.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, validation_split=0.1, verbose=1)\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Evaluate the model on test data\nscore = model2.evaluate(x_test, y_test, verbose=0)\nprint('Test loss:', score[0])\nprint('Test accuracy:', score[1])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Using MSE","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.layers import LSTM, TimeDistributed\n\n# Attention mechanism block (Self-attention)\ndef attention_block(inputs):\n    channels = inputs.shape[-1]\n    attention = GlobalAveragePooling2D()(inputs)\n    attention = Dense(channels // 8, activation='relu')(attention)\n    attention = Dense(channels, activation='sigmoid')(attention)\n    attention = Reshape((1, 1, channels))(attention)\n    attention = Multiply()([inputs, attention])\n    return attention\n\n# CNN-LSTM model with attention mechanism\ninput_shape = (img_rows, img_cols, 1)\ninputs = Input(shape=input_shape)\n\n# CNN layers for spatial feature extraction\nx = Conv2D(32, kernel_size=(5, 5), activation='relu')(inputs)\nx = Conv2D(32, kernel_size=(3, 3), activation='relu')(x)\nx = MaxPooling2D(pool_size=(2, 2))(x)\nx = Dropout(0.25)(x)\n\n# Apply attention mechanism after convolutional layers\nx = attention_block(x)\n\n# Reshaping for LSTM input\n# Reshape the data to (batch_size, time_steps, features) to fit LSTM requirements\nx = TimeDistributed(Flatten())(x)  # Flatten across time\n\n# LSTM layers for temporal feature extraction\nx = LSTM(64, return_sequences=False)(x)  # Add LSTM layer (no return sequences)\nx = Dropout(0.5)(x)\n\n# Output layer\noutputs = Dense(2, activation='sigmoid')(x)\n\n# Build the model\nmodel3 = Model(inputs, outputs)\n\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model3.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy'])\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Train the model\nbatch_size = 128\nepochs = 20\nmodel3.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, validation_split=0.1, verbose=1)\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}