{"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":"code","source":"from __future__ import print_function\nimport tensorflow as tf\n\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, Flatten\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D\n#from keras import backend as K\n\nimport random\nimport numpy as np\nimport pandas as pd\n\nimport scipy.io\nfrom scipy.signal import spectrogram\nimport matplotlib.pyplot as plt","metadata":{"execution":{"iopub.status.busy":"2024-10-17T15:33:12.477237Z","iopub.execute_input":"2024-10-17T15:33:12.478263Z","iopub.status.idle":"2024-10-17T15:33:33.417420Z","shell.execute_reply.started":"2024-10-17T15:33:12.478221Z","shell.execute_reply":"2024-10-17T15:33:33.416326Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"interictal_tst = '/kaggle/input/seizure-prediction/Patient_1/Patient_1/Patient_1_interictal_segment_0001.mat'\npreictal_tst = '/kaggle/input/seizure-prediction/Patient_1/Patient_1/Patient_1_preictal_segment_0001.mat'\ninterictal_data = scipy.io.loadmat(interictal_tst)\npreictal_data = scipy.io.loadmat(preictal_tst)","metadata":{"execution":{"iopub.status.busy":"2024-10-17T15:33:42.822850Z","iopub.execute_input":"2024-10-17T15:33:42.824157Z","iopub.status.idle":"2024-10-17T15:33:45.874894Z","shell.execute_reply.started":"2024-10-17T15:33:42.824103Z","shell.execute_reply":"2024-10-17T15:33:45.873988Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"interictal_array = interictal_data['interictal_segment_1'][0][0][0]\npreictal_array = preictal_data['preictal_segment_1'][0][0][0]","metadata":{"execution":{"iopub.status.busy":"2024-10-17T15:33:53.807918Z","iopub.execute_input":"2024-10-17T15:33:53.809542Z","iopub.status.idle":"2024-10-17T15:33:53.816973Z","shell.execute_reply.started":"2024-10-17T15:33:53.809485Z","shell.execute_reply":"2024-10-17T15:33:53.815912Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"l = list(range(10000))\nfor i in l[::5000]:\n    print('Interictal')\n    i_secs = interictal_array[0][i:i+5000]\n    i_f, i_t, i_Sxx = spectrogram(i_secs, fs=5000, return_onesided=False)\n    i_SS = np.log1p(i_Sxx)\n    plt.imshow(i_SS[:] / np.max(i_SS), cmap='gray')\n    plt.show()\n    print('Preictal')\n    p_secs = preictal_array[0][i:i+5000]\n    p_f, p_t, p_Sxx = spectrogram(p_secs, fs=5000, return_onesided=False)\n    p_SS = np.log1p(p_Sxx)\n    plt.imshow(p_SS[:] / np.max(p_SS), cmap='gray')\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2024-10-17T15:34:29.961477Z","iopub.execute_input":"2024-10-17T15:34:29.962408Z","iopub.status.idle":"2024-10-17T15:34:30.996272Z","shell.execute_reply.started":"2024-10-17T15:34:29.962364Z","shell.execute_reply":"2024-10-17T15:34:30.995194Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"all_X = []\nall_Y = []\n\ntypes = ['Patient_1_interictal_segment', 'Patient_1_preictal_segment']\n\nfor i,typ in enumerate(types):\n    # Looking at 18 files for each event for a balanced dataset\n    for j in range(18):\n        fl = '/kaggle/input/seizure-prediction/Patient_1/Patient_1/{}_{}.mat'.format(typ, str(j + 1).zfill(4))\n        data = scipy.io.loadmat(fl)\n        k = typ.replace('Patient_1_', '') + '_'\n        d_array = data[k + str(j + 1)][0][0][0]\n        lst = list(range(3000000))  # 10 minutes\n        for m in lst[::5000]:\n            # Create a spectrogram every 1 second\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)","metadata":{"execution":{"iopub.status.busy":"2024-10-17T15:34:48.377167Z","iopub.execute_input":"2024-10-17T15:34:48.378124Z","iopub.status.idle":"2024-10-17T15:35:44.887876Z","shell.execute_reply.started":"2024-10-17T15:34:48.378070Z","shell.execute_reply":"2024-10-17T15:35:44.887007Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"all_X[0]","metadata":{"execution":{"iopub.status.busy":"2024-10-17T15:36:18.622879Z","iopub.execute_input":"2024-10-17T15:36:18.624260Z","iopub.status.idle":"2024-10-17T15:36:18.634362Z","shell.execute_reply.started":"2024-10-17T15:36:18.624193Z","shell.execute_reply":"2024-10-17T15:36:18.632725Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Shuffling the data\ndataset = list(zip(all_X, all_Y))\nrandom.shuffle(dataset)\nall_X,all_Y = zip(*dataset)\nprint(len(all_X))","metadata":{"execution":{"iopub.status.busy":"2024-10-17T15:35:44.889688Z","iopub.execute_input":"2024-10-17T15:35:44.890307Z","iopub.status.idle":"2024-10-17T15:35:44.973501Z","shell.execute_reply.started":"2024-10-17T15:35:44.890258Z","shell.execute_reply":"2024-10-17T15:35:44.972337Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Splitting data into train/test, leaving only 600 samples for testing\nx_train = np.array(all_X[:21000])\ny_train = np.array(all_Y[:21000])\nx_test = np.array(all_X[21000:])\ny_test = np.array(all_Y[21000:])","metadata":{"execution":{"iopub.status.busy":"2024-10-17T15:36:38.822183Z","iopub.execute_input":"2024-10-17T15:36:38.822986Z","iopub.status.idle":"2024-10-17T15:36:39.240230Z","shell.execute_reply.started":"2024-10-17T15:36:38.822943Z","shell.execute_reply":"2024-10-17T15:36:39.239254Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"batch_size = 128\nnum_classes = 2\nepochs = 30\nimg_rows, img_cols = 256, 22","metadata":{"execution":{"iopub.status.busy":"2024-10-17T15:36:44.601847Z","iopub.execute_input":"2024-10-17T15:36:44.602642Z","iopub.status.idle":"2024-10-17T15:36:44.607373Z","shell.execute_reply.started":"2024-10-17T15:36:44.602597Z","shell.execute_reply":"2024-10-17T15:36:44.606043Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_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)\ninput_shape = (img_rows, img_cols, 1)\nx_train = x_train.astype('float32')\nx_test = x_test.astype('float32')","metadata":{"execution":{"iopub.status.busy":"2024-10-17T15:36:52.152134Z","iopub.execute_input":"2024-10-17T15:36:52.152892Z","iopub.status.idle":"2024-10-17T15:36:52.352998Z","shell.execute_reply.started":"2024-10-17T15:36:52.152845Z","shell.execute_reply":"2024-10-17T15:36:52.351837Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_train = tf.keras.utils.to_categorical(y_train, num_classes) \ny_test = tf.keras.utils.to_categorical(y_test, num_classes)","metadata":{"execution":{"iopub.status.busy":"2024-10-17T15:37:01.168770Z","iopub.execute_input":"2024-10-17T15:37:01.169175Z","iopub.status.idle":"2024-10-17T15:37:01.174715Z","shell.execute_reply.started":"2024-10-17T15:37:01.169137Z","shell.execute_reply":"2024-10-17T15:37:01.173796Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense, Input, GlobalAveragePooling2D, Multiply, Reshape, Permute\nfrom tensorflow.keras import Model\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# Modify input_shape to match your data shape (with 1 channel)\ninput_shape = (256, 22, 1)\n\ninputs = Input(shape=input_shape)\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# Flatten, Dense, Dropout, and Output layers (same as before)\nx = Flatten()(x)\nx = Dense(32, activation='relu')(x)\nx = Dropout(0.5)(x)\noutputs = Dense(2, activation='sigmoid')(x)\n\nmodel = Model(inputs, outputs)\n\nmodel.compile(loss='binary_crossentropy',\n              optimizer='adam',\n              metrics=['accuracy'])\n\n\n","metadata":{"execution":{"iopub.status.busy":"2024-10-17T15:50:26.427300Z","iopub.execute_input":"2024-10-17T15:50:26.427685Z","iopub.status.idle":"2024-10-17T15:50:26.502824Z","shell.execute_reply.started":"2024-10-17T15:50:26.427647Z","shell.execute_reply":"2024-10-17T15:50:26.501699Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Train the model\nmodel.fit(x_train, y_train,\n          batch_size=batch_size,\n          epochs=epochs,\n          verbose=1,\n          validation_data=(x_test, y_test))\n\n","metadata":{"execution":{"iopub.status.busy":"2024-10-17T15:50:28.787012Z","iopub.execute_input":"2024-10-17T15:50:28.787451Z","iopub.status.idle":"2024-10-17T15:52:20.632130Z","shell.execute_reply.started":"2024-10-17T15:50:28.787413Z","shell.execute_reply":"2024-10-17T15:52:20.631040Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"score = 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-17T15:52:32.247591Z","iopub.execute_input":"2024-10-17T15:52:32.247992Z","iopub.status.idle":"2024-10-17T15:52:33.798474Z","shell.execute_reply.started":"2024-10-17T15:52:32.247953Z","shell.execute_reply":"2024-10-17T15:52:33.797448Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}