{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.7.6","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":29928,"isInternetEnabled":false,"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":"2023-05-09T06:51:37.397826Z","iopub.execute_input":"2023-05-09T06:51:37.398178Z","iopub.status.idle":"2023-05-09T06:51:41.720101Z","shell.execute_reply.started":"2023-05-09T06:51:37.398142Z","shell.execute_reply":"2023-05-09T06:51:41.719328Z"},"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\n","metadata":{"execution":{"iopub.status.busy":"2023-05-09T19:31:51.408163Z","iopub.execute_input":"2023-05-09T19:31:51.408492Z","iopub.status.idle":"2023-05-09T19:31:56.158360Z","shell.execute_reply.started":"2023-05-09T19:31:51.408460Z","shell.execute_reply":"2023-05-09T19:31:56.157491Z"},"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)\n","metadata":{"execution":{"iopub.status.busy":"2023-05-09T19:31:59.633185Z","iopub.execute_input":"2023-05-09T19:31:59.633516Z","iopub.status.idle":"2023-05-09T19:32:03.078571Z","shell.execute_reply.started":"2023-05-09T19:31:59.633484Z","shell.execute_reply":"2023-05-09T19:32:03.077620Z"},"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":"2023-05-09T06:52:02.557255Z","iopub.execute_input":"2023-05-09T06:52:02.557593Z","iopub.status.idle":"2023-05-09T06:52:02.562089Z","shell.execute_reply.started":"2023-05-09T06:52:02.557561Z","shell.execute_reply":"2023-05-09T06:52:02.561026Z"},"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":"2023-05-09T06:52:05.618405Z","iopub.execute_input":"2023-05-09T06:52:05.618737Z","iopub.status.idle":"2023-05-09T06:52:06.185196Z","shell.execute_reply.started":"2023-05-09T06:52:05.618706Z","shell.execute_reply":"2023-05-09T06:52:06.184273Z"},"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        print(fl)\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":"2023-05-09T19:33:19.893329Z","iopub.execute_input":"2023-05-09T19:33:19.893657Z","iopub.status.idle":"2023-05-09T19:33:36.432846Z","shell.execute_reply.started":"2023-05-09T19:33:19.893624Z","shell.execute_reply":"2023-05-09T19:33:36.432073Z"},"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":"2023-05-09T06:53:16.111608Z","iopub.execute_input":"2023-05-09T06:53:16.111994Z","iopub.status.idle":"2023-05-09T06:53:16.197693Z","shell.execute_reply.started":"2023-05-09T06:53:16.111948Z","shell.execute_reply":"2023-05-09T06:53:16.195734Z"},"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:])\n","metadata":{"execution":{"iopub.status.busy":"2023-05-09T06:53:19.218152Z","iopub.execute_input":"2023-05-09T06:53:19.218497Z","iopub.status.idle":"2023-05-09T06:53:19.584823Z","shell.execute_reply.started":"2023-05-09T06:53:19.218462Z","shell.execute_reply":"2023-05-09T06:53:19.583745Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(x_train.shape)","metadata":{"execution":{"iopub.status.busy":"2023-05-09T06:53:35.363473Z","iopub.execute_input":"2023-05-09T06:53:35.363811Z","iopub.status.idle":"2023-05-09T06:53:35.368742Z","shell.execute_reply.started":"2023-05-09T06:53:35.363781Z","shell.execute_reply":"2023-05-09T06:53:35.367706Z"},"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":"2023-05-09T06:53:39.205806Z","iopub.execute_input":"2023-05-09T06:53:39.206135Z","iopub.status.idle":"2023-05-09T06:53:39.211415Z","shell.execute_reply.started":"2023-05-09T06:53:39.206104Z","shell.execute_reply":"2023-05-09T06:53:39.210418Z"},"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":"2023-05-09T06:53:46.026378Z","iopub.execute_input":"2023-05-09T06:53:46.026931Z","iopub.status.idle":"2023-05-09T06:53:46.215263Z","shell.execute_reply.started":"2023-05-09T06:53:46.026893Z","shell.execute_reply":"2023-05-09T06:53:46.214359Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"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":"2023-05-09T06:53:50.031382Z","iopub.execute_input":"2023-05-09T06:53:50.031786Z","iopub.status.idle":"2023-05-09T06:53:50.039345Z","shell.execute_reply.started":"2023-05-09T06:53:50.031752Z","shell.execute_reply":"2023-05-09T06:53:50.038431Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":"2023-05-09T06:53:53.328736Z","iopub.execute_input":"2023-05-09T06:53:53.329062Z","iopub.status.idle":"2023-05-09T06:53:55.733544Z","shell.execute_reply.started":"2023-05-09T06:53:53.329030Z","shell.execute_reply":"2023-05-09T06:53:55.732716Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()\n","metadata":{"execution":{"iopub.status.busy":"2023-05-09T06:54:00.452544Z","iopub.execute_input":"2023-05-09T06:54:00.452876Z","iopub.status.idle":"2023-05-09T06:54:00.463306Z","shell.execute_reply.started":"2023-05-09T06:54:00.452845Z","shell.execute_reply":"2023-05-09T06:54:00.462308Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":"2023-05-09T06:54:04.036961Z","iopub.execute_input":"2023-05-09T06:54:04.037289Z","iopub.status.idle":"2023-05-09T06:55:19.511588Z","shell.execute_reply.started":"2023-05-09T06:54:04.037257Z","shell.execute_reply":"2023-05-09T06:55:19.510648Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}