Spaces:
Sleeping

NeuroSense / predict_eeg.py
FYDP-HSZ's picture
Create predict_eeg.py
d50b4e5 verified
Raw History Blame Contribute Delete
1.65 kB
def predict_eeg(csv_file, model, label_classes=None, window_size=200, stride=100):
"""
Predict EEG emotion classes for a CSV file.
Parameters:
csv_file: path or file object for EEG CSV
model: loaded Keras CNN-GRU model
label_classes: list of class names in the same order as model output
window_size: number of samples per window (default 200 → 2s)
stride: step size for overlapping windows (default 100 → 50% overlap)
Returns:
pred_labels: list of predicted class names (one per window)
window_timestamps: start timestamps corresponding to each window
class_percentages: dict of {class_name: percentage_of_windows}
"""
# 1. Preprocess EEG
X_windows, window_timestamps = preprocess_eeg(csv_file, window_size, stride)
if len(X_windows) == 0:
raise ValueError("No valid EEG windows could be created from this CSV.")
# 2. Predict probabilities
preds = model.predict(X_windows, verbose=0)
# 3. Get integer class predictions
pred_ints = np.argmax(preds, axis=1)
# 4. Map to label names
if label_classes is None:
# fallback default order (must match your training)
label_classes = ["focused", "funny", "meditation", "normal", "sad"]
pred_labels = [label_classes[i] for i in pred_ints]
# 5. Count per-class percentages
from collections import Counter
counts = Counter(pred_labels)
total = len(pred_labels)
class_percentages = {cls: counts.get(cls,0)/total*100 for cls in label_classes}
return pred_labels, window_timestamps, class_percentages