{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.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":59093,"databundleVersionId":7469972,"sourceType":"competition"}],"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T13:20:44.580682Z","iopub.execute_input":"2025-03-24T13:20:44.581006Z","iopub.status.idle":"2025-03-24T13:20:44.584227Z","shell.execute_reply.started":"2025-03-24T13:20:44.580984Z","shell.execute_reply":"2025-03-24T13:20:44.583609Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"BASE_PATH = \"/kaggle/input/hms-harmful-brain-activity-classification\"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T13:20:44.590879Z","iopub.execute_input":"2025-03-24T13:20:44.591135Z","iopub.status.idle":"2025-03-24T13:20:44.604546Z","shell.execute_reply.started":"2025-03-24T13:20:44.591115Z","shell.execute_reply":"2025-03-24T13:20:44.603604Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"os.listdir(\"/kaggle/input/\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T13:20:44.605243Z","iopub.execute_input":"2025-03-24T13:20:44.605529Z","iopub.status.idle":"2025-03-24T13:20:44.624131Z","shell.execute_reply.started":"2025-03-24T13:20:44.605469Z","shell.execute_reply":"2025-03-24T13:20:44.623548Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"os.listdir(\"/kaggle/input/hms-harmful-brain-activity-classification\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T13:20:44.624741Z","iopub.execute_input":"2025-03-24T13:20:44.624927Z","iopub.status.idle":"2025-03-24T13:20:44.640988Z","shell.execute_reply.started":"2025-03-24T13:20:44.62491Z","shell.execute_reply":"2025-03-24T13:20:44.640103Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"eeg_path = BASE_PATH+\"/\"+\"train_eegs\"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T13:20:44.641747Z","iopub.execute_input":"2025-03-24T13:20:44.641987Z","iopub.status.idle":"2025-03-24T13:20:44.655339Z","shell.execute_reply.started":"2025-03-24T13:20:44.641967Z","shell.execute_reply":"2025-03-24T13:20:44.654363Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"os.listdir(eeg_path)[:10]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T13:20:44.656125Z","iopub.execute_input":"2025-03-24T13:20:44.656327Z","iopub.status.idle":"2025-03-24T13:20:44.67813Z","shell.execute_reply.started":"2025-03-24T13:20:44.656308Z","shell.execute_reply":"2025-03-24T13:20:44.677254Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T13:20:44.681145Z","iopub.execute_input":"2025-03-24T13:20:44.681379Z","iopub.status.idle":"2025-03-24T13:20:45.003856Z","shell.execute_reply.started":"2025-03-24T13:20:44.68136Z","shell.execute_reply":"2025-03-24T13:20:45.002927Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pd.read_parquet(eeg_path+\"/\"+os.listdir(eeg_path)[0])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T13:20:45.005969Z","iopub.execute_input":"2025-03-24T13:20:45.006447Z","iopub.status.idle":"2025-03-24T13:20:45.058807Z","shell.execute_reply.started":"2025-03-24T13:20:45.006412Z","shell.execute_reply":"2025-03-24T13:20:45.057887Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train = pd.read_csv(BASE_PATH+\"/train.csv\")\nprint('Train shape', train.shape )\ndisplay( train.head() )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T13:20:45.059642Z","iopub.execute_input":"2025-03-24T13:20:45.059891Z","iopub.status.idle":"2025-03-24T13:20:45.20799Z","shell.execute_reply.started":"2025-03-24T13:20:45.05987Z","shell.execute_reply":"2025-03-24T13:20:45.207054Z"}},"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","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T13:20:45.208941Z","iopub.execute_input":"2025-03-24T13:20:45.209285Z","iopub.status.idle":"2025-03-24T13:20:45.390545Z","shell.execute_reply.started":"2025-03-24T13:20:45.20925Z","shell.execute_reply":"2025-03-24T13:20:45.389664Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 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","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T13:20:45.391495Z","iopub.execute_input":"2025-03-24T13:20:45.391933Z","iopub.status.idle":"2025-03-24T13:20:45.398131Z","shell.execute_reply.started":"2025-03-24T13:20:45.391909Z","shell.execute_reply":"2025-03-24T13:20:45.397286Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import librosa\nimport numpy as np","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T13:20:45.398849Z","iopub.execute_input":"2025-03-24T13:20:45.399068Z","iopub.status.idle":"2025-03-24T13:20:45.418247Z","shell.execute_reply.started":"2025-03-24T13:20:45.399048Z","shell.execute_reply":"2025-03-24T13:20:45.417457Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def 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","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T13:20:45.419102Z","iopub.execute_input":"2025-03-24T13:20:45.419379Z","iopub.status.idle":"2025-03-24T13:20:45.433825Z","shell.execute_reply.started":"2025-03-24T13:20:45.419353Z","shell.execute_reply":"2025-03-24T13:20:45.432769Z"}},"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-03-24T13:20:45.43472Z","iopub.execute_input":"2025-03-24T13:20:45.434974Z","iopub.status.idle":"2025-03-24T13:20:45.452448Z","shell.execute_reply.started":"2025-03-24T13:20:45.434954Z","shell.execute_reply":"2025-03-24T13:20:45.451664Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# spectrogram_from_eeg(eeg_path+\"/\"+os.listdir(eeg_path)[3]).shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T13:20:45.453327Z","iopub.execute_input":"2025-03-24T13:20:45.453601Z","iopub.status.idle":"2025-03-24T13:20:45.467927Z","shell.execute_reply.started":"2025-03-24T13:20:45.453575Z","shell.execute_reply":"2025-03-24T13:20:45.467049Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"csv = pd.read_csv(BASE_PATH+\"/train.csv\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T13:20:45.468691Z","iopub.execute_input":"2025-03-24T13:20:45.468944Z","iopub.status.idle":"2025-03-24T13:20:45.610117Z","shell.execute_reply.started":"2025-03-24T13:20:45.468923Z","shell.execute_reply":"2025-03-24T13:20:45.609135Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"unique_eeg_ids_df = csv.drop_duplicates(subset='eeg_id')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T13:20:45.611045Z","iopub.execute_input":"2025-03-24T13:20:45.611317Z","iopub.status.idle":"2025-03-24T13:20:45.618981Z","shell.execute_reply.started":"2025-03-24T13:20:45.611294Z","shell.execute_reply":"2025-03-24T13:20:45.618098Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"unique_eeg_ids_df = unique_eeg_ids_df","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T13:20:45.619818Z","iopub.execute_input":"2025-03-24T13:20:45.620092Z","iopub.status.idle":"2025-03-24T13:20:45.626315Z","shell.execute_reply.started":"2025-03-24T13:20:45.620057Z","shell.execute_reply":"2025-03-24T13:20:45.625398Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"unique_eeg_ids_df = unique_eeg_ids_df[['eeg_id', 'expert_consensus']]\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T13:20:45.627136Z","iopub.execute_input":"2025-03-24T13:20:45.627351Z","iopub.status.idle":"2025-03-24T13:20:45.642466Z","shell.execute_reply.started":"2025-03-24T13:20:45.627333Z","shell.execute_reply":"2025-03-24T13:20:45.641577Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"unique_values = unique_eeg_ids_df['expert_consensus'].unique()\nprint(unique_values)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T13:20:45.643335Z","iopub.execute_input":"2025-03-24T13:20:45.643605Z","iopub.status.idle":"2025-03-24T13:20:45.660184Z","shell.execute_reply.started":"2025-03-24T13:20:45.643583Z","shell.execute_reply":"2025-03-24T13:20:45.659294Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"unique_eeg_ids_df","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T13:20:45.660995Z","iopub.execute_input":"2025-03-24T13:20:45.661208Z","iopub.status.idle":"2025-03-24T13:20:45.683094Z","shell.execute_reply.started":"2025-03-24T13:20:45.661188Z","shell.execute_reply":"2025-03-24T13:20:45.682203Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"labels = {0:\"Seizure\",1:\"GPD\",2:\"LRDA\",3:\"LPD\",4:\"GRDA\",5:\"Other\"}","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T13:20:45.68396Z","iopub.execute_input":"2025-03-24T13:20:45.684253Z","iopub.status.idle":"2025-03-24T13:20:45.697989Z","shell.execute_reply.started":"2025-03-24T13:20:45.68422Z","shell.execute_reply":"2025-03-24T13:20:45.697153Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras import layers, models\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T13:20:45.698832Z","iopub.execute_input":"2025-03-24T13:20:45.699094Z","iopub.status.idle":"2025-03-24T13:20:48.237891Z","shell.execute_reply.started":"2025-03-24T13:20:45.699073Z","shell.execute_reply":"2025-03-24T13:20:48.236949Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = models.Sequential([\n    layers.Conv3D(32, (3, 3, 3), activation='relu', padding='same', input_shape=(128, 256, 4, 1)),\n    layers.MaxPooling3D((2, 2, 1)),\n\n    layers.Conv3D(64, (3, 3, 3), activation='relu', padding='same'),\n    layers.MaxPooling3D((2, 2, 1)),\n\n    layers.Conv3D(128, (3, 3, 3), activation='relu', padding='same'),\n\n    layers.GlobalAveragePooling3D(),\n    layers.Dense(128, activation='relu'),\n    layers.Dropout(0.5),\n    layers.Dense(6, activation='softmax')\n])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T13:20:48.238807Z","iopub.execute_input":"2025-03-24T13:20:48.239306Z","iopub.status.idle":"2025-03-24T13:20:49.394829Z","shell.execute_reply.started":"2025-03-24T13:20:48.239281Z","shell.execute_reply":"2025-03-24T13:20:49.39392Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 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-03-24T13:20:49.395795Z","iopub.execute_input":"2025-03-24T13:20:49.396133Z","iopub.status.idle":"2025-03-24T13:20:49.406885Z","shell.execute_reply.started":"2025-03-24T13:20:49.3961Z","shell.execute_reply":"2025-03-24T13:20:49.406045Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T13:20:49.410502Z","iopub.execute_input":"2025-03-24T13:20:49.410835Z","iopub.status.idle":"2025-03-24T13:20:49.712292Z","shell.execute_reply.started":"2025-03-24T13:20:49.410812Z","shell.execute_reply":"2025-03-24T13:20:49.711294Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Önce eğitim ve geri kalan verileri (validasyon + test) ayıralım\ntrain_df, rest_df = train_test_split(unique_eeg_ids_df, test_size=0.3, random_state=42) # %30 test + validasyon\n\n# Geri kalan verileri validasyon ve test olarak ayıralım\nval_df, test_df = train_test_split(rest_df, test_size=1/3, random_state=42) # %30'un 1/3'ü test, 2/3'ü validasyon","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T13:20:49.713978Z","iopub.execute_input":"2025-03-24T13:20:49.71462Z","iopub.status.idle":"2025-03-24T13:20:49.724167Z","shell.execute_reply.started":"2025-03-24T13:20:49.714593Z","shell.execute_reply":"2025-03-24T13:20:49.723306Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import keras.utils","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T13:20:49.725207Z","iopub.execute_input":"2025-03-24T13:20:49.725491Z","iopub.status.idle":"2025-03-24T13:20:49.73173Z","shell.execute_reply.started":"2025-03-24T13:20:49.725465Z","shell.execute_reply":"2025-03-24T13:20:49.730837Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class EEGDataGenerator(keras.utils.Sequence):\n    \"\"\"\n    Data generator for EEG spectrograms for Keras.\n    Converts EEG IDs to spectrograms using the provided function and returns batches.\n    \"\"\"\n    \n    def __init__(self, dataframe, spectrogram_function, batch_size=32, \n                 shuffle=True, seed=None, is_test=False):\n        \"\"\"\n        Initialize the data generator.\n        \n        Args:\n            dataframe (pd.DataFrame): DataFrame containing 'eeg_id' and 'expert_consensus' columns\n            spectrogram_function (callable): Function that converts eeg_id to spectrogram array\n            batch_size (int): Size of batches to generate\n            shuffle (bool): Whether to shuffle the data after each epoch\n            seed (int): Random seed for reproducibility\n            is_test (bool): If True, don't return labels (for prediction)\n        \"\"\"\n        self.df = dataframe.copy()\n        self.batch_size = batch_size\n        self.spectrogram_function = spectrogram_function\n        self.shuffle = shuffle\n        self.seed = seed\n        self.is_test = is_test\n        \n        # Generate indices\n        self.indices = np.arange(len(self.df))\n        \n        # Class mapping if needed\n        self.classes = sorted(self.df['expert_consensus'].unique())\n        self.class_indices = {cls: i for i, cls in enumerate(self.classes)}\n        \n        # Initial shuffle\n        if self.shuffle:\n            np.random.seed(self.seed)\n            np.random.shuffle(self.indices)\n    \n    def __len__(self):\n        \"\"\"Denotes the number of batches per epoch\"\"\"\n        return int(np.ceil(len(self.df) / self.batch_size))\n    \n    def __getitem__(self, index):\n        \"\"\"Generate one batch of data\"\"\"\n        # Generate indices of the batch\n        batch_indices = self.indices[index * self.batch_size:(index + 1) * self.batch_size]\n        \n        # Get batch data\n        batch_df = self.df.iloc[batch_indices]\n        \n        # Generate spectrograms\n        batch_x = np.array([\n            self.spectrogram_function(eeg_id) \n            for eeg_id in batch_df['eeg_id']\n        ])\n        \n        if self.is_test:\n            return batch_x\n        \n        # Generate labels (one-hot encoded)\n        batch_y = np.array([\n            self.class_indices[label] \n            for label in batch_df['expert_consensus']\n        ])\n        \n        return batch_x, tf.keras.utils.to_categorical(batch_y, num_classes=len(self.classes))\n    \n    def on_epoch_end(self):\n        \"\"\"Updates indices after each epoch\"\"\"\n        if self.shuffle:\n            np.random.seed(self.seed)\n            np.random.shuffle(self.indices)\n\n\ndef create_eeg_generators(train_df, val_df, test_df, spectrogram_from_eeg, \n                          batch_size=32, seed=42):\n    \"\"\"\n    Create train, validation, and test generators for EEG data.\n    \n    Args:\n        train_df (pd.DataFrame): Training data with 'eeg_id' and 'expert_consensus' columns\n        val_df (pd.DataFrame): Validation data with 'eeg_id' and 'expert_consensus' columns\n        test_df (pd.DataFrame): Test data with 'eeg_id' column\n        spectrogram_from_eeg (callable): Function to convert eeg_id to spectrogram\n        batch_size (int): Batch size for generators\n        seed (int): Random seed for reproducibility\n        \n    Returns:\n        tuple: (train_generator, val_generator, test_generator)\n    \"\"\"\n    # Create generators\n    train_generator = EEGDataGenerator(\n        dataframe=train_df,\n        spectrogram_function=spectrogram_from_eeg,\n        batch_size=batch_size,\n        shuffle=True,\n        seed=seed,\n        is_test=False\n    )\n    \n    val_generator = EEGDataGenerator(\n        dataframe=val_df,\n        spectrogram_function=spectrogram_from_eeg,\n        batch_size=batch_size,\n        shuffle=False,\n        seed=seed,\n        is_test=False\n    )\n    \n    test_generator = EEGDataGenerator(\n        dataframe=test_df,\n        spectrogram_function=spectrogram_from_eeg,\n        batch_size=batch_size,\n        shuffle=False,\n        seed=seed,\n        is_test=True\n    )\n    \n    return train_generator, val_generator, test_generator","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T13:20:49.732453Z","iopub.execute_input":"2025-03-24T13:20:49.732743Z","iopub.status.idle":"2025-03-24T13:20:49.744285Z","shell.execute_reply.started":"2025-03-24T13:20:49.732721Z","shell.execute_reply":"2025-03-24T13:20:49.743468Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_generator, val_generator, test_generator = create_eeg_generators(train_df, val_df, test_df, spectrogram_from_eeg, \n                          batch_size=16, seed=42)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T13:20:49.744937Z","iopub.execute_input":"2025-03-24T13:20:49.745138Z","iopub.status.idle":"2025-03-24T13:20:49.762964Z","shell.execute_reply.started":"2025-03-24T13:20:49.745119Z","shell.execute_reply":"2025-03-24T13:20:49.762193Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T13:20:49.763668Z","iopub.execute_input":"2025-03-24T13:20:49.763856Z","iopub.status.idle":"2025-03-24T13:20:49.778976Z","shell.execute_reply.started":"2025-03-24T13:20:49.763839Z","shell.execute_reply":"2025-03-24T13:20:49.778364Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T13:20:49.779696Z","iopub.execute_input":"2025-03-24T13:20:49.779883Z","iopub.status.idle":"2025-03-24T13:20:49.799755Z","shell.execute_reply.started":"2025-03-24T13:20:49.779866Z","shell.execute_reply":"2025-03-24T13:20:49.798898Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# # Train ve validation generator oluşturma\n# train_generator = eeg_data_generator(train_df, batch_size=16)\n# val_generator = eeg_data_generator(val_df, batch_size=16)\n# test_generator = eeg_data_generator(test_df, batch_size=16)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T13:20:49.800453Z","iopub.execute_input":"2025-03-24T13:20:49.800711Z","iopub.status.idle":"2025-03-24T13:20:49.804283Z","shell.execute_reply.started":"2025-03-24T13:20:49.800691Z","shell.execute_reply":"2025-03-24T13:20:49.803403Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import tensorflow as tf\nprint(\"GPU Available:\", tf.config.list_physical_devices('GPU'))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T13:20:49.805101Z","iopub.execute_input":"2025-03-24T13:20:49.805419Z","iopub.status.idle":"2025-03-24T13:20:49.821251Z","shell.execute_reply.started":"2025-03-24T13:20:49.805387Z","shell.execute_reply":"2025-03-24T13:20:49.82028Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Train the model\nhistory = model.fit(\n    train_generator,\n    validation_data=val_generator,\n    epochs=10\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T13:20:49.821934Z","iopub.execute_input":"2025-03-24T13:20:49.822229Z","iopub.status.idle":"2025-03-24T17:44:33.132187Z","shell.execute_reply.started":"2025-03-24T13:20:49.822198Z","shell.execute_reply":"2025-03-24T17:44:33.13141Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_df\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T17:44:33.133165Z","iopub.execute_input":"2025-03-24T17:44:33.133866Z","iopub.status.idle":"2025-03-24T17:44:33.142053Z","shell.execute_reply.started":"2025-03-24T17:44:33.133837Z","shell.execute_reply":"2025-03-24T17:44:33.141423Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def predict_for_eeg_id(model, eeg_id, spectrogram_from_eeg, class_mapping=None):\n    \"\"\"\n    Tek bir EEG ID için tahmin yapar.\n    \n    Args:\n        model: Eğitilmiş Keras modeli\n        eeg_id: Tahmin yapılacak EEG ID'si\n        spectrogram_from_eeg: EEG ID'yi spektrograma dönüştüren fonksiyon\n        class_mapping: Sınıf indekslerinden sınıf adlarına eşleştirme sözlüğü\n        \n    Returns:\n        dict: Tahmin sonuçları\n    \"\"\"\n    # EEG ID'den spectrogram oluştur\n    spectrogram = spectrogram_from_eeg(eeg_id)\n    \n    # Batch boyutu için yeniden şekillendir\n    spectrogram_batch = np.expand_dims(spectrogram, axis=0)\n    \n    # Tahmin yap\n    prediction = model.predict(spectrogram_batch, verbose=0)\n    \n    # En yüksek olasılığa sahip sınıfı bul\n    predicted_class_index = np.argmax(prediction[0])\n    prediction_confidence = prediction[0][predicted_class_index]\n    \n    # Eğer sınıf eşleştirmesi sağlandıysa, sınıf adını bul\n    if class_mapping:\n        predicted_class = class_mapping.get(predicted_class_index, f\"Sınıf {predicted_class_index}\")\n    else:\n        predicted_class = f\"Sınıf {predicted_class_index}\"\n    \n    # Sonuçları döndür\n    return {\n        \"eeg_id\": eeg_id,\n        \"predicted_class\": predicted_class,\n        \"predicted_class_index\": predicted_class_index,\n        \"confidence\": float(prediction_confidence),\n        \"all_probabilities\": {i: float(p) for i, p in enumerate(prediction[0])}\n    }","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T17:44:33.142729Z","iopub.execute_input":"2025-03-24T17:44:33.142926Z","iopub.status.idle":"2025-03-24T17:44:33.158552Z","shell.execute_reply.started":"2025-03-24T17:44:33.142908Z","shell.execute_reply":"2025-03-24T17:44:33.157793Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"predict_for_eeg_id(model,2292521648\t\t,spectrogram_from_eeg)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T17:44:33.159231Z","iopub.execute_input":"2025-03-24T17:44:33.159459Z","iopub.status.idle":"2025-03-24T17:44:33.77397Z","shell.execute_reply.started":"2025-03-24T17:44:33.15944Z","shell.execute_reply":"2025-03-24T17:44:33.77299Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.save(\"m1.h5\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T17:44:33.774912Z","iopub.execute_input":"2025-03-24T17:44:33.775162Z","iopub.status.idle":"2025-03-24T17:44:33.82151Z","shell.execute_reply.started":"2025-03-24T17:44:33.775138Z","shell.execute_reply":"2025-03-24T17:44:33.820583Z"}},"outputs":[],"execution_count":null}]}