bai-6-Emotion
1
5 languages
license:cc-by-nc-sa-4.0
by
Neurazum
Other
OTHER
New
0 downloads
Early-stage
Edge AI:
Mobile
Laptop
Server
Unknown
Mobile
Laptop
Server
Quick Summary
bai-6 Emotion modeli, EEG ve iEEG tarafından toplanan veriler ile eğitilen bir detaylı duygu sınıflandırma modelidir.
Code Examples
Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Kullanım / Usagepython
import numpy as np
import matplotlib.pyplot as plt
import mne
from matplotlib.animation import FuncAnimation
from tensorflow.keras.models import load_model
import joblib
class EEGMonitor:
def __init__(self, model_path, scaler_path):
self.model = load_model(model_path)
self.scaler = joblib.load(scaler_path)
self.ch_names = ['T7', 'C3', 'Cz', 'C4', 'T8', 'Pz']
self.fs = 1000 # Örnekleme frekansı / Sampling frequency
self.buffer_size = 1000 # 1 saniyelik buffer / 1 second buffer
self.raw_buffer = np.zeros((6, self.buffer_size))
self.feature_contributions = {ch: [] for ch in self.ch_names}
# Elektrot pozisyonları (10-20 sistemi) / Electrode positions (10-20 system)
self.montage = mne.channels.make_standard_montage('standard_1020')
self.fig = plt.figure(figsize=(15, 10))
self.setup_plots()
def setup_plots(self):
self.ax1 = self.fig.add_subplot(223)
self.ax1.set_title("Canlı EEG Sinyalleri / Live EEG Signals")
self.ax1.set_xlabel("Zaman (ms) / Time (ms)")
self.ax1.set_ylabel("Amplitüd (µV) / Amplitude (µV)")
self.ax2 = self.fig.add_subplot(221)
self.ax2.set_title("Elektrot Konumları / Electrode Locations")
self.ax3 = self.fig.add_subplot(224)
self.ax3.set_title("Elektrot Katkı Oranları / Electrode Contribution Ratios")
self.ax3.set_ylim(0, 1)
self.ax4 = self.fig.add_subplot(222)
self.ax4.set_title("Duygu Tahmin Olasılıkları / Emotion Prediction Probabilities")
self.ax4.set_ylim(0, 1)
plt.tight_layout()
def generate_synthetic_data(self):
"""Sentetik EEG verisi üretir (6 kanal x 1000 örnek) / Generates synthetic EEG data (6 channels x 1000 samples)"""
noise = np.random.normal(0, 5e-6, (6, self.buffer_size))
t = np.linspace(0, 1, self.buffer_size)
noise[1] += 2e-6 * np.sin(2 * np.pi * 10 * t)
return noise
def update_buffer(self, new_data):
"""Buffer'ı kaydırmalı olarak günceller / Updates the buffer with new data by rolling"""
self.raw_buffer = np.roll(self.raw_buffer, -new_data.shape[1], axis=1)
self.raw_buffer[:, -new_data.shape[1]:] = new_data
def calculate_channel_contributions(self, features):
"""Her elektrotun tahmindeki katkısını hesaplar / Calculates the contribution of each electrode to the prediction"""
contributions = np.zeros(6)
for i in range(6):
channel_weights = self.model.layers[0].get_weights()[0][i * 6:(i + 1) * 6]
contributions[i] = np.mean(np.abs(channel_weights))
return contributions / np.sum(contributions)
def update_plot(self, frame):
new_data = self.generate_synthetic_data()
self.update_buffer(new_data)
features = self.extract_features(self.raw_buffer)
scaled_features = self.scaler.transform([features])
probs = self.model.predict(scaled_features, verbose=0)[0]
contributions = self.calculate_channel_contributions(features)
self.update_eeg_plot()
self.update_topomap()
self.update_contributions(contributions)
self.update_probabilities(probs)
def update_eeg_plot(self):
self.ax1.clear()
for i in range(6):
offset = i * 20e-6
self.ax1.plot(self.raw_buffer[i] + offset, label=self.ch_names[i])
self.ax1.legend(loc='upper right')
def update_topomap(self):
self.ax2.clear()
info = mne.create_info(self.ch_names, self.fs, 'eeg')
evoked = mne.EvokedArray(self.raw_buffer.mean(axis=1, keepdims=True), info)
evoked.set_montage(self.montage)
mne.viz.plot_topomap(evoked.data[:, 0], evoked.info, axes=self.ax2, show=False)
def update_contributions(self, contributions):
self.ax3.clear()
self.ax3.barh(self.ch_names, contributions, color='skyblue')
for i, v in enumerate(contributions):
self.ax3.text(v, i, f"{v * 100:.1f}%", color='black')
def update_probabilities(self, probs):
emotions = ['Mutlu / Happy', 'Kızgın / Angry', 'Üzgün / Sad', 'Sakin / Calm']
self.ax4.clear()
bars = self.ax4.barh(emotions, probs, color=['green', 'red', 'blue', 'purple'])
for bar in bars:
width = bar.get_width()
self.ax4.text(width, bar.get_y() + 0.2, f"{width * 100:.1f}%", ha='left')
def extract_features(self, data):
"""6 kanal için özellik çıkarımı / Feature extraction for 6 channels"""
features = []
for channel in data:
features.extend([
np.mean(channel),
np.std(channel),
np.ptp(channel),
np.sum(np.abs(np.diff(channel))),
np.median(channel),
np.percentile(np.abs(channel), 95)
])
return np.array(features)
def start_monitoring(self):
anim = FuncAnimation(self.fig, self.update_plot, interval=100)
plt.show()
if __name__ == "__main__":
monitor = EEGMonitor(
model_path='model/path/bai-6 Emotion.h5',
scaler_path='scaler/path/bai-6_scaler.save'
)
monitor.start_monitoring()Deploy This Model
Production-ready deployment in minutes
Together.ai
Instant API access to this model
Production-ready inference API. Start free, scale to millions.
Try Free APIReplicate
One-click model deployment
Run models in the cloud with simple API. No DevOps required.
Deploy NowDisclosure: We may earn a commission from these partners. This helps keep LLMYourWay free.