{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.7.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":3960,"databundleVersionId":868348,"sourceType":"competition"}],"dockerImageVersionId":30299,"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 5GB 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","execution":{"iopub.status.busy":"2024-04-09T04:53:15.740533Z","iopub.execute_input":"2024-04-09T04:53:15.740870Z","iopub.status.idle":"2024-04-09T04:53:26.914817Z","shell.execute_reply.started":"2024-04-09T04:53:15.740794Z","shell.execute_reply":"2024-04-09T04:53:26.913797Z"},"trusted":true},"outputs":[],"execution_count":null},{"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\n","metadata":{"execution":{"iopub.status.busy":"2024-04-09T04:53:26.916353Z","iopub.execute_input":"2024-04-09T04:53:26.916639Z","iopub.status.idle":"2024-04-09T04:53:32.904831Z","shell.execute_reply.started":"2024-04-09T04:53:26.916613Z","shell.execute_reply":"2024-04-09T04:53:32.903879Z"},"trusted":true},"outputs":[],"execution_count":null},{"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)\n","metadata":{"execution":{"iopub.status.busy":"2024-04-09T04:53:32.906123Z","iopub.execute_input":"2024-04-09T04:53:32.906666Z","iopub.status.idle":"2024-04-09T04:53:37.101384Z","shell.execute_reply.started":"2024-04-09T04:53:32.906637Z","shell.execute_reply":"2024-04-09T04:53:37.100488Z"},"trusted":true},"outputs":[],"execution_count":null},{"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-04-09T04:53:37.104111Z","iopub.execute_input":"2024-04-09T04:53:37.104463Z","iopub.status.idle":"2024-04-09T04:53:37.109765Z","shell.execute_reply.started":"2024-04-09T04:53:37.104433Z","shell.execute_reply":"2024-04-09T04:53:37.108648Z"},"trusted":true},"outputs":[],"execution_count":null},{"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-04-09T04:53:37.110954Z","iopub.execute_input":"2024-04-09T04:53:37.111278Z","iopub.status.idle":"2024-04-09T04:53:37.840489Z","shell.execute_reply.started":"2024-04-09T04:53:37.111236Z","shell.execute_reply":"2024-04-09T04:53:37.839576Z"},"trusted":true},"outputs":[],"execution_count":null},{"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-04-09T05:08:31.411906Z","iopub.execute_input":"2024-04-09T05:08:31.412805Z","iopub.status.idle":"2024-04-09T05:08:51.176993Z","shell.execute_reply.started":"2024-04-09T05:08:31.412761Z","shell.execute_reply":"2024-04-09T05:08:51.176136Z"},"trusted":true},"outputs":[],"execution_count":null},{"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-04-09T05:08:51.561957Z","iopub.execute_input":"2024-04-09T05:08:51.562294Z","iopub.status.idle":"2024-04-09T05:08:51.602375Z","shell.execute_reply.started":"2024-04-09T05:08:51.562263Z","shell.execute_reply":"2024-04-09T05:08:51.601443Z"},"trusted":true},"outputs":[],"execution_count":null},{"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:])\n","metadata":{"execution":{"iopub.status.busy":"2024-04-09T05:08:51.603474Z","iopub.execute_input":"2024-04-09T05:08:51.603789Z","iopub.status.idle":"2024-04-09T05:08:51.982285Z","shell.execute_reply.started":"2024-04-09T05:08:51.603760Z","shell.execute_reply":"2024-04-09T05:08:51.981428Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"batch_size = 128\nnum_classes = 2\nepochs = 30\nimg_rows, img_cols = 256, 22","metadata":{"execution":{"iopub.status.busy":"2024-04-09T05:08:51.983532Z","iopub.execute_input":"2024-04-09T05:08:51.983914Z","iopub.status.idle":"2024-04-09T05:08:51.989404Z","shell.execute_reply.started":"2024-04-09T05:08:51.983878Z","shell.execute_reply":"2024-04-09T05:08:51.988406Z"},"trusted":true},"outputs":[],"execution_count":null},{"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-04-09T05:08:51.990570Z","iopub.execute_input":"2024-04-09T05:08:51.990851Z","iopub.status.idle":"2024-04-09T05:08:52.184695Z","shell.execute_reply.started":"2024-04-09T05:08:51.990825Z","shell.execute_reply":"2024-04-09T05:08:52.183792Z"},"trusted":true},"outputs":[],"execution_count":null},{"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-04-09T05:08:52.185894Z","iopub.execute_input":"2024-04-09T05:08:52.186173Z","iopub.status.idle":"2024-04-09T05:08:52.191888Z","shell.execute_reply.started":"2024-04-09T05:08:52.186148Z","shell.execute_reply":"2024-04-09T05:08:52.190895Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(32, kernel_size=(5, 5),\n                 activation='relu',\n                 input_shape=input_shape))\nmodel.add(Conv2D(32, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\nmodel.add(Flatten())\nmodel.add(Dense(32, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(num_classes, activation='sigmoid'))\n\nmodel.compile(loss=tf.keras.losses.binary_crossentropy,\n              optimizer=tf.keras.optimizers.RMSprop(),\n              metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2024-04-09T05:08:52.193086Z","iopub.execute_input":"2024-04-09T05:08:52.193532Z","iopub.status.idle":"2024-04-09T05:08:52.254047Z","shell.execute_reply.started":"2024-04-09T05:08:52.193502Z","shell.execute_reply":"2024-04-09T05:08:52.253293Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.summary()\n","metadata":{"execution":{"iopub.status.busy":"2024-04-09T04:54:43.293103Z","iopub.execute_input":"2024-04-09T04:54:43.293472Z","iopub.status.idle":"2024-04-09T04:54:43.300247Z","shell.execute_reply.started":"2024-04-09T04:54:43.293442Z","shell.execute_reply":"2024-04-09T04:54:43.299252Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.fit(x_train, y_train,\n          batch_size=batch_size,\n          epochs=epochs,\n          verbose=1,\n          validation_data=(x_test, y_test))\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-04-09T04:54:43.301408Z","iopub.execute_input":"2024-04-09T04:54:43.301705Z","iopub.status.idle":"2024-04-09T04:55:56.791597Z","shell.execute_reply.started":"2024-04-09T04:54:43.301663Z","shell.execute_reply":"2024-04-09T04:55:56.790624Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}