{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":59093,"databundleVersionId":7469972,"sourceType":"competition"}],"dockerImageVersionId":31154,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\nimport pandas as pd\nimport numpy as np","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-10-18T13:51:07.257493Z","iopub.execute_input":"2025-10-18T13:51:07.258277Z","iopub.status.idle":"2025-10-18T13:51:07.261666Z","shell.execute_reply.started":"2025-10-18T13:51:07.25825Z","shell.execute_reply":"2025-10-18T13:51:07.260929Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Eldeki tüm veriyi ayrıca import edelim\n\nBASE_PATH = \"/kaggle/input/hms-harmful-brain-activity-classification\"\neeg_path = BASE_PATH+\"/\"+\"train_eegs\"\nimport pandas as pd\npd.read_parquet(eeg_path+\"/\"+os.listdir(eeg_path)[0])\n\ncsv = pd.read_csv(BASE_PATH+\"/train.csv\")\nunique_eeg_ids_df = csv.drop_duplicates(subset='eeg_id')\nunique_eeg_ids_df = unique_eeg_ids_df[['eeg_id', 'expert_consensus']]\nunique_values = unique_eeg_ids_df['expert_consensus'].unique()\nprint(unique_values)\nlabels = {0:\"Seizure\",1:\"GPD\",2:\"LRDA\",3:\"LPD\",4:\"GRDA\",5:\"Other\"}\n# Invert the labels dictionary to map string labels to their numeric values\nlabel_map = {v: k for k, v in labels.items()}\n\n# Replace the string values in the expert_consensus column with their numeric values\nunique_eeg_ids_df['expert_consensus'] = unique_eeg_ids_df['expert_consensus'].map(label_map)\nunique_eeg_ids_df","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-18T13:51:01.779333Z","iopub.execute_input":"2025-10-18T13:51:01.779619Z","iopub.status.idle":"2025-10-18T13:51:03.936183Z","shell.execute_reply.started":"2025-10-18T13:51:01.779597Z","shell.execute_reply":"2025-10-18T13:51:03.935371Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pywt\nprint(\"The wavelet functions we can use:\")\nprint(pywt.wavelist())\n\nUSE_WAVELET = None #or \"db8\" or anything below\n\n# DENOISE FUNCTION\ndef maddest(d, axis=None):\n    return np.mean(np.absolute(d - np.mean(d, axis)), axis)\n\ndef denoise(x, wavelet='haar', level=1):    \n    coeff = pywt.wavedec(x, wavelet, mode=\"per\")\n    sigma = (1/0.6745) * maddest(coeff[-level])\n\n    uthresh = sigma * np.sqrt(2*np.log(len(x)))\n    coeff[1:] = (pywt.threshold(i, value=uthresh, mode='hard') for i in coeff[1:])\n\n    ret=pywt.waverec(coeff, wavelet, mode='per')\n    \n    return ret\n\nimport librosa\n\ndef spectrogram_from_eeg(parquet_path, display=False):\n    parquet_path = BASE_PATH+\"/train_eegs/\"+str(parquet_path)+\".parquet\"\n    # LOAD MIDDLE 50 SECONDS OF EEG SERIES\n    eeg = pd.read_parquet(parquet_path)\n    middle = (len(eeg)-10_000)//2\n    eeg = eeg.iloc[middle:middle+10_000]\n    \n    # VARIABLE TO HOLD SPECTROGRAM\n    img = np.zeros((128,256,4),dtype='float32')\n    \n    if display: plt.figure(figsize=(10,7))\n    signals = []\n    for k in range(4):\n        COLS = FEATS[k]\n        \n        for kk in range(4):\n        \n            # COMPUTE PAIR DIFFERENCES\n            x = eeg[COLS[kk]].values - eeg[COLS[kk+1]].values\n\n            # FILL NANS\n            m = np.nanmean(x)\n            if np.isnan(x).mean()<1: x = np.nan_to_num(x,nan=m)\n            else: x[:] = 0\n\n            # DENOISE\n            if USE_WAVELET:\n                x = denoise(x, wavelet=USE_WAVELET)\n            signals.append(x)\n\n            # RAW SPECTROGRAM\n            mel_spec = librosa.feature.melspectrogram(y=x, sr=200, hop_length=len(x)//256, \n                  n_fft=1024, n_mels=128, fmin=0, fmax=20, win_length=128)\n\n            # LOG TRANSFORM\n            width = (mel_spec.shape[1]//32)*32\n            mel_spec_db = librosa.power_to_db(mel_spec, ref=np.max).astype(np.float32)[:,:width]\n\n            # STANDARDIZE TO -1 TO 1\n            mel_spec_db = (mel_spec_db+40)/40 \n            img[:,:,k] += mel_spec_db\n                \n        # AVERAGE THE 4 MONTAGE DIFFERENCES\n        img[:,:,k] /= 4.0\n        \n        if display:\n            plt.subplot(2,2,k+1)\n            plt.imshow(img[:,:,k],aspect='auto',origin='lower')\n            plt.title(f'EEG {eeg_id} - Spectrogram {NAMES[k]}')\n            \n    if display: \n        plt.show()\n        plt.figure(figsize=(10,5))\n        offset = 0\n        for k in range(4):\n            if k>0: offset -= signals[3-k].min()\n            plt.plot(range(10_000),signals[k]+offset,label=NAMES[3-k])\n            offset += signals[3-k].max()\n        plt.legend()\n        plt.title(f'EEG {eeg_id} Signals')\n        plt.show()\n        print(); print('#'*25); print()\n        \n    return img\n\ndef spectrogram_from_eeg_2d(eeg_id, display=False):\n    data = spectrogram_from_eeg(eeg_id)\n    concatenated_image = np.vstack((np.hstack((data[:, :, 0], data[:, :, 1])), \n                                    np.hstack((data[:, :, 2], data[:, :, 3]))))\n    return concatenated_image","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-18T13:51:08.900805Z","iopub.execute_input":"2025-10-18T13:51:08.901085Z","iopub.status.idle":"2025-10-18T13:51:09.118054Z","shell.execute_reply.started":"2025-10-18T13:51:08.90106Z","shell.execute_reply":"2025-10-18T13:51:09.116955Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras import layers, models\nfrom sklearn.model_selection import train_test_split","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-18T13:51:11.587067Z","iopub.execute_input":"2025-10-18T13:51:11.587788Z","iopub.status.idle":"2025-10-18T13:51:20.421665Z","shell.execute_reply.started":"2025-10-18T13:51:11.587765Z","shell.execute_reply":"2025-10-18T13:51:20.420838Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"NAMES = ['LL','LP','RP','RR']\n\nFEATS = [['Fp1','F7','T3','T5','O1'],\n         ['Fp1','F3','C3','P3','O1'],\n         ['Fp2','F8','T4','T6','O2'],\n         ['Fp2','F4','C4','P4','O2']]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-18T13:51:20.422885Z","iopub.execute_input":"2025-10-18T13:51:20.423591Z","iopub.status.idle":"2025-10-18T13:51:20.427826Z","shell.execute_reply.started":"2025-10-18T13:51:20.423571Z","shell.execute_reply":"2025-10-18T13:51:20.426993Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"unique_eeg_ids_df","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-18T13:51:20.428691Z","iopub.execute_input":"2025-10-18T13:51:20.428971Z","iopub.status.idle":"2025-10-18T13:51:20.453609Z","shell.execute_reply.started":"2025-10-18T13:51:20.428951Z","shell.execute_reply":"2025-10-18T13:51:20.452876Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from matplotlib import pyplot as plt","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-18T13:51:20.454721Z","iopub.execute_input":"2025-10-18T13:51:20.454972Z","iopub.status.idle":"2025-10-18T13:51:20.4648Z","shell.execute_reply.started":"2025-10-18T13:51:20.454955Z","shell.execute_reply":"2025-10-18T13:51:20.46417Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.imshow(spectrogram_from_eeg_2d(1628180742), aspect='auto', origin='lower', cmap='jet')\nplt.axis('off')  # tüm eksenleri ve çerçeveleri gizler\nplt.tight_layout(pad=0)  # kenar boşluklarını sıfırla\nplt.savefig(\"spectrogram_clean.png\", dpi=300, bbox_inches='tight', pad_inches=0)\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-18T14:32:28.379498Z","iopub.execute_input":"2025-10-18T14:32:28.38006Z","iopub.status.idle":"2025-10-18T14:32:29.126605Z","shell.execute_reply.started":"2025-10-18T14:32:28.380036Z","shell.execute_reply":"2025-10-18T14:32:29.12579Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.imshow(spectrogram_from_eeg_2d(1628180742), aspect='auto', origin='lower', cmap='jet')\nplt.axis('off')  # tüm eksenleri ve çerçeveleri gizler\nplt.tight_layout(pad=0)  # kenar boşluklarını sıfırla\nplt.savefig(\"spectrogram_clean.png\", dpi=300, bbox_inches='tight', pad_inches=0)\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-18T14:33:02.10218Z","iopub.execute_input":"2025-10-18T14:33:02.103824Z","iopub.status.idle":"2025-10-18T14:33:02.837128Z","shell.execute_reply.started":"2025-10-18T14:33:02.103793Z","shell.execute_reply":"2025-10-18T14:33:02.836328Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\n\n# Çıktı klasörünü oluştur\nos.makedirs(\"spectrograms\", exist_ok=True)\n\n# Tüm EEG ID'ler için döngü\nfor eeg_id in tqdm(unique_eeg_ids_df[\"eeg_id\"], desc=\"Spectrogram oluşturuluyor\"):\n    try:\n        # EEG'den spectrogram oluştur\n        spec = spectrogram_from_eeg_2d(eeg_id)\n        \n        # Plot ayarları\n        plt.imshow(spec, aspect='auto', origin='lower', cmap='jet')\n        plt.axis('off')  # eksenleri kaldır\n        plt.tight_layout(pad=0)  # boşlukları sıfırla\n        \n        # Kayıt yolu\n        save_path = f\"spectrograms/{eeg_id}.png\"\n        plt.savefig(save_path, dpi=300, bbox_inches='tight', pad_inches=0)\n        plt.close()  # bellek tasarrufu\n\n    except Exception as e:\n        print(f\"{eeg_id} işlenirken hata oluştu: {e}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-18T14:34:16.69697Z","iopub.execute_input":"2025-10-18T14:34:16.697343Z","iopub.status.idle":"2025-10-18T14:34:30.152543Z","shell.execute_reply.started":"2025-10-18T14:34:16.697319Z","shell.execute_reply":"2025-10-18T14:34:30.151198Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n\n# 1. /kaggle/working dizinine geçtiğinizden emin olun (Zaten oradaysanız bu adım gereksizdir, \n# ancak dosyanın çıktı olarak görünmesi için genellikle bu dizinde olması gerekir.)\nos.chdir('/kaggle/working')\n\n# 2. Spectrograms klasörünü ZIP'le\n# ! işareti, hücredeki komutun bir terminal komutu olduğunu gösterir.\n# -r: klasörün içindeki tüm dosyaları da dahil et\n# -q: sessiz mod (çıktı gösterme)\n!zip -r -q spectrograms.zip spectrograms\n\nprint(\"Spectrograms klasörü başarıyla 'spectrograms.zip' olarak sıkıştırıldı.\")\n\n# 3. İsteğe bağlı: İndirme bağlantısı oluşturma (Notebook'unuzu Commit etmeden indirmek için)\n# Bu satır, Kaggle ortamında bir indirme bağlantısı oluşturur.\nfrom IPython.display import FileLink\nFileLink(r'spectrograms.zip')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-18T14:29:54.475065Z","iopub.execute_input":"2025-10-18T14:29:54.475923Z","iopub.status.idle":"2025-10-18T14:30:51.397161Z","shell.execute_reply.started":"2025-10-18T14:29:54.475896Z","shell.execute_reply":"2025-10-18T14:30:51.396212Z"}},"outputs":[],"execution_count":null}]}