Upload 7 files
#1
by
NextGenC
- opened
- .gitattributes +1 -0
- egg_zayn.py +608 -0
- fingerprint.pb +3 -0
- keras_metadata.pb +3 -0
- saved_model.pb +3 -0
- test.py +22 -0
- variables.data-00000-of-00001 +3 -0
- variables.index +0 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
variables.data-00000-of-00001 filter=lfs diff=lfs merge=lfs -text
|
egg_zayn.py
ADDED
|
@@ -0,0 +1,608 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
EggZayn v9.4 - Sonsuz EEG Zekası (Nihai Sürüm)
|
| 3 |
+
- EEGMMIDB ve her EEG verisini hatasız işler, ultra gelişmiş analiz sunar.
|
| 4 |
+
- Contrastive loss yeniden yazıldı, TFA bağımlılığı kaldırıldı.
|
| 5 |
+
- Kullanım: python egg_zayn_gui_v9_4.py
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import os
|
| 9 |
+
import sys
|
| 10 |
+
import numpy as np
|
| 11 |
+
import mne
|
| 12 |
+
from mne.datasets import eegbci
|
| 13 |
+
from sklearn.model_selection import train_test_split
|
| 14 |
+
from sklearn.metrics import confusion_matrix, classification_report
|
| 15 |
+
import tensorflow as tf
|
| 16 |
+
from tensorflow.keras import layers, models
|
| 17 |
+
import tkinter as tk
|
| 18 |
+
from tkinter import filedialog, messagebox, ttk
|
| 19 |
+
import matplotlib.pyplot as plt
|
| 20 |
+
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
|
| 21 |
+
import seaborn as sns
|
| 22 |
+
import threading
|
| 23 |
+
import time
|
| 24 |
+
import psutil
|
| 25 |
+
import datetime
|
| 26 |
+
import warnings
|
| 27 |
+
|
| 28 |
+
# Uyarıları bastır
|
| 29 |
+
warnings.filterwarnings("ignore", category=RuntimeWarning)
|
| 30 |
+
|
| 31 |
+
# Bağımlılık kontrolü
|
| 32 |
+
required_libs = ['mne', 'numpy', 'sklearn', 'tensorflow', 'matplotlib', 'seaborn', 'psutil']
|
| 33 |
+
for lib in required_libs:
|
| 34 |
+
try:
|
| 35 |
+
__import__(lib)
|
| 36 |
+
except ImportError:
|
| 37 |
+
print(f"Hata: {lib} kütüphanesi eksik. Lütfen kurun: pip install {lib}")
|
| 38 |
+
sys.exit(1)
|
| 39 |
+
|
| 40 |
+
# Mixed precision optimizasyonu
|
| 41 |
+
tf.keras.mixed_precision.set_global_policy('mixed_float16')
|
| 42 |
+
|
| 43 |
+
# Veri artırma ve contrastive learning için çiftler
|
| 44 |
+
def augment_data(X, noise_factor=0.01):
|
| 45 |
+
X_aug = X.copy()
|
| 46 |
+
noise = np.random.normal(0, noise_factor, X.shape)
|
| 47 |
+
X_aug += noise
|
| 48 |
+
return X_aug
|
| 49 |
+
|
| 50 |
+
def create_contrastive_pairs(X):
|
| 51 |
+
X_pos = augment_data(X)
|
| 52 |
+
X_neg = np.roll(X, shift=1, axis=0)
|
| 53 |
+
return X_pos, X_neg
|
| 54 |
+
|
| 55 |
+
# EggZayn v9.4 Modeli
|
| 56 |
+
class EggZaynModel:
|
| 57 |
+
def __init__(self):
|
| 58 |
+
self.model = None
|
| 59 |
+
self.class_names = ['Left Fist', 'Right Fist', 'Both Fists', 'Both Feet']
|
| 60 |
+
self.history = None
|
| 61 |
+
|
| 62 |
+
def prepare_eegmmidb_data(self, epoch_duration=1.0, target_sfreq=160):
|
| 63 |
+
"""EEGMMIDB verisini hatasız ve boyut uyumlu şekilde işler."""
|
| 64 |
+
data_dir = './eeg_data'
|
| 65 |
+
subjects = range(1, 110)
|
| 66 |
+
runs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
|
| 67 |
+
|
| 68 |
+
print("EggZayn: EEGMMIDB verisi hazırlanıyor...")
|
| 69 |
+
os.makedirs(data_dir, exist_ok=True)
|
| 70 |
+
total_files = len(subjects) * len(runs)
|
| 71 |
+
processed_files = 0
|
| 72 |
+
|
| 73 |
+
raw_list = []
|
| 74 |
+
motor_channels = ['Fc3', 'Fc4', 'C3', 'C4', 'Cz', 'Cp3', 'Cp4']
|
| 75 |
+
for subject in subjects:
|
| 76 |
+
for run in runs:
|
| 77 |
+
file_path = f"{data_dir}/S{subject:03d}/S{subject:03d}R{run:02d}.edf"
|
| 78 |
+
if not os.path.exists(file_path):
|
| 79 |
+
continue
|
| 80 |
+
|
| 81 |
+
try:
|
| 82 |
+
raw = mne.io.read_raw_edf(file_path, preload=True, verbose=False)
|
| 83 |
+
raw.resample(target_sfreq, npad='auto', verbose=False)
|
| 84 |
+
|
| 85 |
+
raw.notch_filter(60, verbose=False)
|
| 86 |
+
raw.filter(8, 30, fir_design='firwin', verbose=False)
|
| 87 |
+
|
| 88 |
+
available_channels = [ch for ch in raw.ch_names if any(mc.upper() in ch.upper() for mc in motor_channels)]
|
| 89 |
+
if len(available_channels) < 1:
|
| 90 |
+
raise ValueError(f"Denek {subject}, Run {run}: Hiç motor kanal bulunamadı.")
|
| 91 |
+
|
| 92 |
+
raw.pick(available_channels)
|
| 93 |
+
if len(available_channels) < 7:
|
| 94 |
+
raw.set_montage('standard_1020')
|
| 95 |
+
missing_channels = [ch for ch in motor_channels if ch not in available_channels]
|
| 96 |
+
raw.interpolate_bads(reset_bads=True, mode='accurate', exclude=missing_channels)
|
| 97 |
+
raw.pick(motor_channels)
|
| 98 |
+
|
| 99 |
+
events = mne.make_fixed_length_events(raw, duration=epoch_duration)
|
| 100 |
+
labels = self.assign_labels(run, len(events))
|
| 101 |
+
raw_list.append((raw, events, labels))
|
| 102 |
+
processed_files += 1
|
| 103 |
+
print(f"İlerleme: {processed_files}/{total_files}")
|
| 104 |
+
except Exception as e:
|
| 105 |
+
print(f"Hata: Denek {subject}, Run {run} işlenemedi: {e}")
|
| 106 |
+
continue
|
| 107 |
+
|
| 108 |
+
if not raw_list:
|
| 109 |
+
raise ValueError("EggZayn: Hiçbir veri işlenemedi, veri setinde ciddi bir sorun var.")
|
| 110 |
+
|
| 111 |
+
X_all, Y_all = [], []
|
| 112 |
+
expected_samples = int(target_sfreq * epoch_duration) # 160 Hz * 1 sn = 160 örnek
|
| 113 |
+
for raw, events, labels in raw_list:
|
| 114 |
+
epochs = mne.Epochs(raw, events, tmin=0, tmax=epoch_duration, baseline=None, preload=True, verbose=False)
|
| 115 |
+
X = epochs.get_data(picks='eeg')
|
| 116 |
+
if X.shape[2] != expected_samples:
|
| 117 |
+
X_resampled = np.zeros((X.shape[0], X.shape[1], expected_samples))
|
| 118 |
+
for i in range(X.shape[0]):
|
| 119 |
+
for j in range(X.shape[1]):
|
| 120 |
+
X_resampled[i, j, :] = np.interp(
|
| 121 |
+
np.linspace(0, 1, expected_samples),
|
| 122 |
+
np.linspace(0, 1, X.shape[2]),
|
| 123 |
+
X[i, j, :]
|
| 124 |
+
)
|
| 125 |
+
X = X_resampled
|
| 126 |
+
X = (X - X.min(axis=2, keepdims=True)) / (X.max(axis=2, keepdims=True) - X.min(axis=2, keepdims=True))
|
| 127 |
+
|
| 128 |
+
# Veri ve etiket eşitleme
|
| 129 |
+
if X.shape[0] != len(labels):
|
| 130 |
+
min_len = min(X.shape[0], len(labels))
|
| 131 |
+
X = X[:min_len]
|
| 132 |
+
labels = labels[:min_len]
|
| 133 |
+
print(f"Uyarı: Veri ve etiket eşitlemesi yapıldı. Yeni boyut: {min_len}")
|
| 134 |
+
|
| 135 |
+
X_all.append(X)
|
| 136 |
+
Y_all.append(labels)
|
| 137 |
+
|
| 138 |
+
X = np.concatenate(X_all, axis=0)
|
| 139 |
+
Y = np.concatenate(Y_all, axis=0)
|
| 140 |
+
|
| 141 |
+
# Son eşitleme kontrolü
|
| 142 |
+
if X.shape[0] != len(Y):
|
| 143 |
+
min_len = min(X.shape[0], len(Y))
|
| 144 |
+
X = X[:min_len]
|
| 145 |
+
Y = Y[:min_len]
|
| 146 |
+
print(f"Uyarı: Son eşitleme yapıldı. Yeni boyut: {min_len}")
|
| 147 |
+
|
| 148 |
+
unique, counts = np.unique(Y, return_counts=True)
|
| 149 |
+
print(f"EggZayn: Sınıf dağılımı: {dict(zip(unique, counts))}")
|
| 150 |
+
|
| 151 |
+
X_train, X_temp, Y_train, Y_temp = train_test_split(X, Y, test_size=0.3, random_state=42, stratify=Y)
|
| 152 |
+
X_val, X_test, Y_val, Y_test = train_test_split(X_temp, Y_temp, test_size=0.5, random_state=42, stratify=Y_temp)
|
| 153 |
+
|
| 154 |
+
np.save('X_train.npy', X_train)
|
| 155 |
+
np.save('Y_train.npy', Y_train)
|
| 156 |
+
np.save('X_val.npy', X_val)
|
| 157 |
+
np.save('Y_val.npy', Y_val)
|
| 158 |
+
np.save('X_test.npy', X_test)
|
| 159 |
+
np.save('Y_test.npy', Y_test)
|
| 160 |
+
|
| 161 |
+
print(f"EggZayn: Veri hazır: {X.shape[0]} örnek, Şekil: {X.shape}")
|
| 162 |
+
return X_train, Y_train, X_val, Y_val, X_test, Y_test
|
| 163 |
+
|
| 164 |
+
def assign_labels(self, run, num_events):
|
| 165 |
+
"""Optimize edilmiş etiket atama."""
|
| 166 |
+
label_map = {
|
| 167 |
+
(1, 2): 0, # Baseline
|
| 168 |
+
(3, 5, 7): [0, 1], # Sol/Sağ yumruk
|
| 169 |
+
(4, 6, 8): [0, 1], # Sol/Sağ imagery
|
| 170 |
+
(9, 11, 13): [2, 3], # Her iki yumruk/ayak
|
| 171 |
+
(10, 12, 14): [2, 3] # Her iki yumruk/ayak imagery
|
| 172 |
+
}
|
| 173 |
+
for runs, labels in label_map.items():
|
| 174 |
+
if run in runs:
|
| 175 |
+
if isinstance(labels, int):
|
| 176 |
+
return np.full(num_events, labels, dtype=int)
|
| 177 |
+
return np.array([labels[i % 2] for i in range(num_events)])
|
| 178 |
+
raise ValueError(f"Geçersiz run numarası: {run}")
|
| 179 |
+
|
| 180 |
+
def process_signal(self, signal_data, epoch_duration=1.0, target_sfreq=160):
|
| 181 |
+
"""Anlık sinyal veya dosya girişini hatasız ve ultra gelişmiş yöntemlerle işler."""
|
| 182 |
+
if isinstance(signal_data, str):
|
| 183 |
+
raw = mne.io.read_raw(signal_data, preload=True, verbose=False)
|
| 184 |
+
else:
|
| 185 |
+
if not isinstance(signal_data, np.ndarray):
|
| 186 |
+
raise ValueError("EggZayn: Anlık sinyal numpy array olmalı.")
|
| 187 |
+
info = mne.create_info(ch_names=['Fc3', 'Fc4', 'C3', 'C4', 'Cz', 'Cp3', 'Cp4'], sfreq=target_sfreq, ch_types='eeg')
|
| 188 |
+
raw = mne.io.RawArray(signal_data, info)
|
| 189 |
+
|
| 190 |
+
if raw.info['sfreq'] != target_sfreq:
|
| 191 |
+
raw.resample(target_sfreq, npad='auto', verbose=False)
|
| 192 |
+
|
| 193 |
+
raw.notch_filter(60, verbose=False)
|
| 194 |
+
raw.filter(8, 30, fir_design='firwin', verbose=False)
|
| 195 |
+
|
| 196 |
+
available_channels = [ch for ch in raw.ch_names if ch.upper() in ['FC3', 'FC4', 'C3', 'C4', 'CZ', 'CP3', 'CP4']]
|
| 197 |
+
if len(available_channels) < 1:
|
| 198 |
+
raise ValueError("EggZayn: Hiç motor kanal bulunamadı.")
|
| 199 |
+
|
| 200 |
+
raw.pick(available_channels)
|
| 201 |
+
if len(available_channels) < 7:
|
| 202 |
+
raw.set_montage('standard_1020')
|
| 203 |
+
missing_channels = [ch for ch in ['Fc3', 'Fc4', 'C3', 'C4', 'Cz', 'Cp3', 'Cp4'] if ch not in available_channels]
|
| 204 |
+
raw.interpolate_bads(reset_bads=True, mode='accurate', exclude=missing_channels)
|
| 205 |
+
raw.pick(['Fc3', 'Fc4', 'C3', 'C4', 'Cz', 'Cp3', 'Cp4'])
|
| 206 |
+
|
| 207 |
+
events = mne.make_fixed_length_events(raw, duration=epoch_duration)
|
| 208 |
+
epochs = mne.Epochs(raw, events, tmin=0, tmax=epoch_duration, baseline=None, preload=True, verbose=False)
|
| 209 |
+
X = epochs.get_data(picks='eeg')
|
| 210 |
+
expected_samples = int(target_sfreq * epoch_duration)
|
| 211 |
+
if X.shape[2] != expected_samples:
|
| 212 |
+
X_resampled = np.zeros((X.shape[0], X.shape[1], expected_samples))
|
| 213 |
+
for i in range(X.shape[0]):
|
| 214 |
+
for j in range(X.shape[1]):
|
| 215 |
+
X_resampled[i, j, :] = np.interp(
|
| 216 |
+
np.linspace(0, 1, expected_samples),
|
| 217 |
+
np.linspace(0, 1, X.shape[2]),
|
| 218 |
+
X[i, j, :]
|
| 219 |
+
)
|
| 220 |
+
X = X_resampled
|
| 221 |
+
X = (X - X.min(axis=2, keepdims=True)) / (X.max(axis=2, keepdims=True) - X.min(axis=2, keepdims=True))
|
| 222 |
+
return X
|
| 223 |
+
|
| 224 |
+
def build_transformer_block(self, x, num_heads=4, key_dim=32, ff_dim=64):
|
| 225 |
+
attn_output = layers.MultiHeadAttention(num_heads=num_heads, key_dim=key_dim)(x, x)
|
| 226 |
+
x = layers.Add()([x, attn_output])
|
| 227 |
+
x = layers.LayerNormalization(epsilon=1e-6)(x)
|
| 228 |
+
ffn = layers.Dense(ff_dim, activation='gelu')(x)
|
| 229 |
+
ffn = layers.Dense(x.shape[-1])(ffn)
|
| 230 |
+
x = layers.Add()([x, ffn])
|
| 231 |
+
x = layers.LayerNormalization(epsilon=1e-6)(x)
|
| 232 |
+
return x
|
| 233 |
+
|
| 234 |
+
def build_encoder(self, input_shape):
|
| 235 |
+
"""Geliştirilmiş encoder for contrastive learning."""
|
| 236 |
+
inputs = layers.Input(shape=input_shape)
|
| 237 |
+
x = layers.Dense(32, activation='gelu')(inputs)
|
| 238 |
+
x = layers.Dropout(0.05)(x)
|
| 239 |
+
|
| 240 |
+
for _ in range(4):
|
| 241 |
+
x = self.build_transformer_block(x)
|
| 242 |
+
|
| 243 |
+
x = layers.GlobalAveragePooling1D()(x)
|
| 244 |
+
x = layers.Dense(128, activation='gelu')(x)
|
| 245 |
+
outputs = layers.Dense(64)(x)
|
| 246 |
+
|
| 247 |
+
return models.Model(inputs, outputs)
|
| 248 |
+
|
| 249 |
+
def contrastive_loss(self, labels, z1, z2, margin=1.0):
|
| 250 |
+
"""Kendi contrastive loss fonksiyonumuz."""
|
| 251 |
+
# Türleri float32'ye çevir
|
| 252 |
+
labels = tf.cast(labels, tf.float32)
|
| 253 |
+
z1 = tf.cast(z1, tf.float32)
|
| 254 |
+
z2 = tf.cast(z2, tf.float32)
|
| 255 |
+
margin = tf.cast(margin, tf.float32)
|
| 256 |
+
|
| 257 |
+
# Mesafeleri hesapla
|
| 258 |
+
squared_distance = tf.reduce_sum(tf.square(z1 - z2), axis=-1)
|
| 259 |
+
distance = tf.sqrt(squared_distance + tf.keras.backend.epsilon())
|
| 260 |
+
|
| 261 |
+
# Pozitif ve negatif çiftler için kayıp
|
| 262 |
+
positive_loss = labels * squared_distance
|
| 263 |
+
negative_loss = (1 - labels) * tf.square(tf.maximum(margin - distance, 0))
|
| 264 |
+
loss = 0.5 * (positive_loss + negative_loss)
|
| 265 |
+
return tf.reduce_mean(loss)
|
| 266 |
+
|
| 267 |
+
def pretrain(self, X_train, epochs=3):
|
| 268 |
+
"""Contrastive learning ile pretraining."""
|
| 269 |
+
encoder = self.build_encoder(X_train.shape[1:])
|
| 270 |
+
X_pos, X_neg = create_contrastive_pairs(X_train)
|
| 271 |
+
|
| 272 |
+
inputs1 = layers.Input(shape=X_train.shape[1:])
|
| 273 |
+
inputs2 = layers.Input(shape=X_train.shape[1:])
|
| 274 |
+
z1 = encoder(inputs1)
|
| 275 |
+
z2 = encoder(inputs2)
|
| 276 |
+
model = models.Model([inputs1, inputs2], [z1, z2])
|
| 277 |
+
|
| 278 |
+
optimizer = tf.keras.optimizers.Adam(learning_rate=1e-3)
|
| 279 |
+
|
| 280 |
+
# Kendi loss fonksiyonumuzu kullanarak modeli derle
|
| 281 |
+
@tf.function
|
| 282 |
+
def train_step(X1, X2, labels):
|
| 283 |
+
with tf.GradientTape() as tape:
|
| 284 |
+
z1, z2 = model([X1, X2], training=True)
|
| 285 |
+
loss = self.contrastive_loss(labels, z1, z2)
|
| 286 |
+
gradients = tape.gradient(loss, model.trainable_variables)
|
| 287 |
+
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
|
| 288 |
+
return loss
|
| 289 |
+
|
| 290 |
+
# Eğitim döngüsü
|
| 291 |
+
batch_size = 128
|
| 292 |
+
for epoch in range(epochs):
|
| 293 |
+
print(f"Epoch {epoch+1}/{epochs}")
|
| 294 |
+
for i in range(0, len(X_pos), batch_size):
|
| 295 |
+
X1_batch = X_pos[i:i+batch_size]
|
| 296 |
+
X2_batch = X_neg[i:i+batch_size]
|
| 297 |
+
labels_batch = np.ones(len(X1_batch))
|
| 298 |
+
loss = train_step(X1_batch, X2_batch, labels_batch)
|
| 299 |
+
print(f"Batch {i//batch_size+1}: Loss = {loss.numpy():.4f}")
|
| 300 |
+
|
| 301 |
+
return encoder
|
| 302 |
+
|
| 303 |
+
def train(self, X_train, Y_train, X_val, Y_val, save_path='EggZayn_final.h9_4'):
|
| 304 |
+
"""Ultra gelişmiş ve hatasız eğitim."""
|
| 305 |
+
encoder = self.pretrain(X_train)
|
| 306 |
+
inputs = layers.Input(shape=X_train.shape[1:])
|
| 307 |
+
x = encoder(inputs)
|
| 308 |
+
x = layers.Dense(256, activation='gelu')(x)
|
| 309 |
+
x = layers.Dropout(0.05)(x)
|
| 310 |
+
outputs = layers.Dense(4, activation='softmax', dtype='float32')(x)
|
| 311 |
+
self.model = models.Model(inputs, outputs)
|
| 312 |
+
|
| 313 |
+
optimizer = tf.keras.optimizers.Adam(learning_rate=2e-4)
|
| 314 |
+
self.model.compile(optimizer=optimizer, loss='sparse_categorical_crossentropy', metrics=['accuracy'])
|
| 315 |
+
|
| 316 |
+
callbacks = [
|
| 317 |
+
tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=2, restore_best_weights=True),
|
| 318 |
+
tf.keras.callbacks.ModelCheckpoint(save_path, save_best_only=True, monitor='val_accuracy', mode='max'),
|
| 319 |
+
tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=1, min_lr=1e-6)
|
| 320 |
+
]
|
| 321 |
+
|
| 322 |
+
self.history = self.model.fit(X_train, Y_train, epochs=10, batch_size=128,
|
| 323 |
+
validation_data=(X_val, Y_val), callbacks=callbacks, verbose=1)
|
| 324 |
+
|
| 325 |
+
converter = tf.lite.TFLiteConverter.from_keras_model(self.model)
|
| 326 |
+
tflite_model = converter.convert()
|
| 327 |
+
with open(save_path.replace('.h9_4', '.tflite'), 'wb') as f:
|
| 328 |
+
f.write(tflite_model)
|
| 329 |
+
|
| 330 |
+
print(f"EggZayn: Model {save_path} ve {save_path.replace('.h9_4', '.tflite')} olarak kaydedildi.")
|
| 331 |
+
return self.history
|
| 332 |
+
|
| 333 |
+
def evaluate(self, X_test, Y_test):
|
| 334 |
+
if self.model is None:
|
| 335 |
+
raise ValueError("EggZayn: Model eğitilmedi veya yüklenmedi.")
|
| 336 |
+
|
| 337 |
+
loss, accuracy = self.model.evaluate(X_test, Y_test, verbose=0)
|
| 338 |
+
Y_pred = np.argmax(self.model.predict(X_test, verbose=0), axis=1)
|
| 339 |
+
report = classification_report(Y_test, Y_pred, target_names=self.class_names)
|
| 340 |
+
cm = confusion_matrix(Y_test, Y_pred)
|
| 341 |
+
return loss, accuracy, report, cm
|
| 342 |
+
|
| 343 |
+
def predict(self, signal_input):
|
| 344 |
+
"""Prompt tabanlı, ultra gelişmiş tahmin ve raporlama."""
|
| 345 |
+
if self.model is None:
|
| 346 |
+
if os.path.exists('EggZayn_final.h9_4'):
|
| 347 |
+
self.model = tf.keras.models.load_model('EggZayn_final.h9_4')
|
| 348 |
+
else:
|
| 349 |
+
raise ValueError("EggZayn: Model bulunamadı.")
|
| 350 |
+
|
| 351 |
+
start_time = time.time()
|
| 352 |
+
X_processed = self.process_signal(signal_input)
|
| 353 |
+
predictions = self.model.predict(X_processed, verbose=0)
|
| 354 |
+
predicted_classes = np.argmax(predictions, axis=1)
|
| 355 |
+
probabilities = [max(prob) for prob in predictions]
|
| 356 |
+
analysis_time = time.time() - start_time
|
| 357 |
+
|
| 358 |
+
results = [(self.class_names[pred], prob) for pred, prob in zip(predicted_classes, probabilities)]
|
| 359 |
+
|
| 360 |
+
# Profesyonel raporlama
|
| 361 |
+
report = f"Analiz Raporu - {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n"
|
| 362 |
+
report += f"Toplam Örnek: {len(results)}\n"
|
| 363 |
+
report += f"Analiz Süresi: {analysis_time:.3f} saniye\n"
|
| 364 |
+
report += "Sonuçlar:\n"
|
| 365 |
+
for i, (label, prob) in enumerate(results):
|
| 366 |
+
report += f"Örnek {i+1}: {label} (Güven: {prob*100:.2f}%)\n"
|
| 367 |
+
|
| 368 |
+
return results, report
|
| 369 |
+
|
| 370 |
+
def load_model(self, model_path='EggZayn_final.h9_4'):
|
| 371 |
+
self.model = tf.keras.models.load_model(model_path)
|
| 372 |
+
print(f"EggZayn: Model {model_path} yüklendi.")
|
| 373 |
+
|
| 374 |
+
# GUI: EggZaynGUI
|
| 375 |
+
class EggZaynGUI:
|
| 376 |
+
def __init__(self, root):
|
| 377 |
+
self.root = root
|
| 378 |
+
self.root.title("EggZayn v9.4 - Sonsuz EEG Zekası")
|
| 379 |
+
self.root.geometry("1200x900")
|
| 380 |
+
self.root.configure(bg='#1A2526')
|
| 381 |
+
|
| 382 |
+
self.model = EggZaynModel()
|
| 383 |
+
self.X_train, self.Y_train = None, None
|
| 384 |
+
self.X_val, self.Y_val = None, None
|
| 385 |
+
self.X_test, self.Y_test = None, None
|
| 386 |
+
|
| 387 |
+
self.create_widgets()
|
| 388 |
+
|
| 389 |
+
def create_widgets(self):
|
| 390 |
+
style = ttk.Style()
|
| 391 |
+
style.configure('TButton', font=('Arial', 14, 'bold'), background='#00A8E8', foreground='white')
|
| 392 |
+
style.configure('TLabel', font=('Arial', 12), background='#1A2526', foreground='#ECF0F1')
|
| 393 |
+
|
| 394 |
+
top_frame = ttk.Frame(self.root)
|
| 395 |
+
top_frame.pack(pady=20)
|
| 396 |
+
|
| 397 |
+
ttk.Button(top_frame, text="EggZayn'ı Eğit (EEGMMIDB)", command=self.run_full_process_thread).pack(side=tk.LEFT, padx=10)
|
| 398 |
+
ttk.Button(top_frame, text="Kendi Veri Setimle Eğit", command=self.run_custom_train_thread).pack(side=tk.LEFT, padx=10)
|
| 399 |
+
ttk.Button(top_frame, text="Sinyal Analiz Et", command=self.predict_new_data).pack(side=tk.LEFT, padx=10)
|
| 400 |
+
|
| 401 |
+
self.status_label = ttk.Label(self.root, text="Durum: Hazır")
|
| 402 |
+
self.status_label.pack(pady=10)
|
| 403 |
+
|
| 404 |
+
self.progress = ttk.Progressbar(self.root, length=500, mode='determinate')
|
| 405 |
+
self.progress.pack(pady=10)
|
| 406 |
+
|
| 407 |
+
self.result_frame = ttk.Frame(self.root)
|
| 408 |
+
self.result_frame.pack(pady=10, fill=tk.BOTH, expand=True)
|
| 409 |
+
self.result_text = tk.Text(self.result_frame, height=15, width=100, bg='#ECF0F1', fg='#2C3E50', font=('Arial', 11))
|
| 410 |
+
self.result_text.pack(pady=5, padx=5)
|
| 411 |
+
|
| 412 |
+
self.fig, (self.ax1, self.ax2) = plt.subplots(1, 2, figsize=(12, 5), dpi=100)
|
| 413 |
+
self.fig.patch.set_facecolor('#1A2526')
|
| 414 |
+
self.canvas = FigureCanvasTkAgg(self.fig, master=self.root)
|
| 415 |
+
self.canvas.get_tk_widget().pack(pady=10)
|
| 416 |
+
self.toolbar = NavigationToolbar2Tk(self.canvas, self.root)
|
| 417 |
+
self.toolbar.update()
|
| 418 |
+
self.toolbar.pack()
|
| 419 |
+
|
| 420 |
+
def full_process(self):
|
| 421 |
+
self.status_label.config(text="EggZayn: Veri hazırlama aşaması...")
|
| 422 |
+
self.progress['value'] = 0
|
| 423 |
+
self.root.update()
|
| 424 |
+
|
| 425 |
+
self.result_text.delete(1.0, tk.END)
|
| 426 |
+
self.result_text.insert(tk.END, "EggZayn: EEGMMIDB hazırlanıyor...\n")
|
| 427 |
+
self.root.update()
|
| 428 |
+
start_time = time.time()
|
| 429 |
+
try:
|
| 430 |
+
X_train, Y_train, X_val, Y_val, X_test, Y_test = self.model.prepare_eegmmidb_data()
|
| 431 |
+
self.X_train, self.Y_train = X_train, Y_train
|
| 432 |
+
self.X_val, self.Y_val = X_val, Y_val
|
| 433 |
+
self.X_test, self.Y_test = X_test, Y_test
|
| 434 |
+
self.progress['value'] = 33
|
| 435 |
+
self.result_text.insert(tk.END, f"EggZayn: Veri hazır! Süre: {time.time() - start_time:.2f} saniye\n")
|
| 436 |
+
except Exception as e:
|
| 437 |
+
self.result_text.insert(tk.END, f"Hata: Veri hazırlama başarısız: {e}\n")
|
| 438 |
+
messagebox.showerror("Hata", f"EggZayn: Veri hazırlama başarısız: {e}")
|
| 439 |
+
return
|
| 440 |
+
|
| 441 |
+
self.status_label.config(text="EggZayn: Model eğitim aşaması...")
|
| 442 |
+
self.result_text.insert(tk.END, "EggZayn: Model eğitiliyor...\n")
|
| 443 |
+
self.root.update()
|
| 444 |
+
start_time = time.time()
|
| 445 |
+
try:
|
| 446 |
+
self.model.train(self.X_train, self.Y_train, self.X_val, self.Y_val)
|
| 447 |
+
self.progress['value'] = 66
|
| 448 |
+
self.result_text.insert(tk.END, f"EggZayn: Eğitim tamamlandı! Süre: {time.time() - start_time:.2f} saniye\n")
|
| 449 |
+
self.update_training_plot()
|
| 450 |
+
except Exception as e:
|
| 451 |
+
self.result_text.insert(tk.END, f"Hata: Eğitim başarısız: {e}\n")
|
| 452 |
+
messagebox.showerror("Hata", f"EggZayn: Eğitim başarısız: {e}")
|
| 453 |
+
return
|
| 454 |
+
|
| 455 |
+
self.status_label.config(text="EggZayn: Değerlendirme aşaması...")
|
| 456 |
+
self.result_text.insert(tk.END, "EggZayn: Model değerlendiriliyor...\n")
|
| 457 |
+
self.root.update()
|
| 458 |
+
start_time = time.time()
|
| 459 |
+
try:
|
| 460 |
+
loss, accuracy, report, cm = self.model.evaluate(self.X_test, self.Y_test)
|
| 461 |
+
self.progress['value'] = 100
|
| 462 |
+
self.result_text.insert(tk.END, f"EggZayn: Değerlendirme tamamlandı! Süre: {time.time() - start_time:.2f} saniye\n")
|
| 463 |
+
self.result_text.insert(tk.END, f"\nTest Loss: {loss:.4f}\nTest Accuracy: {accuracy:.4f}\n\nClassification Report:\n{report}\n")
|
| 464 |
+
|
| 465 |
+
self.ax2.clear()
|
| 466 |
+
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=self.model.class_names, yticklabels=self.model.class_names, ax=self.ax2)
|
| 467 |
+
self.ax2.set_title('EggZayn Confusion Matrix', color='white')
|
| 468 |
+
self.ax2.set_xlabel('Predicted', color='white')
|
| 469 |
+
self.ax2.set_ylabel('True', color='white')
|
| 470 |
+
self.ax2.tick_params(colors='white')
|
| 471 |
+
self.canvas.draw()
|
| 472 |
+
|
| 473 |
+
self.status_label.config(text="EggZayn: Model hazır ve şölen tamamlandı!")
|
| 474 |
+
except Exception as e:
|
| 475 |
+
self.result_text.insert(tk.END, f"Hata: Değerlendirme başarısız: {e}\n")
|
| 476 |
+
messagebox.showerror("Hata", f"EggZayn: Değerlendirme başarısız: {e}")
|
| 477 |
+
|
| 478 |
+
def custom_train(self):
|
| 479 |
+
file_path = filedialog.askopenfilename(title="EEG Veri Dosyasını Seç (EDF veya NumPy)",
|
| 480 |
+
filetypes=[("EDF files", "*.edf"), ("NumPy files", "*.npy")])
|
| 481 |
+
if not file_path:
|
| 482 |
+
return
|
| 483 |
+
|
| 484 |
+
self.status_label.config(text="EggZayn: Kendi veri seti hazırlanıyor...")
|
| 485 |
+
self.progress['value'] = 0
|
| 486 |
+
self.root.update()
|
| 487 |
+
|
| 488 |
+
self.result_text.delete(1.0, tk.END)
|
| 489 |
+
self.result_text.insert(tk.END, "EggZayn: Kendi veri seti hazırlanıyor...\n")
|
| 490 |
+
self.root.update()
|
| 491 |
+
start_time = time.time()
|
| 492 |
+
try:
|
| 493 |
+
if file_path.endswith('.npy'):
|
| 494 |
+
data = np.load(file_path, allow_pickle=True)
|
| 495 |
+
if 'X' not in data or 'Y' not in data:
|
| 496 |
+
raise ValueError("EggZayn: .npy dosyasında 'X' ve 'Y' anahtarları olmalı.")
|
| 497 |
+
X_temp, Y_temp = data['X'], data['Y']
|
| 498 |
+
X_train, X_temp, Y_train, Y_temp = train_test_split(X_temp, Y_temp, test_size=0.3, random_state=42, stratify=Y_temp)
|
| 499 |
+
X_val, X_test, Y_val, Y_test = train_test_split(X_temp, Y_temp, test_size=0.5, random_state=42, stratify=Y_temp)
|
| 500 |
+
else:
|
| 501 |
+
X_train, Y_train, X_val, Y_val, X_test, Y_test = self.model.prepare_custom_data(file_path)
|
| 502 |
+
self.X_train, self.Y_train = X_train, Y_train
|
| 503 |
+
self.X_val, self.Y_val = X_val, Y_val
|
| 504 |
+
self.X_test, self.Y_test = X_test, Y_test
|
| 505 |
+
self.progress['value'] = 33
|
| 506 |
+
self.result_text.insert(tk.END, f"EggZayn: Kendi veri hazır! Süre: {time.time() - start_time:.2f} saniye\n")
|
| 507 |
+
except Exception as e:
|
| 508 |
+
self.result_text.insert(tk.END, f"Hata: Kendi veri hazırlama başarısız: {e}\n")
|
| 509 |
+
messagebox.showerror("Hata", f"EggZayn: Kendi veri hazırlama başarısız: {e}")
|
| 510 |
+
return
|
| 511 |
+
|
| 512 |
+
self.status_label.config(text="EggZayn: Model eğitim aşaması...")
|
| 513 |
+
self.result_text.insert(tk.END, "EggZayn: Model eğitiliyor...\n")
|
| 514 |
+
self.root.update()
|
| 515 |
+
start_time = time.time()
|
| 516 |
+
try:
|
| 517 |
+
self.model.train(self.X_train, self.Y_train, self.X_val, self.Y_val)
|
| 518 |
+
self.progress['value'] = 66
|
| 519 |
+
self.result_text.insert(tk.END, f"EggZayn: Eğitim tamamlandı! Süre: {time.time() - start_time:.2f} saniye\n")
|
| 520 |
+
self.update_training_plot()
|
| 521 |
+
except Exception as e:
|
| 522 |
+
self.result_text.insert(tk.END, f"Hata: Eğitim başarısız: {e}\n")
|
| 523 |
+
messagebox.showerror("Hata", f"EggZayn: Eğitim başarısız: {e}")
|
| 524 |
+
return
|
| 525 |
+
|
| 526 |
+
self.status_label.config(text="EggZayn: Değerlendirme aşaması...")
|
| 527 |
+
self.result_text.insert(tk.END, "EggZayn: Model değerlendiriliyor...\n")
|
| 528 |
+
self.root.update()
|
| 529 |
+
start_time = time.time()
|
| 530 |
+
try:
|
| 531 |
+
loss, accuracy, report, cm = self.model.evaluate(self.X_test, self.Y_test)
|
| 532 |
+
self.progress['value'] = 100
|
| 533 |
+
self.result_text.insert(tk.END, f"EggZayn: Değerlendirme tamamlandı! Süre: {time.time() - start_time:.2f} saniye\n")
|
| 534 |
+
self.result_text.insert(tk.END, f"\nTest Loss: {loss:.4f}\nTest Accuracy: {accuracy:.4f}\n\nClassification Report:\n{report}\n")
|
| 535 |
+
|
| 536 |
+
self.ax2.clear()
|
| 537 |
+
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=self.model.class_names, yticklabels=self.model.class_names, ax=self.ax2)
|
| 538 |
+
self.ax2.set_title('EggZayn Confusion Matrix', color='white')
|
| 539 |
+
self.ax2.set_xlabel('Predicted', color='white')
|
| 540 |
+
self.ax2.set_ylabel('True', color='white')
|
| 541 |
+
self.ax2.tick_params(colors='white')
|
| 542 |
+
self.canvas.draw()
|
| 543 |
+
|
| 544 |
+
self.status_label.config(text="EggZayn: Model hazır ve şölen tamamlandı!")
|
| 545 |
+
except Exception as e:
|
| 546 |
+
self.result_text.insert(tk.END, f"Hata: Değerlendirme başarısız: {e}\n")
|
| 547 |
+
messagebox.showerror("Hata", f"EggZayn: Değerlendirme başarısız: {e}")
|
| 548 |
+
|
| 549 |
+
def update_training_plot(self):
|
| 550 |
+
if self.model.history:
|
| 551 |
+
self.ax1.clear()
|
| 552 |
+
self.ax1.plot(self.model.history.history['accuracy'], label='Training Accuracy', color='cyan')
|
| 553 |
+
self.ax1.plot(self.model.history.history['val_accuracy'], label='Validation Accuracy', color='orange')
|
| 554 |
+
self.ax1.plot(self.model.history.history['loss'], label='Training Loss', color='red')
|
| 555 |
+
self.ax1.plot(self.model.history.history['val_loss'], label='Validation Loss', color='purple')
|
| 556 |
+
self.ax1.set_title('EggZayn Training Metrics', color='white')
|
| 557 |
+
self.ax1.set_xlabel('Epoch', color='white')
|
| 558 |
+
self.ax1.set_ylabel('Value', color='white')
|
| 559 |
+
self.ax1.legend(facecolor='#1A2526', edgecolor='white', loc='best', labelcolor='white')
|
| 560 |
+
self.ax1.tick_params(colors='white')
|
| 561 |
+
self.ax1.set_facecolor('#ECF0F1')
|
| 562 |
+
self.canvas.draw()
|
| 563 |
+
|
| 564 |
+
def predict_new_data(self):
|
| 565 |
+
file_path = filedialog.askopenfilename(title="EEG Sinyal Dosyasını Seç (EDF veya NumPy)",
|
| 566 |
+
filetypes=[("EDF files", "*.edf"), ("NumPy files", "*.npy")])
|
| 567 |
+
if not file_path:
|
| 568 |
+
return
|
| 569 |
+
|
| 570 |
+
self.status_label.config(text="EggZayn: Sinyal analiz ediliyor...")
|
| 571 |
+
self.progress['value'] = 0
|
| 572 |
+
self.root.update()
|
| 573 |
+
|
| 574 |
+
self.result_text.delete(1.0, tk.END)
|
| 575 |
+
self.result_text.insert(tk.END, "EggZayn: Sinyal analiz ediliyor...\n")
|
| 576 |
+
self.root.update()
|
| 577 |
+
try:
|
| 578 |
+
predictions, report = self.model.predict(file_path)
|
| 579 |
+
self.progress['value'] = 100
|
| 580 |
+
self.result_text.insert(tk.END, report)
|
| 581 |
+
|
| 582 |
+
pred_probs = np.array([prob for _, prob in predictions])
|
| 583 |
+
self.ax1.clear()
|
| 584 |
+
self.ax1.bar(self.model.class_names, pred_probs.mean(axis=0), color='skyblue', edgecolor='black')
|
| 585 |
+
self.ax1.set_title('EggZayn Ortalama Tahmin Olasılıkları', color='white')
|
| 586 |
+
self.ax1.set_ylabel('Olasılık', color='white')
|
| 587 |
+
self.ax1.set_ylim(0, 1)
|
| 588 |
+
self.ax1.tick_params(colors='white')
|
| 589 |
+
self.ax1.set_facecolor('#ECF0F1')
|
| 590 |
+
|
| 591 |
+
self.ax2.clear()
|
| 592 |
+
self.canvas.draw()
|
| 593 |
+
|
| 594 |
+
self.status_label.config(text="EggZayn: Analiz tamamlandı!")
|
| 595 |
+
except Exception as e:
|
| 596 |
+
self.result_text.insert(tk.END, f"Hata: Sinyal analizi başarısız: {e}\n")
|
| 597 |
+
messagebox.showerror("Hata", f"EggZayn: Sinyal analizi başarısız: {e}")
|
| 598 |
+
|
| 599 |
+
def run_full_process_thread(self):
|
| 600 |
+
threading.Thread(target=self.full_process, daemon=True).start()
|
| 601 |
+
|
| 602 |
+
def run_custom_train_thread(self):
|
| 603 |
+
threading.Thread(target=self.custom_train, daemon=True).start()
|
| 604 |
+
|
| 605 |
+
if __name__ == '__main__':
|
| 606 |
+
root = tk.Tk()
|
| 607 |
+
app = EggZaynGUI(root)
|
| 608 |
+
root.mainloop()
|
fingerprint.pb
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:97b938a5506ba18e906aa8bf880ce676894a47dc305577ac9ea0b547a5baec9e
|
| 3 |
+
size 57
|
keras_metadata.pb
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:114cf365bc24bddabe56941ad3e5e28b57f38e97fdf60edf74875cd1dc5648d9
|
| 3 |
+
size 143923
|
saved_model.pb
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d284727ea960b5dde9af51832993c534c4662f9c40fa0f059062492c38cf0b7c
|
| 3 |
+
size 1212002
|
test.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from tensorflow import keras
|
| 3 |
+
|
| 4 |
+
# Modeli yükle
|
| 5 |
+
model = keras.models.load_model('EggZayn_final.h9_4')
|
| 6 |
+
|
| 7 |
+
# Test verilerini yükle
|
| 8 |
+
X_test = np.load('X_test.npy')
|
| 9 |
+
Y_test = np.load('Y_test.npy')
|
| 10 |
+
|
| 11 |
+
# İlk 20 örnek için tahmin yap
|
| 12 |
+
predictions = model.predict(X_test[:20])
|
| 13 |
+
|
| 14 |
+
# "0" sınıfını penalize et
|
| 15 |
+
adjusted_predictions = predictions.copy()
|
| 16 |
+
adjusted_predictions[:, 0] *= 0.7 # "0" sınıfını %30 azalt
|
| 17 |
+
|
| 18 |
+
# Eşik ayarı (%20, daha düşük eşik)
|
| 19 |
+
threshold = 0.2
|
| 20 |
+
predicted_classes = np.where(np.max(adjusted_predictions, axis=1) > threshold, np.argmax(adjusted_predictions, axis=1), -1)
|
| 21 |
+
print(f"Düzeltilmiş Tahminler (Eşik: {threshold}): {predicted_classes}")
|
| 22 |
+
print(f"Gerçek Etiketler: {Y_test[:20]}")
|
variables.data-00000-of-00001
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a89ef53c500b6981bc484c09c112c2ab89d7b1666e7082d056aaedd1e5109676
|
| 3 |
+
size 1503722
|
variables.index
ADDED
|
Binary file (13.1 kB). View file
|
|
|