1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
| import torch import torch.nn as nn import numpy as np from scipy import signal as sig
class UnifiedEEGFeatureExtractor(nn.Module): """ 统一EEG特征提取器 目标:提取跨被试通用的EEG特征 关键:使用域自适应技术,减少个体差异 参考: Ammar et al., Electronics 2026 """ def __init__(self, num_channels=14, fs=128, num_classes=3): super().__init__() self.num_channels = num_channels self.fs = fs self.spatial_filter = nn.Conv2d(1, 32, (num_channels, 1)) self.temporal_filter = nn.Conv2d(32, 64, (1, 25), padding=(0, 12)) self.domain_adapt = nn.Sequential( nn.Linear(64 * 128, 256), nn.ReLU(), nn.Dropout(0.5), nn.Linear(256, 128), nn.ReLU() ) self.classifier = nn.Sequential( nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, num_classes) ) def forward(self, x): """ Args: x: (B, 1, 14, 128) - 14通道, 1秒@128Hz Returns: logits: (B, 3) """ x = self.spatial_filter(x) x = torch.relu(x) x = self.temporal_filter(x) x = torch.relu(x) x = x.flatten(1) x = self.domain_adapt(x) return self.classifier(x)
class LeakageFreePipeline: """ 防数据泄露的实验Pipeline 论文核心贡献之一:严格的数据隔离协议 """ def __init__(self): self.train_subjects = [] self.test_subjects = [] def leave_one_subject_out(self, all_subjects): """ 留一被试交叉验证(LOSOCV) 关键:训练集中完全不包含测试被试的任何数据 包括:不同时段、不同会话的数据 """ results = [] for test_subj in all_subjects: train_subs = [s for s in all_subjects if s != test_subj] train_data = self.load_data(train_subs) test_data = self.load_data([test_subj]) model = UnifiedEEGFeatureExtractor() self.train(model, train_data) acc = self.evaluate(model, test_data) results.append((test_subj, acc)) return results def check_leakage(self, train_data, test_data): """检查数据泄露""" train_subj = set(train_data['subject']) test_subj = set(test_data['subject']) assert len(train_subj & test_subj) == 0, "数据泄露:训练/测试有被试重叠" return True
|