{"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":"none","dataSources":[{"sourceId":3960,"databundleVersionId":868348,"sourceType":"competition"}],"dockerImageVersionId":30787,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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":"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":{"execution":{"iopub.status.busy":"2024-10-18T06:48:53.715329Z","iopub.execute_input":"2024-10-18T06:48:53.716399Z","iopub.status.idle":"2024-10-18T06:49:13.762706Z","shell.execute_reply.started":"2024-10-18T06:48:53.716354Z","shell.execute_reply":"2024-10-18T06:49:13.761726Z"},"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":{"execution":{"iopub.status.busy":"2024-10-18T06:49:17.696146Z","iopub.execute_input":"2024-10-18T06:49:17.696803Z","iopub.status.idle":"2024-10-18T06:49:17.706714Z","shell.execute_reply.started":"2024-10-18T06:49:17.696761Z","shell.execute_reply":"2024-10-18T06:49:17.705507Z"},"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":{"execution":{"iopub.status.busy":"2024-10-18T06:49:27.780974Z","iopub.execute_input":"2024-10-18T06:49:27.781424Z","iopub.status.idle":"2024-10-18T06:51:56.290211Z","shell.execute_reply.started":"2024-10-18T06:49:27.781382Z","shell.execute_reply":"2024-10-18T06:51:56.289303Z"},"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":{"execution":{"iopub.status.busy":"2024-10-18T06:51:56.291995Z","iopub.execute_input":"2024-10-18T06:51:56.292341Z","iopub.status.idle":"2024-10-18T06:51:56.354088Z","shell.execute_reply.started":"2024-10-18T06:51:56.292306Z","shell.execute_reply":"2024-10-18T06:51:56.353298Z"},"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":{"execution":{"iopub.status.busy":"2024-10-18T06:51:56.355109Z","iopub.execute_input":"2024-10-18T06:51:56.35542Z","iopub.status.idle":"2024-10-18T06:51:57.133668Z","shell.execute_reply.started":"2024-10-18T06:51:56.355381Z","shell.execute_reply":"2024-10-18T06:51:57.132818Z"},"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":{"execution":{"iopub.status.busy":"2024-10-18T06:51:57.135903Z","iopub.execute_input":"2024-10-18T06:51:57.136234Z","iopub.status.idle":"2024-10-18T06:51:57.516712Z","shell.execute_reply.started":"2024-10-18T06:51:57.136201Z","shell.execute_reply":"2024-10-18T06:51:57.515461Z"},"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":{"execution":{"iopub.status.busy":"2024-10-18T06:51:57.51805Z","iopub.execute_input":"2024-10-18T06:51:57.518478Z","iopub.status.idle":"2024-10-18T06:51:57.524836Z","shell.execute_reply.started":"2024-10-18T06:51:57.518428Z","shell.execute_reply":"2024-10-18T06:51:57.523988Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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# Compile the model\nmodel.compile(loss='binary_crossentropy',\n              optimizer='adam',\n              metrics=['accuracy'])\n\n# Print model summary\nmodel.summary()\n","metadata":{"execution":{"iopub.status.busy":"2024-10-18T07:01:46.924292Z","iopub.execute_input":"2024-10-18T07:01:46.9247Z","iopub.status.idle":"2024-10-18T07:01:47.475818Z","shell.execute_reply.started":"2024-10-18T07:01:46.924665Z","shell.execute_reply":"2024-10-18T07:01:47.474977Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 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","metadata":{"execution":{"iopub.status.busy":"2024-10-18T07:03:08.408648Z","iopub.execute_input":"2024-10-18T07:03:08.409484Z","iopub.status.idle":"2024-10-18T07:08:50.947343Z","shell.execute_reply.started":"2024-10-18T07:03:08.409441Z","shell.execute_reply":"2024-10-18T07:08:50.945989Z"},"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":{"execution":{"iopub.status.busy":"2024-10-18T07:10:39.183671Z","iopub.execute_input":"2024-10-18T07:10:39.184127Z","iopub.status.idle":"2024-10-18T07:10:39.942849Z","shell.execute_reply.started":"2024-10-18T07:10:39.184091Z","shell.execute_reply":"2024-10-18T07:10:39.941718Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2024-10-18T06:54:47.307665Z","iopub.execute_input":"2024-10-18T06:54:47.308065Z","iopub.status.idle":"2024-10-18T06:54:47.344542Z","shell.execute_reply.started":"2024-10-18T06:54:47.308028Z","shell.execute_reply":"2024-10-18T06:54:47.3437Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Compile the model\nmodel = Model(inputs, outputs)\nmodel.compile(loss='binary_crossentropy',\n              optimizer='adam',\n              metrics=['accuracy'])\n","metadata":{"execution":{"iopub.status.busy":"2024-10-18T06:51:58.715944Z","iopub.execute_input":"2024-10-18T06:51:58.716219Z","iopub.status.idle":"2024-10-18T06:51:58.734606Z","shell.execute_reply.started":"2024-10-18T06:51:58.716188Z","shell.execute_reply":"2024-10-18T06:51:58.733713Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 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","metadata":{"execution":{"iopub.status.busy":"2024-10-18T06:51:58.735876Z","iopub.execute_input":"2024-10-18T06:51:58.736204Z","iopub.status.idle":"2024-10-18T06:54:01.106048Z","shell.execute_reply.started":"2024-10-18T06:51:58.736172Z","shell.execute_reply":"2024-10-18T06:54:01.105077Z"},"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":{"execution":{"iopub.status.busy":"2024-10-18T06:54:01.108741Z","iopub.execute_input":"2024-10-18T06:54:01.109054Z","iopub.status.idle":"2024-10-18T06:54:02.536069Z","shell.execute_reply.started":"2024-10-18T06:54:01.109021Z","shell.execute_reply":"2024-10-18T06:54:02.534948Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-10-18T06:59:20.822671Z","iopub.execute_input":"2024-10-18T06:59:20.823361Z","iopub.status.idle":"2024-10-18T06:59:20.837878Z","shell.execute_reply.started":"2024-10-18T06:59:20.823315Z","shell.execute_reply":"2024-10-18T06:59:20.837032Z"},"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":{"execution":{"iopub.status.busy":"2024-10-18T06:59:21.039007Z","iopub.execute_input":"2024-10-18T06:59:21.039731Z","iopub.status.idle":"2024-10-18T07:01:15.51469Z","shell.execute_reply.started":"2024-10-18T06:59:21.039693Z","shell.execute_reply":"2024-10-18T07:01:15.513739Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Assuming you have your data ready in x_train, y_train\nmodel2.fit(x_train, y_train, batch_size=128, epochs=20, validation_data=(x_test, y_test))\n","metadata":{},"execution_count":null,"outputs":[]}]}